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) {
1780 settle_in(task, verdict, detail, max_attempts, &PHRASES_EN)
1781}
1782
1783fn settle_in(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize, p: &Phrases) {
1785 if verdict.parked {
1791 task.park(detail);
1792 return;
1793 }
1794 match verdict.status {
1795 RunStatus::Merged | RunStatus::Ready
1796 if task.pr_recovery.as_ref().is_some_and(|s| {
1797 s.disposition != Some(crate::pr_recovery::Disposition::Review)
1798 }) =>
1799 {
1800 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()));
1801 }
1802 RunStatus::Merged | RunStatus::Ready => task.succeed(),
1803 RunStatus::AlreadyInBase => task.already_landed(detail),
1804 RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1805 RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1806 task.stall(detail)
1807 }
1808 RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1809 RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1810 RunStatus::Blocked => task.fail(detail, max_attempts),
1811 RunStatus::VerifiedNoop => task.handed_off(detail),
1812 other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1813 }
1814}
1815
1816pub fn supersede_prior_runs(task: &Task, home: &Path) {
1865 let now = Timestamp::now();
1866 let last_run_succeeded = task
1873 .runs
1874 .last()
1875 .and_then(|id| RunState::load_under(id, home).ok())
1876 .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
1877 for id in task.superseded_attempts(last_run_succeeded) {
1878 let mut state = match RunState::load_under(id, home) {
1879 Ok(s) => s,
1880 Err(e) => {
1881 tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
1882 continue;
1883 }
1884 };
1885 if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
1886 continue;
1887 }
1888 let daemon_claims = is_working_on(home, id, now);
1889 if state.liveness(daemon_claims) == Liveness::Live {
1890 continue;
1891 }
1892 state.status = RunStatus::Superseded;
1893 if let Err(e) = state.save_under(home) {
1894 tracing::warn!("could not mark run {id} superseded: {e:#}");
1895 }
1896 }
1897}
1898
1899fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
1921 for task in queue.list() {
1922 if task.status != TaskStatus::Done || task.runs.len() < 2 {
1923 continue;
1924 }
1925 supersede_prior_runs(&task, home);
1926 }
1927}
1928
1929fn settle_and_diagnose(
1936 task: &mut Task,
1937 verdict: Verdict,
1938 detail: &str,
1939 max_attempts: usize,
1940 state: &RunState,
1941) {
1942 let p = phrases(&state.config.graph.language);
1943 if let Some(d) = &state.merge_decision {
1946 use crate::merge_decision as md;
1947 if task.runs.last().is_some_and(|id| id != &state.id) {
1948 return;
1949 }
1950 if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
1951 task.succeed();
1952 } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
1953 if state.liveness(false) != Liveness::Dead {
1954 task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
1955 return;
1956 }
1957 let replacement = md::Replacement {
1958 question: d.question.clone(),
1959 run: state.id.clone(),
1960 pr: d.target.pr.clone(),
1961 agent: agent.to_owned(),
1962 context: format!(
1963 "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
1964 d.target.pr,
1965 state.id,
1966 serde_json::to_string(&state.reviews).unwrap_or_default()
1967 ),
1968 };
1969 task.requeue();
1970 task.pr_recovery = None;
1971 task.review_of = None;
1972 task.replacement = Some(replacement);
1973 } else {
1974 task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
1975 format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
1976 } 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())) }));
1977 }
1978 task.mark_action_applied(&d.question);
1979 if let Some(pass) = state.passes.last() {
1980 task.record_pass_at(
1981 &state.id,
1982 pass.index,
1983 Some(pass.started_at),
1984 task.attempts,
1985 None,
1986 );
1987 }
1988 return;
1989 }
1990 if let Some(replacement) = &task.replacement
1991 && !state.parked
1992 && state.resource_block.is_none()
1993 && (state.viable().is_empty()
1994 || (state.status == RunStatus::Blocked && state.tally.is_none()))
1995 {
1996 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)));
1997 return;
1998 }
1999 let attempts_before = task.attempts;
2000 if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
2007 task.notice_cause(
2008 &format!("resource:{}:{}", block.kind, block.node),
2009 None,
2010 None,
2011 );
2012 task.last_error = Some(detail.to_owned());
2013 task.diagnostic = None;
2014 task.attempts = task.attempts.saturating_sub(1);
2015 if block.kind == "disk pressure" {
2016 task.hold_machine(Some(format!(
2017 "{}{}",
2018 crate::disk::RUNNING_PRESSURE,
2019 block.detail
2020 )));
2021 } else {
2022 task.hold_machine(Some(format!(
2023 "{}{}; no attempt was spent; resume to retry the affected operation",
2024 crate::cache::RESOURCE_HOLD,
2025 block.description()
2026 )));
2027 }
2028 if let Some(pass) = state.passes.last() {
2029 task.record_pass_at(
2030 &state.id,
2031 pass.index,
2032 Some(pass.started_at),
2033 attempts_before,
2034 None,
2035 );
2036 }
2037 return;
2038 }
2039 if let Some(hold) = state.land_unrelated.as_ref().filter(|hold| {
2040 state.parked
2041 && state.status == RunStatus::Landing
2042 && state
2043 .pr_pushed_head
2044 .as_ref()
2045 .is_none_or(|h| h == &hold.head)
2046 && task.runs.last() == Some(&state.id)
2047 }) {
2048 let pass = state.passes.last().map_or(0, |p| p.index);
2051 if !task
2052 .passes
2053 .iter()
2054 .any(|p| p.run == state.id && p.pass_index == pass)
2055 {
2056 task.attempts = task.attempts.saturating_sub(1);
2057 }
2058 task.hold_machine(Some(format!(
2059 "[ci-unrelated] CI failure reproduced on base; owner question {}",
2060 hold.question
2061 )));
2062 task.last_error = Some(detail.to_owned());
2063 task.diagnostic = None;
2064 task.record_pass_at(
2065 &state.id,
2066 pass,
2067 state.passes.last().map(|p| p.started_at),
2068 attempts_before,
2069 Some(crate::run::ParkCause::Question),
2070 );
2071 return;
2072 }
2073 let unresolved = task.hold_notice_cause.clone();
2074 if state.base_sync_blocked() {
2075 task.hold_machine(Some(detail.to_owned()));
2077 task.last_error = Some(detail.to_owned());
2078 } else if !verdict.parked
2079 && task
2080 .pr_recovery
2081 .as_ref()
2082 .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
2083 && matches!(
2084 verdict.status,
2085 RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
2086 )
2087 {
2088 if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
2089 task.succeed();
2090 } else {
2091 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()));
2092 }
2093 } else if !verdict.parked
2094 && task.pr_recovery.is_some()
2095 && matches!(
2096 verdict.status,
2097 RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
2098 )
2099 && !verdict.quota_hit
2100 {
2101 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.")));
2102 } else {
2103 settle_in(task, verdict, detail, max_attempts, p);
2104 }
2105 if !verdict.parked
2106 && !verdict.quota_hit
2107 && matches!(
2108 verdict.status,
2109 RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
2110 )
2111 {
2112 task.recovery_failed(state);
2113 }
2114 if state.prep_failure.is_some() {
2115 task.hold_notice_cause = unresolved;
2118 task.startup_notice_cause("startup-candidates");
2119 }
2120 if let Some(pass) = state.passes.last() {
2123 let parked = match &pass.end {
2124 Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2125 _ => None,
2126 };
2127 task.record_pass_at(
2128 &state.id,
2129 pass.index,
2130 Some(pass.started_at),
2131 attempts_before,
2132 parked,
2133 );
2134 }
2135 if task.status == TaskStatus::Held {
2136 if state.base_sync_blocked() {
2137 task.base_sync_notice(state);
2138 } else if state.prep_failure.is_none() {
2139 task.notice_cause(
2140 label(verdict.status),
2141 Some(&state.id),
2142 state.passes.last().map(|p| p.index),
2143 );
2144 }
2145 task.diagnostic = diagnostic(state);
2146 note_open_question(task, &state.id, p);
2147 }
2148}
2149
2150fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2165 let Some(home) = crate::run::try_home() else {
2166 return;
2167 };
2168 let open = Questions::at(home.join("questions")).open_for(run);
2169 let Some(q) = open.first() else {
2170 return;
2171 };
2172 let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2173 decisions.sort_unstable();
2174 task.notice_cause(
2175 &format!("questions:{}", decisions.join(",")),
2176 Some(run),
2177 None,
2178 );
2179 let base = task.hold_reason.clone().unwrap_or_default();
2180 task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2181}
2182
2183fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2194 match last_run {
2195 Some(state) => {
2196 let verdict = Verdict {
2197 status: state.status,
2198 left_pr: state.pr.is_some(),
2199 quota_hit: !state.quota.is_empty(),
2200 parked: state.parked,
2201 no_viable_candidates: state.viable().is_empty(),
2202 };
2203 let detail = format!(
2204 "{}{}",
2205 phrases(&state.config.graph.language).recovered_running,
2206 describe(&state)
2207 );
2208 settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2209 }
2210 None => {
2211 let why = phrases(language).no_run_to_recover;
2214 task.last_error = Some(why.to_owned());
2215 task.notice_cause("missing-run", None, None);
2218 task.hold_machine(Some(why.to_owned()));
2219 }
2220 }
2221}
2222
2223fn reclaim_orphaned_running(
2245 queue: &Queue,
2246 max_attempts: usize,
2247 live_workers: &std::collections::BTreeSet<String>,
2248) -> Vec<String> {
2249 let mut reclaimed = Vec::new();
2250 for listed in queue.list() {
2251 if listed.status != TaskStatus::Running || live_workers.contains(&listed.id) {
2252 continue;
2253 }
2254 let Ok(_claim) = queue.claim(&listed.id) else {
2255 continue;
2256 };
2257 let Ok(mut task) = queue.get(&listed.id) else {
2261 continue;
2262 };
2263 if task.status != TaskStatus::Running {
2264 continue;
2265 }
2266 let last_run = task.runs.last().and_then(|id| RunState::load(id).ok());
2267 if let Some(state) = &last_run
2277 && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2278 {
2279 tracing::warn!("abandon questions for {}: {e:#}", state.id);
2280 }
2281 let language = if last_run.is_none() {
2282 language_of(&task, Path::new("."))
2283 } else {
2284 String::new()
2285 };
2286 reclaim(&mut task, last_run, max_attempts, &language);
2287 if task.status == TaskStatus::Done {
2288 supersede_prior_runs(&task, &crate::run::home());
2289 }
2290 record(queue, &mut task);
2291 reclaimed.push(task.id.clone());
2292 }
2293 reclaimed
2294}
2295
2296fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2328 reclaim_abandoned_runs_with(
2329 home,
2330 now,
2331 crate::proc::pid_status,
2332 crate::proc::process_started_at,
2333 )
2334}
2335
2336fn reclaim_abandoned_runs_with<F, G>(
2342 home: &Path,
2343 now: Timestamp,
2344 query: F,
2345 identity: G,
2346) -> Vec<String>
2347where
2348 F: Fn(u32) -> Option<bool>,
2349 G: Fn(u32) -> Option<String>,
2350{
2351 let mut abandoned = Vec::new();
2352 for entry in std::fs::read_dir(home.join("runs"))
2353 .into_iter()
2354 .flatten()
2355 .flatten()
2356 {
2357 let id = entry.file_name().to_string_lossy().into_owned();
2358 if !crate::run::is_run_id(&id) {
2359 continue;
2360 }
2361 let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2364 continue;
2365 };
2366 let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2374 continue;
2375 };
2376 let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2377 continue;
2378 };
2379 if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2380 continue;
2381 }
2382 let daemon_claims = is_working_on(home, &id, now);
2394 if state.liveness_under_with(home, daemon_claims, &query, &identity)
2395 != crate::run::Liveness::Dead
2396 {
2397 continue;
2398 }
2399 state.abandon("daemon");
2400 if let Err(e) = state.save_under(home) {
2401 tracing::warn!("could not persist abandoned run {id}: {e:#}");
2402 continue;
2403 }
2404 if let Some(notice) = notices::run_ended(&state) {
2407 notices::raise_in(home, notice);
2408 }
2409 if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2417 tracing::warn!("abandon questions for {id}: {e:#}");
2418 }
2419 abandoned.push(id);
2420 }
2421 abandoned
2422}
2423
2424#[derive(Debug, Clone, Serialize, Deserialize)]
2425struct TaskWorker {
2426 opts: Opts,
2427 queue: PathBuf,
2428 task: String,
2429 #[serde(default)]
2430 lane: PermitKind,
2431 #[serde(default)]
2432 standalone: bool,
2433}
2434
2435fn task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2436 Ok(crate::worker::active(home)?
2437 .into_iter()
2438 .filter(|job| job.kind == "task")
2439 .collect())
2440}
2441
2442fn owned_task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2443 task_jobs(home)?
2444 .into_iter()
2445 .filter_map(
2446 |job| match serde_json::from_value::<TaskWorker>(job.payload.clone()) {
2447 Ok(request) if !request.standalone => Some(Ok(job)),
2448 Ok(_) => None,
2449 Err(error) => Some(Err(error.into())),
2450 },
2451 )
2452 .collect()
2453}
2454
2455#[must_use]
2457pub fn managed(home: &Path) -> bool {
2458 match crate::worker::active(home) {
2459 Err(error) => {
2460 tracing::error!("cannot determine scheduler ownership: {error:#}");
2461 true
2462 }
2463 Ok(jobs) if jobs.iter().any(|j| j.kind == "scheduler") => true,
2464 Ok(_) => {
2465 read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2466 && crate::worker::try_lease(home, "scheduler").map_or(true, |lease| lease.is_none())
2467 }
2468 }
2469}
2470
2471pub async fn spawn_detached(home: &Path, opts: &Opts) -> Result<crate::worker::Job> {
2473 anyhow::ensure!(
2474 crate::worker::control(home, "scheduler")?.is_none() || !managed(home),
2475 "the scheduler is stopping; wait for retirement before starting it again"
2476 );
2477 crate::worker::spawn(
2478 home,
2479 "scheduler",
2480 "scheduler",
2481 serde_json::to_value(opts.absolute()?)?,
2482 )
2483 .await
2484}
2485
2486fn park_request_path(home: &Path, job: &crate::worker::Job) -> PathBuf {
2487 home.join("worker-parks").join(format!("{}.json", job.id))
2488}
2489
2490fn request_task_park(
2491 home: &Path,
2492 job: &crate::worker::Job,
2493 cause: crate::run::ParkCause,
2494) -> Result<()> {
2495 let path = park_request_path(home, job);
2496 std::fs::create_dir_all(path.parent().context("worker park directory")?)?;
2497 std::fs::write(path, serde_json::to_vec(&cause)?)?;
2498 crate::worker::request(home, &job.key, crate::worker::Control::Park)
2499}
2500
2501pub fn request_control(home: &Path, control: crate::worker::Control) -> Result<()> {
2503 if control == crate::worker::Control::Park {
2504 for job in owned_task_jobs(home)? {
2505 request_task_park(home, &job, crate::run::ParkCause::Operator)?;
2506 }
2507 }
2508 crate::worker::request(home, "scheduler", control)
2509}
2510
2511pub async fn restart_detached(home: &Path) -> Result<()> {
2513 let active = crate::worker::active(home)?;
2514 let prior = active.into_iter().find(|job| job.kind == "scheduler");
2515 if prior.is_none() && !managed(home) {
2516 return Ok(());
2517 }
2518 let opts: Opts = match prior {
2519 Some(job) => serde_json::from_value(job.payload)?,
2520 None => serde_json::from_slice(&std::fs::read(home.join("scheduler-options.json"))?)?,
2521 };
2522 request_control(home, crate::worker::Control::Stop)?;
2523 loop {
2524 let reserved = crate::worker::active(home)?
2525 .iter()
2526 .any(|job| job.kind == "scheduler");
2527 if !reserved && crate::worker::try_lease(home, "scheduler")?.is_some() {
2528 break;
2529 }
2530 tokio::time::sleep(Duration::from_millis(100)).await;
2531 }
2532 spawn_detached(home, &opts).await?;
2533 Ok(())
2534}
2535
2536pub async fn run_scheduler_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2538 let opts: Opts = serde_json::from_value(payload)?;
2539 let _ = home;
2540 serve_until(opts, Stop::new()).await
2541}
2542
2543pub async fn run_task_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2545 let request: TaskWorker = serde_json::from_value(payload)?;
2546 let queue = Queue::at(request.queue);
2547 let key = format!("task:{}", request.task);
2548 let job = task_jobs(home)?
2549 .into_iter()
2550 .find(|job| job.key == key)
2551 .context("task worker reservation is missing")?;
2552 let park_path = park_request_path(home, &job);
2553 let _claim = loop {
2556 match queue.claim(&request.task) {
2557 Ok(claim) => break claim,
2558 Err(e) if e.chain().any(|c| c.is::<std::io::Error>()) => {
2561 return Err(e.context("claim the task for its worker"));
2562 }
2563 Err(_) => {
2564 sweep_stale_claims(&queue, STALE_CLAIM);
2565 tokio::time::sleep(Duration::from_millis(50)).await;
2566 }
2567 }
2568 };
2569 let mut task = queue.get(&request.task)?;
2570 if !task.status.runnable()
2571 || (!request.standalone
2572 && request.lane
2573 != permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent))
2574 {
2575 return Ok(());
2576 }
2577 let stop = Stop::new();
2578 let watcher = {
2579 let home = home.to_path_buf();
2580 let stop = stop.clone();
2581 let park_path = park_path.clone();
2582 tokio::spawn(async move {
2583 loop {
2584 if crate::worker::control(&home, &key).ok().flatten().is_some() {
2585 let cause = std::fs::read(&park_path)
2586 .ok()
2587 .and_then(|body| serde_json::from_slice(&body).ok())
2588 .unwrap_or(crate::run::ParkCause::Operator);
2589 stop.park(cause);
2590 return;
2591 }
2592 tokio::time::sleep(Duration::from_millis(200)).await;
2593 }
2594 })
2595 };
2596 let quota = if request.standalone {
2597 run_claimed_until(&request.opts, &queue, &mut task, &stop).await
2598 } else {
2599 let status = Arc::new(Mutex::new(Status::new()));
2600 Box::pin(attempt(
2601 &request.opts,
2602 &queue,
2603 &status,
2604 &stop,
2605 crate::graph::Pause::new(),
2606 &mut task,
2607 ))
2608 .await
2609 };
2610 watcher.abort();
2611 let _ = std::fs::remove_file(park_path);
2612 persist_cooldown(home, "a).await?;
2613 Ok(())
2614}
2615
2616pub async fn spawn_claimed(
2619 home: &Path,
2620 opts: &Opts,
2621 queue: &Queue,
2622 task: &Task,
2623 claim: crate::queue::Claim,
2624) -> Result<crate::worker::Job> {
2625 let request = TaskWorker {
2626 opts: opts.absolute()?,
2627 queue: std::path::absolute(queue.root())?,
2628 task: task.id.clone(),
2629 lane: permit_kind(land_resume_state(task) == LandResume::Ready, task.urgent),
2630 standalone: true,
2631 };
2632 let job = crate::worker::spawn(
2633 home,
2634 "task",
2635 &format!("task:{}", task.id),
2636 serde_json::to_value(request)?,
2637 )
2638 .await?;
2639 drop(claim);
2640 Ok(job)
2641}
2642
2643pub async fn run_detached_claimed(
2646 opts: &Opts,
2647 queue: &Queue,
2648 task: &mut Task,
2649 claim: crate::queue::Claim,
2650) -> Result<()> {
2651 let home = crate::run::home();
2652 let job = spawn_claimed(&home, opts, queue, task, claim).await?;
2653 loop {
2654 crate::worker::active(&home)?;
2657 let current = crate::worker::get(&home, &job.id)?;
2658 if matches!(
2659 current.status,
2660 crate::worker::Status::Finished | crate::worker::Status::Failed
2661 ) {
2662 *task = queue.get(&task.id)?;
2663 anyhow::ensure!(
2664 current.status != crate::worker::Status::Failed,
2665 "task worker failed: {}",
2666 current.result.as_deref().unwrap_or("unknown failure")
2667 );
2668 return Ok(());
2669 }
2670 tokio::time::sleep(Duration::from_millis(200)).await;
2671 }
2672}
2673
2674async fn persist_cooldown(home: &Path, quota: &[QuotaLoss]) -> Result<()> {
2675 if let Some(until) = cooldown_until(quota, Timestamp::now()) {
2676 let _lease = loop {
2677 if let Some(lease) = crate::worker::try_lease(home, "task-quota-cooldown")? {
2678 break lease;
2679 }
2680 tokio::time::sleep(Duration::from_millis(10)).await;
2681 };
2682 if read_cooldown(home)?.is_none_or(|previous| previous < until) {
2683 let path = home.join("task-quota-cooldown.json");
2684 let temporary = path.with_extension("json.tmp");
2685 std::fs::write(&temporary, serde_json::to_vec(&until)?)?;
2686 std::fs::rename(temporary, path)?;
2687 }
2688 }
2689 Ok(())
2690}
2691
2692fn read_cooldown(home: &Path) -> Result<Option<Timestamp>> {
2693 match std::fs::read(home.join("task-quota-cooldown.json")) {
2694 Ok(body) => Ok(Some(serde_json::from_slice(&body)?)),
2695 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
2696 Err(error) => Err(error.into()),
2697 }
2698}
2699
2700pub async fn serve(opts: Opts) -> Result<()> {
2706 tracing::info!(
2707 "automatic update and restart requires magi web; standalone serve does not restart"
2708 );
2709 serve_until(opts, Stop::new()).await
2710}
2711
2712pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
2723 let opts = opts.absolute()?;
2724 let home = crate::run::home();
2725 let _scheduler = crate::worker::try_lease(&home, "scheduler")?
2726 .context("another scheduler already owns this home")?;
2727 if let Some(reading) = read_status(&home)
2728 && legacy_scheduler_running(&reading, Timestamp::now(), std::process::id())
2729 {
2730 bail!("a legacy scheduler is still running; stop it before starting independent dispatch");
2731 }
2732 if !crate::worker::active(&home)?
2733 .iter()
2734 .any(|job| job.kind == "scheduler")
2735 {
2736 crate::worker::clear_control(&home, "scheduler")?;
2737 }
2738 std::fs::write(
2739 home.join("scheduler-options.json"),
2740 serde_json::to_vec(&opts)?,
2741 )?;
2742 let control = {
2743 let home = home.clone();
2744 let stop = stop.clone();
2745 tokio::spawn(async move {
2746 loop {
2747 match crate::worker::control(&home, "scheduler").ok().flatten() {
2748 Some(crate::worker::Control::Park) => {
2749 let _ = request_control(&home, crate::worker::Control::Park);
2750 stop.park(crate::run::ParkCause::Operator);
2751 break;
2752 }
2753 Some(crate::worker::Control::Stop) => {
2754 stop.stop();
2755 break;
2756 }
2757 None => {}
2758 }
2759 tokio::time::sleep(Duration::from_millis(100)).await;
2760 }
2761 })
2762 };
2763 let signal = {
2764 let stop = stop.clone();
2765 tokio::spawn(async move {
2766 if tokio::signal::ctrl_c().await.is_ok() {
2767 stop.stop();
2768 tracing::info!("scheduler shutdown requested; independent workers continue");
2769 }
2770 })
2771 };
2772
2773 let worktrees_root = opts
2774 .worktrees_root
2775 .clone()
2776 .unwrap_or_else(crate::run::default_worktree_root);
2777 let outcome = drive(
2778 &opts,
2779 &Queue::open(),
2780 &status_path(),
2781 &crate::run::home(),
2782 &worktrees_root,
2783 &stop,
2784 )
2785 .await;
2786
2787 signal.abort();
2788 control.abort();
2789 outcome
2790}
2791
2792async fn drive(
2805 opts: &Opts,
2806 queue: &Queue,
2807 status_file: &Path,
2808 home: &Path,
2809 worktrees_root: &Path,
2810 stop: &Stop,
2811) -> Result<()> {
2812 let recovery_cfg = prepare(&opts.repo, opts).ok();
2820 let daemon_cfg = recovery_cfg
2821 .as_ref()
2822 .map(|c| c.daemon.clone())
2823 .unwrap_or_default();
2824 let reconciled = crate::driver::reconcile(home);
2825 if !reconciled.is_empty() {
2826 tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
2827 }
2828 let mut initial_status = Status::new();
2829 let owned = owned_task_jobs(home)?;
2830 initial_status.current = current_work(home, Timestamp::now())
2831 .into_iter()
2832 .filter(|current| {
2833 owned
2834 .iter()
2835 .any(|job| job.key.strip_prefix("task:") == Some(current.task.as_str()))
2836 })
2837 .collect();
2838 initial_status.idle = initial_status.current.is_empty();
2839 initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
2840 recovery_cfg.as_ref(),
2841 daemon_cfg.max_deputies,
2842 ));
2843 let status = Arc::new(Mutex::new(initial_status));
2844 write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
2845 let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
2846
2847 let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
2853
2854 tracing::info!(
2855 "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
2856 queue.root().display(),
2857 opts.poll.as_secs(),
2858 opts.max_attempts,
2859 concurrency,
2860 if daemon_cfg.pause_for_interrupts {
2861 ", interrupts enabled"
2862 } else {
2863 ""
2864 }
2865 );
2866
2867 let outcome = tokio::select! {
2868 outcome = poll(opts, queue, &status, home, worktrees_root, stop, DispatchLimits {
2869 max_concurrent: concurrency,
2870 pause_for_interrupts: daemon_cfg.pause_for_interrupts,
2871 recovery_cfg,
2872 }) => outcome,
2873 () = async {
2874 while !stop.stopped() {
2875 tokio::time::sleep(Duration::from_millis(25)).await;
2876 }
2877 } => {
2878 if stop.parking() {
2879 request_control(home, crate::worker::Control::Park)?;
2880 }
2881 Ok(())
2882 }
2883 };
2884
2885 stop.busy.store(0, Ordering::SeqCst);
2886 beat.abort();
2887 clear_status_at(status_file);
2888 outcome
2889}
2890
2891pub(crate) fn release_watch_settings_from_config(
2894 home: &Path,
2895 repo: &Path,
2896 cfg: &Config,
2897) -> (Vec<PathBuf>, u64) {
2898 let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
2899 .into_iter()
2900 .map(|r| r.path)
2901 .collect();
2902 let mut known: Vec<PathBuf> = Queue::at(home.join("queue"))
2905 .list()
2906 .into_iter()
2907 .map(|t| t.repo)
2908 .collect();
2909 let runs = home.join("runs");
2910 for id in crate::run::list_ids_in(&runs) {
2911 let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
2912 .ok()
2913 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
2914 .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
2915 known.extend(repo);
2916 }
2917 for k in known {
2918 let k = k.canonicalize().unwrap_or(k);
2919 if k.join(".git").exists() && !paths.contains(&k) {
2920 paths.push(k);
2921 }
2922 }
2923 let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
2924 if !paths.contains(&own) {
2925 paths.push(own);
2926 }
2927 (paths, cfg.daemon.release_stall_minutes)
2928}
2929
2930const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
2932
2933async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
2939 loop {
2940 tokio::time::sleep(HEARTBEAT).await;
2941 let snapshot = {
2942 let mut guard = lock(&status);
2943 guard.updated_at = Timestamp::now();
2944 guard.clone()
2945 };
2946 if let Err(e) = write_status_to(&path, &snapshot) {
2947 tracing::warn!("could not refresh the daemon status file: {e:#}");
2950 }
2951 }
2952}
2953
2954#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2957enum LandResume {
2958 NotLanding,
2961 StillWaiting,
2966 Ready,
2970}
2971
2972fn land_resume_state(task: &Task) -> LandResume {
2976 let Some(run_id) = task.runs.last() else {
2977 return LandResume::NotLanding;
2978 };
2979 let Ok(state) = RunState::load(run_id) else {
2980 return LandResume::NotLanding;
2981 };
2982 if !state.parked {
2983 return LandResume::NotLanding;
2984 }
2985 if state.status == RunStatus::Landing
2986 && state.land_approval.as_ref().is_some_and(|binding| {
2987 ask::Questions::open()
2988 .get(&binding.question)
2989 .is_ok_and(|q| {
2990 q.run == state.id
2991 && q.resolution()
2992 .as_deref()
2993 .is_some_and(crate::merge_decision::stops)
2994 })
2995 })
2996 {
2997 return LandResume::Ready;
2998 }
2999 if !implementers_match(task, &state) {
3000 return LandResume::NotLanding;
3001 }
3002 let node = if state.status == RunStatus::Landing {
3006 land::APPROVAL_NODE
3007 } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
3008 crate::github_text::ASK_NODE
3009 } else {
3010 return LandResume::NotLanding;
3011 };
3012 let store = ask::Questions::open();
3013 let waiting = store
3014 .list()
3015 .into_iter()
3016 .filter(|q| &q.run == run_id && q.node == node)
3017 .max_by(|a, b| a.id.cmp(&b.id));
3018 let Some(mut q) = waiting else {
3019 return LandResume::Ready;
3020 };
3021 if !q.status.open() {
3022 if q.resolution().as_deref() == Some(land::REPAIR) {
3025 return if state.liveness(false) == Liveness::Live {
3026 LandResume::StillWaiting
3027 } else {
3028 LandResume::NotLanding
3029 };
3030 }
3031 return LandResume::Ready;
3032 }
3033 let timeout = Duration::from_secs(state.config.graph.answer_timeout);
3040 let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
3041 if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
3042 q.abandon(format!(
3043 "no answer within {}s of asking",
3044 timeout.as_secs().max(1)
3045 ));
3046 if store.put(&mut q).is_ok() {
3049 return LandResume::Ready;
3050 }
3051 }
3052 LandResume::StillWaiting
3053}
3054
3055const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
3063
3064const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
3076
3077#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3090enum Interrupt {
3091 Idle,
3093 Parking {
3105 parked: Vec<String>,
3106 interrupt_task: String,
3107 },
3108 Running {
3116 parked: Vec<String>,
3117 interrupt_task: String,
3118 },
3119 Resuming { parked: Vec<String> },
3126}
3127
3128fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
3149 match state {
3150 Interrupt::Idle => {
3151 if in_flight.len() != 1 {
3163 return Interrupt::Idle;
3164 }
3165 match runnable.iter().find(|t| t.interrupt) {
3166 Some(t) => Interrupt::Parking {
3167 parked: in_flight.to_vec(),
3168 interrupt_task: t.id.clone(),
3169 },
3170 None => Interrupt::Idle,
3171 }
3172 }
3173 Interrupt::Parking {
3174 parked,
3175 interrupt_task,
3176 } => {
3177 if in_flight.iter().any(|id| parked.contains(id)) {
3178 Interrupt::Parking {
3180 parked,
3181 interrupt_task,
3182 }
3183 } else if in_flight.contains(&interrupt_task) {
3184 Interrupt::Running {
3185 parked,
3186 interrupt_task,
3187 }
3188 } else if runnable.iter().any(|t| t.id == interrupt_task) {
3189 Interrupt::Parking {
3193 parked,
3194 interrupt_task,
3195 }
3196 } else {
3197 Interrupt::Resuming { parked }
3202 }
3203 }
3204 Interrupt::Running {
3205 parked,
3206 interrupt_task,
3207 } => {
3208 if in_flight.contains(&interrupt_task) {
3209 Interrupt::Running {
3210 parked,
3211 interrupt_task,
3212 }
3213 } else {
3214 Interrupt::Resuming { parked }
3220 }
3221 }
3222 Interrupt::Resuming { parked } => {
3223 if in_flight.iter().any(|id| parked.contains(id)) {
3224 Interrupt::Idle
3230 } else if runnable.iter().any(|t| parked.contains(&t.id)) {
3231 Interrupt::Resuming { parked }
3232 } else {
3233 Interrupt::Idle
3236 }
3237 }
3238 }
3239}
3240
3241fn advance_interrupt_tick(
3247 enabled: bool,
3248 state: Interrupt,
3249 in_flight: &[String],
3250 runnable: &[Task],
3251) -> Interrupt {
3252 if !enabled {
3253 return Interrupt::Idle;
3254 }
3255 advance_interrupt(state, in_flight, runnable)
3256}
3257
3258fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
3263 match state {
3264 Interrupt::Idle => candidates,
3265 Interrupt::Parking {
3266 parked,
3267 interrupt_task,
3268 } => {
3269 if in_flight.iter().any(|id| parked.contains(id)) {
3270 Vec::new()
3271 } else {
3272 candidates
3273 .into_iter()
3274 .filter(|t| &t.id == interrupt_task)
3275 .collect()
3276 }
3277 }
3278 Interrupt::Running { .. } => Vec::new(),
3279 Interrupt::Resuming { parked } => candidates
3287 .into_iter()
3288 .find(|t| parked.contains(&t.id))
3289 .into_iter()
3290 .collect(),
3291 }
3292}
3293
3294struct DispatchLimits {
3298 max_concurrent: usize,
3301 pause_for_interrupts: bool,
3303 recovery_cfg: Option<Config>,
3304}
3305
3306#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3315enum PermitKind {
3316 None,
3321 Urgent,
3328 #[default]
3331 Ordinary,
3332}
3333
3334fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
3337 if priority {
3338 PermitKind::None
3339 } else if urgent {
3340 PermitKind::Urgent
3341 } else {
3342 PermitKind::Ordinary
3343 }
3344}
3345
3346fn available_slots(requests: &[TaskWorker], limit: usize) -> (usize, usize) {
3347 let (ordinary, urgent) = requests.iter().filter(|request| !request.standalone).fold(
3348 (0usize, 0usize),
3349 |(ordinary, urgent), request| match request.lane {
3350 PermitKind::Ordinary => (ordinary + 1, urgent),
3351 PermitKind::Urgent => (ordinary, urgent + 1),
3352 PermitKind::None => (ordinary, urgent),
3353 },
3354 );
3355 (
3356 limit.saturating_sub(ordinary),
3357 1usize.saturating_sub(urgent),
3358 )
3359}
3360
3361struct DispatchClaim {
3362 task: Task,
3363 claim: crate::queue::Claim,
3364 permit: Option<tokio::sync::OwnedSemaphorePermit>,
3365}
3366
3367fn claim_dispatch(
3370 queue: &Queue,
3371 candidate: &Task,
3372 cooling_down: bool,
3373 ordinary: &Arc<tokio::sync::Semaphore>,
3374 urgent: &Arc<tokio::sync::Semaphore>,
3375) -> Option<DispatchClaim> {
3376 let Ok(claim) = queue.claim(&candidate.id) else {
3377 tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
3378 return None;
3379 };
3380 let task = match queue.get(&candidate.id) {
3381 Ok(t) if t.status.runnable() => t,
3382 Ok(_) => return None,
3383 Err(e) => {
3384 tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
3385 return None;
3386 }
3387 };
3388 let resume = land_resume_state(&task);
3389 if resume == LandResume::StillWaiting {
3390 return None;
3391 }
3392 let priority = resume == LandResume::Ready;
3393 if !priority && cooling_down {
3394 return None;
3395 }
3396 let permit = match permit_kind(priority, task.urgent) {
3399 PermitKind::None => None,
3400 PermitKind::Urgent => Some(Arc::clone(urgent).try_acquire_owned().ok()?),
3401 PermitKind::Ordinary => Some(Arc::clone(ordinary).try_acquire_owned().ok()?),
3402 };
3403 let stamp = Timestamp::now();
3406 let mut task = task;
3407 task.dispatched_at = Some(stamp);
3408 if let Err(e) = queue.modify(&task.id, |t| {
3409 t.dispatched_at = Some(stamp);
3410 true
3411 }) {
3412 tracing::warn!("could not record dispatch order of {}: {e:#}", task.short());
3413 }
3414 Some(DispatchClaim {
3415 task,
3416 claim,
3417 permit,
3418 })
3419}
3420
3421#[derive(Serialize, Deserialize)]
3440struct ServiceWorker {
3441 opts: Opts,
3442 queue: PathBuf,
3443 worktrees_root: PathBuf,
3444 operation: String,
3445}
3446
3447fn load_conductor(home: &Path) -> Result<Conductor> {
3448 match std::fs::read(home.join("conductor-state.json")) {
3449 Ok(body) => serde_json::from_slice(&body).context("read conductor state"),
3450 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Conductor::new()),
3451 Err(error) => Err(error.into()),
3452 }
3453}
3454
3455fn conductor_work(queue: &Queue, home: &Path) -> (Vec<Task>, Vec<Task>, Vec<Task>) {
3456 let live: std::collections::BTreeSet<_> = current_work(home, Timestamp::now())
3457 .into_iter()
3458 .map(|c| c.task)
3459 .collect();
3460 let stalled = stalled_tasks(queue, home, Timestamp::now());
3461 let stalled_ids: std::collections::BTreeSet<_> = stalled.iter().map(|t| t.id.clone()).collect();
3462 let finished = finished_tasks(queue)
3463 .into_iter()
3464 .filter(|t| !live.contains(&t.id) && !stalled_ids.contains(&t.id))
3465 .filter(|t| !awaiting_resume_with(t, |id| RunState::load_under(id, home)))
3466 .collect();
3467 let queued = queued_tasks(queue)
3468 .into_iter()
3469 .filter(|t| !live.contains(&t.id))
3470 .collect();
3471 (queued, stalled, finished)
3472}
3473
3474async fn start_service(
3475 home: &Path,
3476 opts: &Opts,
3477 queue: &Queue,
3478 worktrees_root: &Path,
3479 operation: &str,
3480 cfg: Option<&Config>,
3481 busy: bool,
3482) -> Result<()> {
3483 let fetch_cfg = if operation == "fetch" {
3486 match prepare(&opts.repo, opts) {
3487 Ok(cfg) => Some(cfg),
3488 Err(error) => {
3489 tracing::warn!("could not reload periodic fetch configuration: {error:#}");
3490 return Ok(());
3491 }
3492 }
3493 } else {
3494 None
3495 };
3496 let cfg = fetch_cfg.as_ref().or(cfg);
3497 let ticks = home.join("service-ticks");
3498 std::fs::create_dir_all(&ticks)?;
3499 let receipt = ticks.join(format!("daemon-{operation}"));
3500 let last = std::fs::read(&receipt)
3501 .ok()
3502 .and_then(|body| serde_json::from_slice::<Timestamp>(&body).ok());
3503 let interval = match operation {
3504 "disk-pressure" => 30,
3505 "cache" => CACHE_CHECK_INTERVAL_SECS,
3506 "fetch" => cfg.map_or(60, |cfg| cfg.repos.fetch_interval.max(1)),
3507 _ => opts.poll.as_secs().max(1),
3508 };
3509 let now = Timestamp::now();
3510 if !cache_check_due(last, now, interval) {
3511 return Ok(());
3512 }
3513 let key = format!("service:daemon-{operation}");
3514 if crate::worker::active(home)?
3515 .iter()
3516 .any(|job| job.key == key)
3517 {
3518 return Ok(());
3519 }
3520 let eligible = match operation {
3521 "conductor" => {
3522 let (queued, stalled, finished) = conductor_work(queue, home);
3523 !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3524 && load_conductor(home)?.worth_a_look(queue, &stalled, &finished)
3525 }
3526 "maintenance" => Questions::at(home.join("questions"))
3527 .list()
3528 .iter()
3529 .any(|q| {
3530 q.chosen_action().is_some_and(|action| action.maintenance())
3531 && !home
3532 .join("choice-actions")
3533 .join(format!("{}.json", q.id))
3534 .exists()
3535 }),
3536 "housekeeping" => !busy && runnable(queue).is_empty(),
3537 "cache" => {
3538 !busy
3539 && !runnable(queue).is_empty()
3540 && cfg.is_some_and(|cfg| cfg.disk.cache_limit_bytes > 0)
3541 }
3542 "disk-pressure" => busy,
3543 "fetch" => {
3544 cfg.is_some_and(|cfg| cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty())
3545 }
3546 _ => false,
3547 };
3548 if !eligible {
3549 return Ok(());
3550 }
3551 let request = ServiceWorker {
3552 opts: opts.absolute()?,
3553 queue: std::path::absolute(queue.root())?,
3554 worktrees_root: std::path::absolute(worktrees_root)?,
3555 operation: operation.to_owned(),
3556 };
3557 if let Err(error) =
3558 crate::worker::spawn(home, "daemon-service", &key, serde_json::to_value(request)?).await
3559 {
3560 tracing::warn!(operation, "could not launch daemon service: {error:#}");
3561 }
3562 std::fs::write(receipt, serde_json::to_vec(&now)?)?;
3563 Ok(())
3564}
3565
3566pub async fn run_service_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
3569 let request: ServiceWorker = serde_json::from_value(payload)?;
3570 let opts = &request.opts;
3571 let queue = Queue::at(request.queue);
3572 let questions = Questions::at(home.join("questions"));
3573 match request.operation.as_str() {
3574 "maintenance" => apply_maintenance_choices(&queue, &questions, home).await,
3575 "conductor" => {
3576 let path = home.join("conductor-state.json");
3577 let mut conductor = load_conductor(home)?;
3578 let (queued, stalled, finished) = conductor_work(&queue, home);
3579 if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3580 && conductor.worth_a_look(&queue, &stalled, &finished)
3581 {
3582 let cfg = prepare(&opts.repo, opts)?;
3583 conductor
3584 .maybe_run(
3585 &cfg,
3586 &opts.repo,
3587 &queue,
3588 &questions,
3589 home,
3590 &queued,
3591 &stalled,
3592 &finished,
3593 opts.max_attempts,
3594 )
3595 .await;
3596 let temporary = path.with_extension("json.tmp");
3597 std::fs::write(&temporary, serde_json::to_vec(&conductor)?)?;
3598 std::fs::rename(temporary, path)?;
3599 }
3600 }
3601 "fetch" => {
3602 let cfg = prepare(&opts.repo, opts)?;
3603 if cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty() {
3604 let outcome = clean::fetch_origins(&cfg.repos.roots, FETCH_TIMEOUT, || false).await;
3605 tracing::debug!("fetch origins: {outcome:?}");
3606 }
3607 }
3608 "cache" => {
3609 if task_jobs(home)?.is_empty() {
3610 let mut checked = None;
3611 maybe_prune_cache_between_runs(
3612 &opts.repo,
3613 opts,
3614 home,
3615 &Stop::new(),
3616 &mut checked,
3617 Timestamp::now(),
3618 )
3619 .await;
3620 }
3621 }
3622 "disk-pressure" => {
3623 if let Ok(cfg) = prepare(&opts.repo, opts) {
3624 crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
3625 if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
3626 tracing::warn!("disk pressure cache cleanup failed: {e:#}");
3627 }
3628 for current in current_work(home, Timestamp::now()) {
3629 if let Ok(state) = RunState::load_under(¤t.run, home)
3630 && let Some(reason) = disk_gate(&state.repo, &state.config)
3631 {
3632 for job in owned_task_jobs(home)?.into_iter().filter(|job| {
3633 job.key.strip_prefix("task:") == Some(current.task.as_str())
3634 }) {
3635 request_task_park(
3636 home,
3637 &job,
3638 crate::run::ParkCause::Interrupt {
3639 reason: reason.clone(),
3640 },
3641 )?;
3642 }
3643 notices::raise_in(
3644 home,
3645 Notice::warn(
3646 "disk:pressure",
3647 "Disk pressure persists after cleanup; active workers were asked to checkpoint and park. New starts and resumes wait for free space.",
3648 ),
3649 );
3650 }
3651 }
3652 }
3653 }
3654 "housekeeping" => {
3655 if task_jobs(home)?.is_empty() {
3656 if let Ok(cfg) = prepare(&opts.repo, opts) {
3657 crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
3658 }
3659 janitor(&opts.repo, opts, home, &request.worktrees_root).await;
3660 resweep_superseded_attempts(&queue, home);
3661 triage_held(&queue, home, opts).await;
3662 }
3663 }
3664 operation => bail!("unknown daemon service {operation}"),
3665 }
3666 Ok(())
3667}
3668
3669fn task_worker_spawn_error(home: &Path, request: &TaskWorker, error: anyhow::Error) -> Result<()> {
3673 let key = format!("task:{}", request.task);
3674 let payload = serde_json::to_value(request)?;
3675 if crate::worker::active(home)?
3676 .iter()
3677 .any(|job| job.key == key && job.kind == "task" && job.payload != payload)
3678 {
3679 tracing::warn!(
3680 "task {} acquired a competing worker reservation: {error:#}",
3681 crate::run::short_of(&request.task)
3682 );
3683 return Ok(());
3684 }
3685 tracing::error!("task worker startup stopped dispatch: {error:#}");
3686 notices::raise_in(
3687 home,
3688 Notice::error(
3689 "loop:worker-startup",
3690 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),
3693 ).link(Link::Task { id: request.task.clone() }),
3694 );
3695 Err(error).with_context(|| {
3696 format!(
3697 "cannot start task {} worker; dispatcher stopped; any unacknowledged reservation remains occupied",
3698 crate::run::short_of(&request.task)
3699 )
3700 })
3701}
3702
3703async fn poll(
3704 opts: &Opts,
3705 queue: &Queue,
3706 status: &Arc<Mutex<Status>>,
3707 home: &Path,
3708 worktrees_root: &Path,
3709 stop: &Stop,
3710 limits: DispatchLimits,
3711) -> Result<()> {
3712 let mut attempted = Vec::new();
3713 let mut settling_once_services = false;
3714 let interrupt_path = home.join("scheduler-interrupt.json");
3715 let mut interrupt = match std::fs::read(&interrupt_path) {
3716 Ok(body) => serde_json::from_slice(&body).context("read scheduler interrupt state")?,
3717 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Interrupt::Idle,
3718 Err(error) => return Err(error.into()),
3719 };
3720 let mut previous = std::collections::BTreeSet::<String>::new();
3721 while !stop.stopped() {
3722 let jobs: Vec<_> = crate::worker::active(home)?
3723 .into_iter()
3724 .filter(|job| job.kind == "task")
3725 .collect();
3726 let requests: Vec<_> = jobs
3727 .iter()
3728 .map(|job| {
3729 serde_json::from_value::<TaskWorker>(job.payload.clone())
3730 .with_context(|| format!("read live task worker {}", job.id))
3731 })
3732 .collect::<Result<_>>()?;
3733 let live: std::collections::BTreeSet<_> = requests.iter().map(|r| r.task.clone()).collect();
3734 let owned: std::collections::BTreeSet<_> = requests
3735 .iter()
3736 .filter(|r| !r.standalone)
3737 .map(|r| r.task.clone())
3738 .collect();
3739 let current: Vec<_> = requests
3740 .iter()
3741 .zip(&jobs)
3742 .filter(|(request, _)| !request.standalone)
3743 .map(|(request, job)| Current {
3744 worker: Some(job.id.clone()),
3745 task: request.task.clone(),
3746 run: queue
3747 .get(&request.task)
3748 .ok()
3749 .and_then(|task| task.runs.last().cloned())
3750 .unwrap_or_default(),
3751 })
3752 .collect();
3753 {
3754 let mut snapshot = lock(status);
3755 snapshot.polls += 1;
3756 snapshot.completed += previous.difference(&owned).count();
3757 snapshot.current = current;
3758 snapshot.idle = owned.is_empty();
3759 }
3760 previous = owned.clone();
3761 stop.busy.store(owned.len(), Ordering::SeqCst);
3762
3763 let (ordinary, urgent) = available_slots(&requests, limits.max_concurrent);
3766 let sem = Arc::new(tokio::sync::Semaphore::new(ordinary));
3767 let urgent_sem = Arc::new(tokio::sync::Semaphore::new(urgent));
3768 let mut permits = Vec::new();
3769 sweep_stale_claims(queue, STALE_CLAIM);
3770 reclaim_orphaned_running(queue, opts.max_attempts, &live);
3771 reclaim_abandoned_runs(home, Timestamp::now());
3772 let questions = Questions::at(home.join("questions"));
3773
3774 crate::task_chat::sweep(
3777 queue,
3778 &crate::talk::Talks::at(home.join("talks")),
3779 &questions,
3780 home,
3781 );
3782 repair_choice_offers(&questions);
3783 resolve_blockers(queue, &questions);
3784 apply_task_choice_actions(queue, &questions, home);
3785 triage::apply_answers(queue, &questions);
3786 reconcile_task_questions(queue, &questions);
3787 let talks = crate::talk::Talks::at(home.join("talks"));
3788 crate::chat_notify::sweep(queue, &talks, home);
3789 crate::notice_delivery::sweep(queue, &talks, home, &opts.repo);
3790 crate::chat_watch::sweep(home, &talks);
3791 let mut turns = tokio::task::JoinSet::new();
3792 crate::chat_notify::start_turns(&talks, stop.parking(), &mut turns);
3793 while turns.join_next().await.is_some() {}
3795
3796 crate::consult::start_services(
3797 home,
3798 &opts.repo,
3799 limits.recovery_cfg.as_ref(),
3800 opts.config.as_deref(),
3801 )
3802 .await?;
3803 for operation in [
3804 "conductor",
3805 "maintenance",
3806 "housekeeping",
3807 "disk-pressure",
3808 "cache",
3809 "fetch",
3810 ] {
3811 if settling_once_services {
3815 break;
3816 }
3817 start_service(
3818 home,
3819 opts,
3820 queue,
3821 worktrees_root,
3822 operation,
3823 limits.recovery_cfg.as_ref(),
3824 !live.is_empty(),
3825 )
3826 .await?;
3827 }
3828 let latest = crate::worker::active(home)?;
3829 if latest.iter().any(|job| job.key == "service:daemon-cache")
3830 || latest
3831 .iter()
3832 .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
3833 {
3834 stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
3835 continue;
3836 }
3837 let candidates: Vec<Task> = runnable(queue)
3838 .into_iter()
3839 .filter(|task| !live.contains(&task.id))
3840 .filter(|task| !opts.once || !attempted.contains(&task.id))
3841 .collect();
3842 let in_flight: Vec<_> = owned.iter().cloned().collect();
3843 let prior_interrupt = std::mem::discriminant(&interrupt);
3844 interrupt = advance_interrupt_tick(
3845 limits.pause_for_interrupts,
3846 interrupt,
3847 &in_flight,
3848 &candidates,
3849 );
3850 if prior_interrupt != std::mem::discriminant(&interrupt) {
3853 let temporary = interrupt_path.with_extension("json.tmp");
3854 std::fs::write(&temporary, serde_json::to_vec(&interrupt)?)?;
3855 std::fs::rename(temporary, &interrupt_path)?;
3856 }
3857 if let Interrupt::Parking {
3858 parked,
3859 interrupt_task,
3860 } = &interrupt
3861 {
3862 for job in jobs.iter().filter(|job| {
3863 parked
3864 .iter()
3865 .any(|id| job.key.strip_prefix("task:") == Some(id.as_str()))
3866 }) {
3867 if crate::worker::control(home, &job.key)?.is_none() {
3868 request_task_park(
3869 home,
3870 job,
3871 crate::run::ParkCause::Interrupt {
3872 reason: format!(
3873 "task {} asked to run first",
3874 crate::run::short_of(interrupt_task)
3875 ),
3876 },
3877 )?;
3878 }
3879 }
3880 }
3881 let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
3882 let cooling = read_cooldown(home)?.is_some_and(|until| Timestamp::now() < until);
3883 let mut started = false;
3884 let mut resync = false;
3885 for candidate in candidates {
3886 if stop.stopped() {
3887 break;
3888 }
3889 let Some(DispatchClaim {
3890 task,
3891 claim,
3892 permit,
3893 }) = claim_dispatch(queue, &candidate, cooling, &sem, &urgent_sem)
3894 else {
3895 continue;
3896 };
3897 if crate::worker::active(home)?
3898 .iter()
3899 .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
3900 {
3901 drop(claim);
3902 resync = true;
3903 break;
3904 }
3905 let lane = permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent);
3906 let request = TaskWorker {
3907 opts: opts.absolute()?,
3908 queue: std::path::absolute(queue.root())?,
3909 task: task.id.clone(),
3910 lane,
3911 standalone: false,
3912 };
3913 if let Err(error) = crate::worker::spawn(
3916 home,
3917 "task",
3918 &format!("task:{}", task.id),
3919 serde_json::to_value(&request)?,
3920 )
3921 .await
3922 {
3923 task_worker_spawn_error(home, &request, error)?;
3924 drop(claim);
3925 resync = true;
3926 break;
3927 }
3928 drop(claim);
3929 permits.extend(permit);
3930 attempted.push(task.id);
3931 started = true;
3932 }
3933 if started || resync {
3934 continue;
3935 }
3936 if owned.is_empty() && opts.once {
3937 settling_once_services = true;
3938 if crate::worker::active(home)?.iter().any(|job| {
3942 job.kind == "daemon-service"
3943 && matches!(
3944 job.key.as_str(),
3945 "service:daemon-housekeeping"
3946 | "service:daemon-conductor"
3947 | "service:daemon-maintenance"
3948 )
3949 }) {
3950 stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
3951 continue;
3952 }
3953 break;
3954 }
3955 stop.idle(if live.is_empty() {
3956 opts.poll
3957 } else {
3958 RECHECK_WHILE_BUSY.min(opts.poll)
3959 })
3960 .await;
3961 }
3962 stop.busy.store(0, Ordering::SeqCst);
3965 Ok(())
3966}
3967
3968async fn resume_owner_lock(home: &Path, id: &str) -> Result<crate::pr_head::OwnerLock> {
3972 let busy = |error: &anyhow::Error| {
3973 error.downcast_ref::<std::io::Error>().is_some_and(|error| {
3974 error.kind() == std::io::ErrorKind::WouldBlock
3975 || cfg!(windows) && error.raw_os_error() == Some(33)
3976 })
3977 };
3978 match crate::pr_head::owner_lock(home, id) {
3979 Ok(lock) => return Ok(lock),
3980 Err(error) if busy(&error) => {}
3981 Err(error) => return Err(error),
3982 }
3983 let wait = RunState::load_under(id, home)?
3984 .config
3985 .graph
3986 .timeout_resource_wait;
3987 crate::pr_head::owner_lock_wait(home, id, Duration::from_secs(wait)).await
3988}
3989
3990async fn public_resume_owner(
3994 home: &Path,
3995 runs: &[String],
3996 repo: &Path,
3997) -> Result<Option<RunState>> {
3998 let mut owner = None;
3999 for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
4000 let _lock = resume_owner_lock(home, id).await?;
4001 let state = RunState::load_under(id, home)?;
4002 if state.released()
4003 || state.retired_to.is_some()
4004 || state.pr_taken_over_by.is_some()
4005 || !crate::handover::landing_checkpoint(&state)
4006 {
4007 continue;
4008 }
4009 anyhow::ensure!(
4010 crate::git::toplevel(&state.repo).await?.canonicalize()?
4011 == crate::git::toplevel(repo).await?.canonicalize()?,
4012 "public owner repository differs; inspect run lineage"
4013 );
4014 anyhow::ensure!(
4015 owner.is_none(),
4016 "multiple retained public owners; inspect run lineage"
4017 );
4018 if let Some(reason) = crate::handover::resume_refusal_under(&state, Some(home)) {
4019 anyhow::bail!(reason.diagnostic(&state));
4020 }
4021 let claimed = is_working_on_other(home, id, Timestamp::now())?;
4022 anyhow::ensure!(
4023 state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
4024 "public owner's driver is live or unknown; wait before retrying"
4025 );
4026 owner = Some(state);
4027 }
4028 Ok(owner)
4029}
4030
4031async fn attempt(
4037 opts: &Opts,
4038 queue: &Queue,
4039 status: &Arc<Mutex<Status>>,
4040 stop: &Stop,
4041 interrupt_pause: crate::graph::Pause,
4042 task: &mut Task,
4043) -> Vec<QuotaLoss> {
4044 let repo = repo_for(task, &opts.repo);
4045 tracing::info!(
4046 "task {} — {} (repo {})",
4047 task.short(),
4048 task.title,
4049 repo.display()
4050 );
4051
4052 let public_owner = match public_resume_owner(&crate::run::home(), &task.runs, &repo).await {
4053 Ok(owner) => owner,
4054 Err(e) => {
4055 task.hold_machine(Some(format!(
4056 "Cannot verify existing public owner: {e:#}; no attempt started."
4057 )));
4058 record(queue, task);
4059 return Vec::new();
4060 }
4061 };
4062 let resume_runs = public_owner
4063 .as_ref()
4064 .map(|s| vec![s.id.clone()])
4065 .unwrap_or_else(|| task.runs.clone());
4066
4067 if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
4071 && previous
4072 .merge_decision
4073 .as_ref()
4074 .is_some_and(|decision| !decision.closed)
4075 && previous.status != RunStatus::Landing
4076 && !crate::merge_decision::resumable_hold(&previous)
4077 {
4078 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)));
4079 record(queue, task);
4080 return Vec::new();
4081 }
4082 let stop_owner = resume_runs
4083 .last()
4084 .and_then(|id| RunState::load(id).ok())
4085 .filter(|state| {
4086 crate::merge_decision::resumable_hold(state)
4087 || state.status == RunStatus::Landing
4088 && state.land_approval.as_ref().is_some_and(|binding| {
4089 Questions::open().get(&binding.question).is_ok_and(|q| {
4090 q.run == state.id
4091 && q.resolution()
4092 .as_deref()
4093 .is_some_and(crate::merge_decision::stops)
4094 })
4095 })
4096 });
4097 if let Some(owner) = stop_owner {
4098 let mut runner = match Runner::resume(&owner.id) {
4099 Ok(runner) => runner,
4100 Err(e) => {
4101 task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
4102 record(queue, task);
4103 return Vec::new();
4104 }
4105 };
4106 runner.on_pause(stop.pause());
4107 runner.watch_interrupt(interrupt_pause);
4108 let quota_before = runner.state.quota.clone();
4109 task.start(owner.id.clone());
4110 record(queue, task);
4111 lock(status).current.push(Current {
4112 worker: None,
4113 task: task.id.clone(),
4114 run: owner.id,
4115 });
4116 runner.state.next_pass_task_entry = true;
4117 let result = runner.execute().await;
4118 return finish_attempt(
4119 opts.max_attempts,
4120 queue,
4121 task,
4122 &runner.state,
4123 "a_before,
4124 result,
4125 );
4126 }
4127
4128 if let Some(owner) = &public_owner
4129 && (task.fresh_start || !may_resume_run(owner, task))
4130 {
4131 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)));
4132 record(queue, task);
4133 return Vec::new();
4134 }
4135
4136 if let Some(held) = crate::base_sync_recovery::held_run(queue, task)
4137 && !task.fresh_start
4138 && task.review_branch.is_none()
4139 && task.pr_recovery.is_none()
4140 {
4141 let authorized = if task.resumption.is_some() && compatible_run_instruction(&held, task) {
4144 let home = queue.root().parent().expect("queue has a home");
4145 match Runner::authorize_base_recovery_from_resumption(home, &held.id, &task.id).await {
4146 Ok(()) => true,
4147 Err(error) => {
4148 tracing::debug!(run = %held.id, %error, "base recovery resumption refused");
4149 false
4150 }
4151 }
4152 } else {
4153 false
4154 };
4155 if !authorized {
4156 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()));
4157 task.base_sync_notice(&held);
4159 task.resume_override = None;
4160 record(queue, task);
4161 return Vec::new();
4162 }
4163 }
4164 let unfinished = (!task.fresh_start)
4165 .then(|| unfinished_run(&resume_runs, task.short()))
4166 .flatten()
4167 .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
4168 let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
4169 if !task.fresh_start
4170 && task.pr_recovery.is_none()
4171 && task.review_branch.is_none()
4172 && task.resume_override.is_none()
4173 && previous
4174 .as_ref()
4175 .is_some_and(|run| run.retired_to.is_some())
4176 && unfinished.is_none()
4177 {
4178 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()));
4179 record(queue, task);
4180 return Vec::new();
4181 }
4182
4183 let saved_recovery = previous.as_ref().filter(|run| {
4184 task.replacement.is_none()
4185 && task.pr_recovery.as_ref().is_some_and(|selected| {
4186 selected.check_task(&task.id, &task.instruction).is_ok()
4187 && selected_starter(selected, Some(run), unfinished.as_deref())
4188 == Starter::Resume(run.id.clone())
4189 })
4190 });
4191
4192 let explicit = match &task.overrides {
4196 Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
4197 Some(_) => opts.config.as_deref(),
4198 None => opts.config.as_deref(),
4199 };
4200 let (mut config, layers) = if let Some(run) = saved_recovery {
4201 let mut saved = run.clone();
4204 if let Err(e) = saved.configure_recovery_resume() {
4205 task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
4206 record(queue, task);
4207 return Vec::new();
4208 }
4209 (saved.config, Vec::new())
4210 } else {
4211 let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
4212 Ok(loaded) => loaded,
4213 Err(e) => {
4214 let reason = format!("[config] {e:#}");
4215 record_config_failure(task, &e);
4216 task.last_error = Some(reason.clone());
4217 task.hold_machine(Some(reason));
4218 record(queue, task);
4219 return Vec::new();
4220 }
4221 };
4222 if let Err(e) = apply_options(&mut config, opts, task) {
4223 task.hold_manual(Some(format!(
4224 "[config] {e:#}; correct the merge override before releasing the task"
4225 )));
4226 record(queue, task);
4227 return Vec::new();
4228 }
4229 if let Some(selected) = &task.pr_recovery
4230 && let Err(e) = selected.configure(&mut config)
4231 {
4232 task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
4233 record(queue, task);
4234 return Vec::new();
4235 }
4236 (config, layers)
4237 };
4238 let config_evidence = crate::pr_recovery::ConfigEvidence {
4239 layers,
4240 overrides: task.overrides.clone(),
4241 daemon_merge: task
4242 .overrides
4243 .as_ref()
4244 .is_none_or(|o| o.inherit_daemon_options)
4245 .then(|| opts.merge.clone())
4246 .flatten(),
4247 };
4248 apply_task_implementers(&mut config, task);
4249 if let Some(replacement) = &task.replacement {
4250 let safe = RunState::load(&replacement.run).is_ok_and(|old| {
4251 old.liveness(false) == Liveness::Dead
4252 && old.merge_decision.as_ref().is_some_and(|d| {
4253 d.closed
4254 && d.question == replacement.question
4255 && d.replacement_run.as_ref().is_none_or(|run| {
4256 task.runs.last() == Some(run)
4257 && RunState::load(run).is_ok_and(|current| {
4258 current.replaces.as_ref().is_some_and(|pin| {
4259 pin.question == replacement.question
4260 && pin.agent == replacement.agent
4261 })
4262 })
4263 })
4264 })
4265 });
4266 if !safe {
4267 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()));
4268 record(queue, task);
4269 return Vec::new();
4270 }
4271 match config.agent(&replacement.agent) {
4272 Ok(agent) if crate::agent::installed(agent) => {}
4273 _ => {
4274 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)));
4275 record(queue, task);
4276 return Vec::new();
4277 }
4278 }
4279 config.graph.implementers = 1;
4280 config.graph.land_approval = true;
4281 config.merge.mode = MergeMode::Pr;
4282 config.graph.selected_implementer = Some(replacement.agent.clone());
4283 }
4284 let p = phrases(&config.graph.language);
4285 let start_failed = p.could_not_start;
4286 if let Ok(base) =
4291 crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
4292 .await
4293 && let Ok(head) =
4294 crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
4295 {
4296 let mut inputs = crate::queue::recovery_inputs(&task.sources);
4297 if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
4298 let source = crate::git::rev_parse(&repo, branch)
4299 .await
4300 .unwrap_or_default();
4301 inputs.push_str(&format!(";review:{branch}:{source}"));
4302 }
4303 if let Some(reason) = task.recovery_exhausted(
4304 &head,
4305 &inputs,
4306 task.attempt_limit
4307 .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
4308 ) {
4309 task.hold_unrequested_retry(Some(reason));
4310 record(queue, task);
4311 return Vec::new();
4312 }
4313 task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
4314 }
4315
4316 if let Some(reason) = disk_gate(&repo, &config) {
4324 task.notice_cause("disk-space", None, None);
4325 task.last_error = Some(reason.clone());
4326 task.hold_machine(Some(reason.clone()));
4327 record(queue, task);
4328 tracing::warn!("holding {} for want of disk space: {reason}", task.short());
4329 notices::raise(
4332 Notice::warn(
4333 &format!("disk:{}", repo.display()),
4334 format!("Task {} held for want of free disk space: {reason}. Free some, then release it from the queue.", task.id),
4335 )
4336 .link(Link::Task {
4337 id: task.id.clone(),
4338 }),
4339 );
4340 return Vec::new();
4341 }
4342
4343 let review_branch = take_review_branch(task, previous.as_ref());
4368 let branch_exists = match &review_branch {
4369 Some(branch) => crate::git::branch_exists(&repo, branch)
4370 .await
4371 .unwrap_or(false),
4372 None => false,
4373 };
4374 let proposed = review_retry_starter(
4378 task,
4379 previous.as_ref(),
4380 review_branch.as_deref(),
4381 branch_exists,
4382 unfinished.as_deref(),
4383 );
4384 let retry_selected = task.replacement.is_some()
4385 && task.resumption.is_some()
4386 && !task.fresh_start
4387 && previous.as_ref().is_some_and(|run| {
4388 run.replaces.is_some()
4389 && ((run.status == RunStatus::Failed && run.viable().is_empty())
4390 || (run.status == RunStatus::Blocked && run.tally.is_none()))
4391 });
4392 let stop_pin = task
4393 .resume_override
4394 .as_ref()
4395 .filter(|pin| {
4396 Questions::open().get(&pin.question_id).is_ok_and(|q| {
4397 q.node == land::APPROVAL_NODE
4398 && q.resolution()
4399 .as_deref()
4400 .is_some_and(crate::merge_decision::stops)
4401 })
4402 })
4403 .and_then(|pin| pin.pinned_run.clone());
4404 let starter = if let Some(owner) = &public_owner {
4405 Starter::Resume(owner.id.clone())
4406 } else if let Some(run) = stop_pin {
4407 Starter::Resume(run)
4410 } else if retry_selected {
4411 Starter::Resume(previous.as_ref().unwrap().id.clone())
4412 } else if let Some(selected) = &task.pr_recovery {
4413 if selected.check_task(&task.id, &task.instruction).is_ok() {
4414 selected_starter(selected, previous.as_ref(), unfinished.as_deref())
4415 } else {
4416 Starter::Review(selected.branch.clone())
4417 }
4418 } else {
4419 starter_with_implementers(task, previous.as_ref(), proposed)
4420 };
4421 if let Some(pin) = &task.resume_override
4424 && let Some(run) = &pin.pinned_run
4425 && starter != Starter::Resume(run.clone())
4426 {
4427 let run = run.clone();
4428 task.notice_cause("resume-owner", Some(&run), None);
4429 task.hold_machine(Some(format!(
4430 "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
4431 task.id
4432 )));
4433 record(queue, task);
4434 return Vec::new();
4435 }
4436 if task.replacement.is_some()
4437 && previous.as_ref().is_some_and(|run| run.replaces.is_some())
4438 && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
4439 {
4440 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()));
4441 record(queue, task);
4442 return Vec::new();
4443 }
4444 if let Some(reason) = retained_attempt_hold(
4445 task,
4446 &starter,
4447 config.disk.retained_attempt_limit,
4448 RunState::load,
4449 ) {
4450 if let Starter::Review(branch) = &starter {
4453 task.review_branch = Some(branch.clone());
4454 }
4455 task.hold_unrequested_retry(Some(reason));
4456 record(queue, task);
4457 return Vec::new();
4458 }
4459 let attachments = match task_attachments(queue, task) {
4464 Ok(a) => a,
4465 Err(e) => {
4466 task.attempts += 1;
4467 task.fail_startup_target(
4468 "startup-attachments",
4469 e.name.clone(),
4470 format!("{start_failed}{e:#}"),
4471 opts.max_attempts,
4472 );
4473 record(queue, task);
4474 return Vec::new();
4475 }
4476 };
4477 let startup_pause = stop.pause();
4478 let startup_interrupt = interrupt_pause.clone();
4479 let wait = crate::repo_lock::WaitPolicy::new(
4480 Duration::from_secs(config.graph.timeout_resource_wait),
4481 move || startup_pause.parked() || startup_interrupt.parked(),
4482 );
4483 let started = wait.scope(Box::pin(async { match &starter {
4486 Starter::Review(_) if task.pr_recovery.is_some() => {
4487 let selected = task.pr_recovery.clone().expect("selected recovery");
4488 match selected.check_task(&task.id, &task.instruction) {
4489 Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
4490 .await
4491 .map(|mut r| {
4492 r.state.attachments = attachments.clone();
4493 r
4494 }),
4495 Err(e) => Err(e),
4496 }
4497 }
4498 Starter::Review(branch) => {
4499 tracing::info!(
4500 "task {} reopens `{branch}` as a review-only pass",
4501 task.short()
4502 );
4503 let takeover = crate::handover::Takeover {
4506 earlier: task.earlier_attempts().to_vec(),
4507 home: crate::run::home(),
4508 choice: take_divergence_answer(branch, &config.merge.remote, task),
4509 task_instruction: Some(instruction_for(task)),
4510 };
4511 Runner::review_taking_over(
4512 &repo,
4513 branch,
4514 config,
4515 Some(takeover),
4516 crate::run::Origin::queue(&task.id),
4517 )
4518 .await
4519 }
4520 Starter::Resume(id) => {
4521 tracing::info!("resuming run {id} rather than competing again");
4522 Runner::resume(id).and_then(|mut r| {
4523 if retry_selected {
4524 for candidate in &mut r.state.candidates {
4527 candidate.failed = None;
4528 candidate.empty = false;
4529 candidate.commits = 0;
4530 }
4531 r.state.status = RunStatus::Implementing;
4532 r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
4533 }
4534 if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
4535 r.state.sources = task.sources.clone();
4536 }
4537 if r.state.prep_failure.is_some() {
4538 let approval = task
4539 .resumption
4540 .as_ref()
4541 .context("preparation retry requires an explicit task release")?;
4542 r.retry_preparation(approval.at)?;
4543 }
4544 if let Some(instruction) =
4545 prepare_instruction(&starter, Some(&r.state.instruction), task)
4546 {
4547 r.state.instruction = instruction;
4548 }
4549 r.state.attachments = attachments.clone();
4550 if task.replacement.is_some() {
4551 r.state.config.merge.mode = MergeMode::Pr;
4552 r.state.config.graph.land_approval = true;
4553 }
4554 if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
4558 .overrides
4559 .as_ref()
4560 .and_then(|o| o.merge.as_deref())
4561 .and_then(|m| merge_mode(m).ok())
4562 {
4563 r.state.config.merge.mode = mode;
4564 }
4565 Ok(r)
4566 })
4567 }
4568 Starter::Start => {
4569 if let Some(branch) = &review_branch {
4570 tracing::warn!(
4571 "conductor chose review for task {} but branch `{branch}` no longer \
4572 exists; requeuing as a fresh competition instead",
4573 task.short()
4574 );
4575 }
4576 let instruction = prepare_instruction(&starter, None, task)
4577 .unwrap_or_else(|| task.instruction.clone());
4578 Runner::start_naming(
4579 &repo,
4580 instruction,
4581 &task.title,
4582 config,
4583 crate::run::Origin::queue(&task.id),
4584 )
4585 .await
4586 .map(|mut r| {
4587 r.state.attachments = attachments.clone();
4588 r.state.sources = task.sources.clone();
4589 r
4590 })
4591 }
4592 }})).await;
4593 let mut runner = match started {
4594 Ok(r) => r,
4595 Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
4596 task.last_error = Some(e.to_string());
4597 if stop.parking() || interrupt_pause.parked() {
4598 let attempts = task.attempts;
4599 task.park(e.to_string());
4600 task.attempts = attempts;
4602 } else {
4603 task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
4604 }
4605 record(queue, task);
4606 return Vec::new();
4607 }
4608 Err(e) if task.pr_recovery.is_some() => {
4612 task.startup_notice_cause("startup-public-head");
4613 task.attempts += 1;
4614 if let Some(partial) = e.downcast_ref::<crate::pr_recovery::StartupFailed>() {
4615 task.link_run(&partial.run);
4616 task.record_pass(&partial.run, 0, task.attempts, None);
4617 }
4618 task.last_error = Some(format!("{start_failed}{e:#}"));
4619 task.hold_unrequested_retry(Some(format!(
4620 "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."
4621 )));
4622 record(queue, task);
4623 return Vec::new();
4624 }
4625 Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
4626 let detail = match e.downcast_ref::<crate::handover::Refused>() {
4627 Some(r) => (p.handover_refused)(r),
4628 None => format!("{e:#}"),
4629 };
4630 task.startup_notice_cause("startup-handover");
4631 let reason = format!("{start_failed}{detail}");
4632 task.last_error = Some(reason.clone());
4633 let branch = match &starter {
4636 Starter::Review(branch) => Some(branch.clone()),
4637 _ => None,
4638 };
4639 task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
4643 record(queue, task);
4644 tracing::warn!(
4645 "holding {} for a branch it cannot take over: {e:#}",
4646 task.short()
4647 );
4648 return Vec::new();
4649 }
4650 Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
4655 let d = e
4656 .downcast_ref::<crate::reconcile::Diverged>()
4657 .expect("checked by the guard");
4658 let mut q = ask::Question::new(
4659 task.id.clone(),
4660 crate::reconcile::NODE.to_owned(),
4661 crate::reconcile::SEAT.to_owned(),
4662 d.summary(),
4663 d.detail(),
4664 d.choices(),
4665 );
4666 match Questions::open().put(&mut q) {
4667 Ok(()) => {
4668 task.last_error = Some(format!("{e:#}"));
4669 task.review_branch = Some(d.branch.clone());
4672 task.review_instruction = Some(task.instruction.clone());
4673 task.block(vec![q.id.clone()], Some(d.summary()));
4674 }
4675 Err(put) => {
4676 tracing::warn!("could not file the divergence question: {put:#}");
4677 task.attempts += 1;
4678 task.fail_startup(
4679 "startup-question-store",
4680 format!("{start_failed}{e:#}"),
4681 opts.max_attempts,
4682 );
4683 }
4684 }
4685 record(queue, task);
4686 return Vec::new();
4687 }
4688 Err(e) => {
4689 if e.downcast_ref::<crate::reconcile::Stale>().is_some()
4695 && let Starter::Review(branch) = &starter
4696 {
4697 task.review_branch = Some(branch.clone());
4698 task.review_instruction = Some(task.instruction.clone());
4699 task.last_error = Some(format!("{start_failed}{e:#}"));
4700 task.status = crate::queue::TaskStatus::Failed;
4701 record(queue, task);
4702 return Vec::new();
4703 }
4704 task.attempts += 1;
4705 task.last_error = Some(format!("{start_failed}{e:#}"));
4706 task.startup_notice_cause("startup-source");
4707 task.hold_unrequested_retry(Some(format!(
4708 "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
4709 )));
4710 record(queue, task);
4711 return Vec::new();
4712 }
4713 };
4714 if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
4715 runner.state.recovery_config = Some(config_evidence);
4716 }
4717 if let Some(replacement) = &task.replacement {
4718 if matches!(starter, Starter::Start) {
4719 runner.state.instruction.push_str(&format!(
4720 "\n\n# Replacement review context\n{}",
4721 replacement.context
4722 ));
4723 }
4724 runner.state.replaces = Some(replacement.clone());
4725 runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
4726 if let Ok(mut old) = RunState::load(&replacement.run)
4727 && let Some(d) = &mut old.merge_decision
4728 {
4729 d.replacement_run = Some(runner.state.id.clone());
4730 old.event(
4731 "replacement",
4732 format!(
4733 "replacement run {} owns the next attempt; old PR remains closed",
4734 runner.state.id
4735 ),
4736 );
4737 if let Err(e) = old.save() {
4738 task.hold_manual(Some(format!(
4739 "Could not link replacement history: {e}; no agents dispatched"
4740 )));
4741 record(queue, task);
4742 return Vec::new();
4743 }
4744 }
4745 }
4746 runner.state.task_instruction = Some(task.instruction.clone());
4747 runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
4750 if runner.state.origin_chat.is_none() {
4751 runner.state.origin_chat = task.chat_talk().map(str::to_owned);
4752 }
4753 runner.on_pause(stop.pause());
4755 runner.watch_interrupt(interrupt_pause);
4759
4760 let run = runner.state.id.clone();
4763 task.start(run.clone());
4764 record(queue, task);
4765 lock(status).current.push(Current {
4766 worker: None,
4767 task: task.id.clone(),
4768 run,
4769 });
4770
4771 let quota_before = runner.state.quota.clone();
4774 runner.state.next_pass_task_entry = true;
4775 let result = runner.execute().await;
4776 finish_attempt(
4777 opts.max_attempts,
4778 queue,
4779 task,
4780 &runner.state,
4781 "a_before,
4782 result,
4783 )
4784}
4785
4786pub fn finish_attempt(
4791 max_attempts: usize,
4792 queue: &Queue,
4793 task: &mut Task,
4794 state: &RunState,
4795 quota_before: &[QuotaLoss],
4796 result: Result<()>,
4797) -> Vec<QuotaLoss> {
4798 let detail = match result {
4799 Ok(()) => describe(state),
4800 Err(e) => format!("{e:#}"),
4801 };
4802 let fresh = losses_this_attempt(quota_before, &state.quota);
4803 let verdict = Verdict {
4804 status: state.status,
4805 left_pr: state.pr.is_some(),
4808 quota_hit: !fresh.is_empty(),
4814 parked: state.parked,
4818 no_viable_candidates: state.viable().is_empty(),
4821 };
4822 if let Some(replacement) = &state.replaces
4823 && let Some(pr) = &state.pr
4824 && let Ok(mut old) = RunState::load(&replacement.run)
4825 && let Some(d) = &mut old.merge_decision
4826 {
4827 d.replacement_pr = Some(pr.url.clone());
4828 let _ = old.save();
4829 }
4830 settle_and_diagnose(task, verdict, &detail, max_attempts, state);
4831 if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
4832 task.hold_unrequested_retry(Some(format!(
4833 "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.",
4834 task.short()
4835 )));
4836 }
4837 if task.status == TaskStatus::Done {
4838 supersede_prior_runs(task, &crate::run::home());
4839 }
4840 record(queue, task);
4841 tracing::info!(
4842 "task {} is {} after run {} ({})",
4843 task.short(),
4844 task.status.as_str(),
4845 state.short(),
4846 label(state.status)
4847 );
4848 fresh
4849}
4850
4851pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
4855 if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
4858 && !awaiting_resume_with(task, RunState::load)
4859 && withheld_text_wait(task).is_none()
4863 && !(task.fresh_start && task.replacement.is_some())
4864 {
4865 let why = task.last_error.clone().map_or_else(
4866 || "the run did not finish".to_owned(),
4867 |e| format!("the run did not finish: {e}"),
4868 );
4869 task.hold_unrequested_retry(Some(format!(
4870 "{why}. It was started by hand, so it is not retried \
4871 automatically; `magi task release` retries it."
4872 )));
4873 record(queue, task);
4874 }
4875}
4876
4877#[must_use]
4881pub fn loop_would_resume(run: &str) -> bool {
4882 unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
4883}
4884
4885#[must_use]
4895pub fn foreign_loop(
4896 reading: Option<&Reading>,
4897 now: Timestamp,
4898 own_pid: u32,
4899) -> Option<Option<u32>> {
4900 let reading = reading.filter(|r| r.running(now))?;
4901 match reading.pid {
4902 Some(pid) if pid == own_pid => None,
4903 pid => Some(pid),
4904 }
4905}
4906
4907fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
4908 reading.worker_protocol != Some(1)
4909 && (foreign_loop(Some(reading), now, own_pid).is_some()
4910 || reading
4911 .pid
4912 .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
4913}
4914
4915pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
4926 run_claimed_until(opts, queue, task, &Stop::new()).await;
4927}
4928
4929async fn run_claimed_until(
4930 opts: &Opts,
4931 queue: &Queue,
4932 task: &mut Task,
4933 stop: &Stop,
4934) -> Vec<QuotaLoss> {
4935 let status = Arc::new(Mutex::new(Status::new()));
4936 let mut quota = Box::pin(attempt(
4939 opts,
4940 queue,
4941 &status,
4942 stop,
4943 crate::graph::Pause::new(),
4944 task,
4945 ))
4946 .await;
4947 let mut resumes = 0;
4956 while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
4957 let Some(timeout) = withheld_text_wait(task) else {
4958 break;
4959 };
4960 eprintln!(
4961 "waiting for the owner's answer on a withheld pull request text \
4962 (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
4963 );
4964 let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
4967 let ready = loop {
4968 match land_resume_state(task) {
4969 LandResume::StillWaiting
4970 if !stop.parking() && std::time::Instant::now() < limit =>
4971 {
4972 tokio::time::sleep(WITHHELD_POLL).await;
4973 }
4974 LandResume::Ready => break true,
4975 _ => break false,
4976 }
4977 };
4978 if !ready || stop.parking() {
4979 break;
4980 }
4981 resumes += 1;
4982 quota.extend(
4983 Box::pin(attempt(
4984 opts,
4985 queue,
4986 &status,
4987 stop,
4988 crate::graph::Pause::new(),
4989 task,
4990 ))
4991 .await,
4992 );
4993 }
4994 hold_if_runnable(queue, task);
4995 quota
4996}
4997
4998const MAX_WITHHELD_RESUMES: u32 = 3;
5001
5002const WITHHELD_POLL: Duration = Duration::from_secs(15);
5004
5005fn withheld_text_wait(task: &Task) -> Option<u64> {
5008 let id = task.runs.last()?;
5009 let s = RunState::load(id).ok()?;
5010 (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
5011 .then_some(s.config.graph.answer_timeout)
5012}
5013
5014fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
5024 after
5025 .iter()
5026 .filter(|q| !before.contains(q))
5027 .cloned()
5028 .collect()
5029}
5030
5031fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
5034 if quota.is_empty() {
5035 return None;
5036 }
5037 let with_hint = quota.iter().find(|q| q.reset.is_some());
5038 let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
5039 let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
5040 let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
5041 Some(
5042 now.checked_add(jiff::SignedDuration::from_secs(secs))
5043 .unwrap_or(Timestamp::MAX),
5044 )
5045}
5046
5047fn implementers_match(task: &Task, state: &RunState) -> bool {
5049 task.replacement.as_ref().map_or_else(
5050 || {
5051 task.implementers()
5052 .is_none_or(|n| n == state.config.graph.implementers)
5053 },
5054 |replacement| {
5055 state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
5056 && state.config.graph.implementers == 1
5057 },
5058 )
5059}
5060
5061fn starter_with_implementers(
5063 task: &Task,
5064 previous: Option<&RunState>,
5065 proposed: Starter,
5066) -> Starter {
5067 if previous.is_some_and(|s| !implementers_match(task, s)) {
5068 task.review_of
5069 .as_ref()
5070 .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
5071 } else {
5072 proposed
5073 }
5074}
5075
5076fn apply_task_implementers(config: &mut Config, task: &Task) {
5078 if let Some(n) = task.implementers() {
5079 config.graph.implementers = n;
5080 }
5081}
5082
5083#[cfg(test)]
5088fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
5089 let explicit = match &task.overrides {
5090 Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
5091 _ => opts.config.as_deref(),
5092 };
5093 let (mut config, _) = Config::discover(repo, explicit)?;
5094 apply_options(&mut config, opts, task)?;
5095 Ok(config)
5096}
5097
5098fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
5099 if task
5100 .overrides
5101 .as_ref()
5102 .is_none_or(|o| o.inherit_daemon_options)
5103 && let Some(mode) = opts.merge.as_deref()
5104 {
5105 config.merge.mode = merge_mode(mode)?;
5106 }
5107 if let Some(o) = &task.overrides {
5108 o.apply(config);
5109 }
5110 Ok(())
5111}
5112
5113fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
5115 let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
5116 if let Some(mode) = &opts.merge {
5117 config.merge.mode = merge_mode(mode)?;
5118 }
5119 Ok(config)
5120}
5121
5122async fn maybe_prune_cache_between_runs(
5127 repo: &Path,
5128 opts: &Opts,
5129 home: &Path,
5130 stop: &Stop,
5131 last_checked: &mut Option<Timestamp>,
5132 now: Timestamp,
5133) {
5134 if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
5135 return;
5136 }
5137 *last_checked = Some(now);
5138 let cfg = match prepare(repo, opts) {
5139 Ok(cfg) => cfg,
5140 Err(e) => {
5141 tracing::warn!("cache check: no config: {e:#}");
5142 return;
5143 }
5144 };
5145 match clean::prune_cache_if_over_limit(&cfg, home) {
5146 Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
5147 "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
5148 pruned.files,
5149 pruned.freed
5150 ),
5151 Ok(_) => {}
5152 Err(e) => {
5153 tracing::warn!("housekeep: prune cache: {e:#}");
5154 notices::raise_in(
5155 home,
5156 Notice::warn(
5157 "housekeep:cache",
5158 format!(
5159 "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
5160 e.to_string()
5161 .lines()
5162 .next()
5163 .unwrap_or("unknown cleanup error")
5164 ),
5165 ),
5166 );
5167 }
5168 }
5169}
5170
5171fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
5175 last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
5176}
5177
5178async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
5197 let cfg = match prepare(repo, opts) {
5198 Ok(cfg) => cfg,
5199 Err(e) => {
5200 tracing::warn!("housekeep: no config: {e:#}");
5201 return;
5202 }
5203 };
5204 let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
5213 let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
5214 if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
5219 let mut extra = Vec::new();
5220 if out.unreadable > 0 {
5221 extra.push(format!("{} unreadable", out.unreadable));
5222 }
5223 if out.orphaned_worktrees > 0 {
5224 extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
5225 }
5226 let detail = if extra.is_empty() {
5227 String::new()
5228 } else {
5229 format!(" ({})", extra.join(", "))
5230 };
5231 tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
5232 }
5233 if out.external_merges_recorded > 0 {
5234 tracing::info!(
5235 "housekeep: recorded {} run(s) as merged externally",
5236 out.external_merges_recorded
5237 );
5238 }
5239 if out.stale_pr_states_repaired > 0 {
5240 tracing::info!(
5241 "housekeep: rewrote {} run record(s) whose pull request had already settled",
5242 out.stale_pr_states_repaired
5243 );
5244 }
5245 if out.cache_files > 0 {
5246 tracing::info!(
5247 "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
5248 out.cache_files,
5249 out.cache_freed
5250 );
5251 }
5252 if out.questions_abandoned > 0 {
5253 tracing::info!(
5254 "housekeep: abandoned {} question(s) left open by a finished run",
5255 out.questions_abandoned
5256 );
5257 }
5258}
5259
5260async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
5269 let questions = Questions::at(home.join("questions"));
5270 let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
5271 if report.is_empty() {
5272 return;
5273 }
5274 if !report.quarantined.is_empty() {
5275 tracing::info!(
5276 "triage: held {} blocked task(s) whose blocked-on task or \
5277 question no longer exists: {}",
5278 report.quarantined.len(),
5279 report.quarantined.join(", ")
5280 );
5281 }
5282 if !report.resumed.is_empty() {
5283 tracing::info!(
5284 "triage: resumed {} held task(s) whose machine hold had resolved: {}",
5285 report.resumed.len(),
5286 report.resumed.join(", ")
5287 );
5288 }
5289 if !report.asked.is_empty() {
5290 tracing::info!(
5291 "triage: asked about {} held task(s): {}",
5292 report.asked.len(),
5293 report.asked.join(", ")
5294 );
5295 }
5296 if !report.answered.is_empty() {
5297 tracing::info!(
5298 "triage: applied {} operator answer(s): {}",
5299 report.answered.len(),
5300 report.answered.join(", ")
5301 );
5302 }
5303}
5304
5305pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
5312 disk_gate_with(repo, config, crate::disk::free_bytes)
5313}
5314
5315fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
5319 repo: &Path,
5320 config: &Config,
5321 free_bytes: F,
5322) -> Option<String> {
5323 let min = config.disk.min_free_bytes;
5324 if min == 0 {
5325 return None;
5326 }
5327 let mut paths = vec![repo.to_owned()];
5328 if let Some(cache) = config.cache_dir() {
5329 paths.push(cache);
5330 }
5331 if let Some(root) = &config.graph.worktree_root {
5332 paths.push(root.clone());
5333 }
5334 for path in paths {
5335 let probe = if path == repo {
5336 path.as_path()
5337 } else {
5338 path.ancestors().find(|p| p.exists()).unwrap_or(&path)
5339 };
5340 let reason = match free_bytes(probe) {
5341 Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
5342 Err(e) => Some(crate::disk::unmeasured_in(
5343 probe,
5344 &e,
5345 &config.graph.language,
5346 )),
5347 };
5348 if reason.is_some() {
5349 return reason;
5350 }
5351 }
5352 None
5353}
5354
5355const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
5362
5363const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
5367
5368fn quota_wait(
5377 reset_at: Option<Timestamp>,
5378 now: Timestamp,
5379 fallback: Duration,
5380 cap: Duration,
5381) -> Duration {
5382 match reset_at {
5383 Some(at) if at > now => {
5384 let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
5385 Duration::from_secs(secs).min(cap)
5386 }
5387 _ => fallback,
5388 }
5389}
5390
5391fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
5405 parse_reset_hint_zoned(text, now)
5406 .or_else(|| parse_reset_hint_dated(text))
5407 .or_else(|| parse_reset_hint_relative(text, recorded))
5408}
5409
5410fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
5414 let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
5415 let mut rest = rest.trim();
5416 if rest.is_empty() {
5417 return None;
5418 }
5419 let mut total: i64 = 0;
5420 let mut matched = false;
5421 for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
5422 if let Some((digits, tail)) = rest.split_once(unit)
5423 && !digits.is_empty()
5424 && digits.bytes().all(|b| b.is_ascii_digit())
5425 {
5426 total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
5427 rest = tail;
5428 matched = true;
5429 }
5430 }
5431 if !rest.is_empty() || !matched {
5432 return None;
5433 }
5434 recorded
5435 .checked_add(jiff::SignedDuration::from_secs(total))
5436 .ok()
5437}
5438
5439fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
5443 let clock = clock.trim().to_lowercase();
5444 let (digits, pm) = clock
5445 .strip_suffix("am")
5446 .map(|d| (d, false))
5447 .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
5448 let (h, m) = digits.trim().split_once(':')?;
5449 let mut hour: i8 = h.trim().parse().ok()?;
5450 let minute: i8 = m.trim().parse().ok()?;
5451 if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
5452 return None;
5453 }
5454 if pm && hour != 12 {
5455 hour += 12;
5456 } else if !pm && hour == 12 {
5457 hour = 0;
5458 }
5459 Some((hour, minute))
5460}
5461
5462fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
5467 let open = text.find('(')?;
5468 let close = text.rfind(')')?;
5469 if close <= open {
5470 return None;
5471 }
5472 let zone = text[open + 1..close].trim();
5473 let (hour, minute) = parse_12h_clock(&text[..open])?;
5474 let tz = jiff::tz::TimeZone::get(zone).ok()?;
5475 let candidate = now
5476 .to_zoned(tz)
5477 .with()
5478 .hour(hour)
5479 .minute(minute)
5480 .second(0)
5481 .millisecond(0)
5482 .microsecond(0)
5483 .nanosecond(0)
5484 .build()
5485 .ok()?;
5486 let mut at = candidate.timestamp();
5487 if at <= now {
5488 at += jiff::SignedDuration::from_hours(24);
5489 }
5490 Some(at)
5491}
5492
5493fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
5502 let words: Vec<&str> = text.split_whitespace().collect();
5503 if words.len() < 5 {
5504 return None;
5505 }
5506 (0..=words.len() - 5)
5507 .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
5508}
5509
5510fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
5516 if trailing.is_some_and(|next| next.starts_with('(')) {
5517 return None;
5518 }
5519 let month = month_number(window[0])?;
5520 let day_token = window[1].strip_suffix(',')?.to_lowercase();
5521 let day_digits = ["st", "nd", "rd", "th"]
5522 .iter()
5523 .find_map(|suffix| day_token.strip_suffix(*suffix))?;
5524 let day: i8 = day_digits.parse().ok()?;
5525 let year_token = window[2];
5526 if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
5527 return None;
5528 }
5529 let year: i16 = year_token.parse().ok()?;
5530 let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
5534 let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
5535 let date = jiff::civil::Date::new(year, month, day).ok()?;
5536 let candidate = date
5537 .at(hour, minute, 0, 0)
5538 .to_zoned(jiff::tz::TimeZone::UTC)
5539 .ok()?;
5540 Some(candidate.timestamp())
5541}
5542
5543fn month_number(name: &str) -> Option<i8> {
5546 const NAMES: [&str; 12] = [
5547 "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
5548 ];
5549 let lower = name.to_lowercase();
5550 NAMES
5551 .iter()
5552 .position(|n| *n == lower.as_str())
5553 .map(|i| i as i8 + 1)
5554}
5555
5556#[cfg(test)]
5558fn exhausted_review_budget(state: &RunState) -> bool {
5559 !crate::handover::can_resume(state)
5562 && state.status == RunStatus::Blocked
5563 && !state.released()
5564 && state.retired_to.is_none()
5565}
5566
5567fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
5604 unfinished_run_with(runs, short, RunState::load)
5605}
5606
5607pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
5610where
5611 F: FnMut(&str) -> Result<RunState>,
5612{
5613 let mut id = runs.last()?.clone();
5614 let mut visited = std::collections::BTreeSet::new();
5615 let mut repo = None;
5616 loop {
5617 if !runs.contains(&id) || !visited.insert(id.clone()) {
5618 tracing::warn!("invalid or cyclic recovery authority for task {short}");
5619 return None;
5620 }
5621 let state = match load(&id) {
5622 Ok(state) if state.id == id => state,
5623 Ok(_) => return None,
5624 Err(e) => {
5625 tracing::warn!("could not read run {id} for task {short}: {e:#}");
5626 return None;
5627 }
5628 };
5629 if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
5630 return None;
5631 }
5632 repo = Some(state.repo.clone());
5633 if let Some(authority) = state.retired_to {
5634 id = authority;
5635 continue;
5636 }
5637 return (crate::handover::can_resume(&state)
5638 && state.liveness(false) != crate::run::Liveness::Live)
5639 .then_some(id);
5640 }
5641}
5642
5643fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
5651where
5652 F: FnOnce(&str) -> Result<RunState>,
5653{
5654 if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
5656 || task.fresh_start
5657 || task.review_branch.is_some()
5658 {
5659 return false;
5660 }
5661 let Some(id) = task.runs.last() else {
5662 return false;
5663 };
5664 load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
5665}
5666
5667#[derive(Debug, Clone, PartialEq, Eq)]
5670enum Starter {
5671 Review(String),
5674 Resume(String),
5676 Start,
5678}
5679
5680fn retained_attempt_hold(
5684 task: &Task,
5685 starter: &Starter,
5686 limit: usize,
5687 mut load: impl FnMut(&str) -> Result<RunState>,
5688) -> Option<String> {
5689 if limit == 0 || matches!(starter, Starter::Resume(_)) {
5690 return None;
5691 }
5692 let mut retained = 0;
5693 for id in task.runs.iter().collect::<std::collections::BTreeSet<_>>() {
5694 let state = match load(id) {
5695 Ok(state) if state.id == *id => state,
5696 _ => {
5697 return Some(format!(
5698 "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
5699 ));
5700 }
5701 };
5702 if state.retired_to.is_some() || state.released() {
5703 continue;
5704 }
5705 retained += 1;
5708 }
5709 (retained >= limit).then(|| format!(
5710 "[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."
5711 ))
5712}
5713
5714fn selected_starter(
5716 selected: &crate::pr_recovery::Selection,
5717 previous: Option<&RunState>,
5718 unfinished: Option<&str>,
5719) -> Starter {
5720 if let Some(id) = unfinished
5721 && previous.is_some_and(|r| {
5722 r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
5723 })
5724 {
5725 Starter::Resume(id.to_owned())
5726 } else {
5727 Starter::Review(selected.branch.clone())
5728 }
5729}
5730
5731fn take_divergence_answer(
5735 branch: &str,
5736 remote: &str,
5737 task: &mut Task,
5738) -> Option<crate::reconcile::Choice> {
5739 let summary = crate::reconcile::summary_for(branch, remote);
5740 let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
5741 (a.question == summary)
5742 .then(|| crate::reconcile::Choice::from_answer(&a.answer))
5743 .flatten()
5744 .map(|c| (i, c))
5745 })?;
5746 task.answers.remove(idx);
5747 Some(choice)
5748}
5749
5750fn choose_starter(
5762 review_branch: Option<&str>,
5763 branch_exists: bool,
5764 unfinished: Option<&str>,
5765) -> Starter {
5766 match review_branch {
5767 Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
5768 Some(_) => Starter::Start,
5769 None => match unfinished {
5770 Some(id) => Starter::Resume(id.to_owned()),
5771 None => Starter::Start,
5772 },
5773 }
5774}
5775
5776fn review_retry_starter(
5780 task: &Task,
5781 previous: Option<&RunState>,
5782 branch: Option<&str>,
5783 exists: bool,
5784 unfinished: Option<&str>,
5785) -> Starter {
5786 if let Some(run) = previous
5787 && unfinished == Some(run.id.as_str())
5788 && run.reviewed_commits.is_some()
5789 && branch.is_some_and(|branch| {
5790 exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
5791 })
5792 && may_resume_run(run, task)
5793 {
5794 return Starter::Resume(run.id.clone());
5795 }
5796 match (branch, unfinished, &task.review_of) {
5797 (None, None, Some(branch)) => Starter::Review(branch.clone()),
5798 _ => choose_starter(branch, exists, unfinished),
5799 }
5800}
5801
5802fn take_review_branch(task: &mut Task, previous: Option<&RunState>) -> Option<String> {
5804 let branch = task.review_branch.take();
5805 let instruction = task.review_instruction.take();
5806 branch.filter(|branch| match &instruction {
5807 Some(authored) => *authored == task.instruction,
5808 None => previous.map_or_else(
5811 || task.review_of.as_ref() == Some(branch),
5812 |run| compatible_run_instruction(run, task),
5813 ),
5814 })
5815}
5816
5817fn may_resume_run(run: &RunState, task: &Task) -> bool {
5820 task.resume_override
5821 .as_ref()
5822 .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
5823 || compatible_run_instruction(run, task)
5824}
5825
5826pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
5828 if let Some(authored) = &run.task_instruction {
5829 return compatible_instruction(authored, task);
5830 }
5831 if compatible_instruction(&run.instruction, task) {
5832 return true;
5833 }
5834 if run.reviewed_commits.is_some() {
5837 if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
5838 return strip_answers_block(authored, task).trim() == task.instruction.trim();
5839 }
5840 if let Some(branch) = &task.review_of {
5841 let canonical = format!(
5842 "Review the branch `{branch}` (review-only: no implementation, no judging)."
5843 );
5844 let generated = format!(
5845 "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"
5846 );
5847 return task.instruction == canonical && run.instruction.starts_with(&generated);
5848 }
5849 }
5850 false
5851}
5852
5853pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
5855 strip_answers_block(old, task) == task.instruction
5856}
5857
5858fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
5861 if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
5862 return fallback.to_path_buf();
5863 }
5864 task.repo.clone()
5865}
5866
5867const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
5871
5872fn answers_block(task: &Task, count: usize) -> String {
5874 let mut s = ANSWERS_HEADER.to_owned();
5875 for a in &task.answers[..count] {
5876 s.push_str(&format!("- {}: {}\n", a.question, a.answer));
5877 }
5878 s
5879}
5880
5881fn resumption_block(r: &crate::queue::Resumption) -> String {
5884 format!(
5885 "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
5886 Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
5887 r.generation, r.at, r.instruction, r.answers_through,
5888 )
5889}
5890
5891fn append_answers(base: &str, task: &Task) -> String {
5893 let mut s = base.to_owned();
5894 if !task.answers.is_empty() {
5895 s.push_str(&answers_block(task, task.answers.len()));
5896 }
5897 if let Some(r) = &task.resumption {
5898 s.push_str(&resumption_block(r));
5899 }
5900 s
5901}
5902
5903fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
5907 let mut instruction = instruction;
5908 for approval in task
5909 .resumption
5910 .iter()
5911 .chain(task.resumption_history.iter().rev())
5912 {
5913 if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
5914 instruction = base;
5915 break;
5916 }
5917 }
5918 for count in (1..=task.answers.len()).rev() {
5919 let block = answers_block(task, count);
5920 if let Some(base) = instruction.strip_suffix(&block) {
5921 return base;
5922 }
5923 }
5924 instruction
5925}
5926
5927fn instruction_for(task: &Task) -> String {
5935 append_answers(&task.instruction, task)
5936}
5937
5938fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
5950 append_answers(strip_answers_block(old_instruction, task), task)
5951}
5952
5953fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
5955 let failure = error.downcast_ref::<crate::config::ConfigFailure>();
5956 task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
5957 if let Some(cause) = task.hold_notice_cause.as_mut() {
5958 cause.target = failure.map(|f| f.target.clone());
5959 }
5960}
5961
5962#[derive(Debug, thiserror::Error)]
5963#[error("attachment `{name}` is recorded on the task but {path} is missing")]
5964struct MissingAttachment {
5965 name: String,
5966 path: PathBuf,
5967}
5968
5969fn task_attachments(
5971 queue: &Queue,
5972 task: &Task,
5973) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
5974 let paths = queue.attachment_paths(task);
5975 for (name, path) in task.attachments.iter().zip(&paths) {
5976 if !path.is_file() {
5977 return Err(MissingAttachment {
5978 name: name.clone(),
5979 path: path.clone(),
5980 });
5981 }
5982 }
5983 Ok(paths)
5984}
5985
5986fn prepare_instruction(
5997 starter: &Starter,
5998 old_instruction: Option<&str>,
5999 task: &Task,
6000) -> Option<String> {
6001 match starter {
6002 Starter::Start => Some(instruction_for(task)),
6003 Starter::Resume(_) => Some(resumed_instruction(
6004 old_instruction.expect("a resumed run always has a prior instruction"),
6005 task,
6006 )),
6007 Starter::Review(_) => None,
6008 }
6009}
6010
6011fn record(queue: &Queue, task: &mut Task) {
6015 if let Err(e) = queue.put(task) {
6016 tracing::error!("could not record task {}: {e:#}", task.short());
6017 let notice = Notice::error(
6018 "loop:record",
6019 format!(
6020 "Task {} state could not be saved: {}. Check the disk.",
6021 task.id,
6022 e.to_string().lines().next().unwrap_or("unknown save error")
6023 ),
6024 )
6025 .link(Link::Task {
6026 id: task.id.clone(),
6027 });
6028 match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
6030 Some(home) => notices::raise_in(home, notice),
6031 None => notices::raise(notice),
6032 }
6033 }
6034}
6035
6036fn runnable(queue: &Queue) -> Vec<Task> {
6042 let mut tasks: Vec<Task> = queue
6043 .list()
6044 .into_iter()
6045 .filter(|t| t.status.runnable())
6046 .collect();
6047 tasks.sort_unstable_by(crate::queue::dispatch_order);
6048 tasks
6049}
6050
6051fn describe(state: &RunState) -> String {
6065 let p = phrases(&state.config.graph.language);
6066 let mut detail = if state.status == RunStatus::Stalled {
6067 let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
6068 seats.sort_unstable();
6069 seats.dedup();
6070 if seats.is_empty() {
6071 p.quorum_lost.to_owned()
6072 } else {
6073 format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
6074 }
6075 } else {
6076 format!("{}{}", p.run_ended, state.status.display_label())
6077 };
6078 if let Some(cause) = state.verification_blocking_cause() {
6079 detail.push_str(&format!(" ({cause})"));
6080 } else if let Some(last) = state.events.last() {
6081 let unanswered = state
6085 .reviews
6086 .last()
6087 .filter(|r| {
6088 state.status == RunStatus::Blocked
6089 && last.node == "review"
6090 && r.incomplete()
6091 && r.blocking == 0
6092 && r.round == state.config.graph.review_rounds
6093 && r.e2e.iter().all(crate::run::CommandOutcome::ok)
6094 })
6095 .map(|r| (r.expected - r.answered, r.round));
6096 match unanswered {
6097 Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
6098 detail.push_str(&format!(
6099 " ({}: {})",
6100 last.node,
6101 (p.reviewers_never_answered)(missing, rounds)
6102 ));
6103 }
6104 _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
6105 }
6106 }
6107 detail.push_str(&format!(" [run {}]", state.id));
6108 detail
6109}
6110
6111const DIAGNOSTIC_MAX: usize = 4_000;
6117
6118const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
6123
6124fn diagnostic(state: &RunState) -> Option<String> {
6138 let mut parts: Vec<String> = Vec::new();
6139
6140 for o in state.gate.iter().filter(|o| !o.ok()) {
6142 parts.push(format!(
6143 "gate `{}` failed ({}):\n{}",
6144 o.command,
6145 notices::exit_status(o.code),
6146 crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
6147 ));
6148 }
6149
6150 if let Some(last) = state
6153 .events
6154 .iter()
6155 .rev()
6156 .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
6157 {
6158 parts.push(last.message.clone());
6159 }
6160
6161 if state.viable().is_empty() {
6168 for c in &state.candidates {
6169 if let Some(evidence) = &c.verified_noop {
6170 parts.push(format!(
6171 "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
6172 c.label
6173 ));
6174 } else if !c.summary.trim().is_empty() {
6175 parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
6176 } else if let Some(why) = &c.failed {
6177 parts.push(format!("candidate {}: {why}", c.label));
6178 }
6179 }
6180 }
6181
6182 if parts.is_empty() {
6183 return None;
6184 }
6185 Some(crate::run::tail(
6190 &parts.join("\n\n"),
6191 DIAGNOSTIC_MAX.saturating_sub(100),
6192 ))
6193}
6194
6195fn label(status: RunStatus) -> &'static str {
6203 status.as_str()
6204}
6205
6206pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
6208 match mode {
6209 "none" => Ok(MergeMode::None),
6210 "local" => Ok(MergeMode::Local),
6211 "pr" => Ok(MergeMode::Pr),
6212 other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
6213 }
6214}
6215
6216fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
6221 mutex
6222 .lock()
6223 .unwrap_or_else(std::sync::PoisonError::into_inner)
6224}
6225
6226#[cfg(test)]
6227mod tests {
6228 use super::*;
6229 use crate::queue::{Source, TaskStatus};
6230 use crate::run::{Candidate, CommandOutcome};
6231 use pretty_assertions::assert_eq;
6232
6233 fn task() -> Task {
6234 Task::new(
6235 "add retries".to_owned(),
6236 "add retries".to_owned(),
6237 PathBuf::from("/repo"),
6238 Source::Human,
6239 )
6240 }
6241
6242 fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
6243 let job = crate::worker::Job {
6244 id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
6245 sequence: 1,
6246 kind: "task".into(),
6247 key: format!("task:{}", request.task),
6248 payload: serde_json::to_value(request).unwrap(),
6249 generation: "a".repeat(64),
6250 version: None,
6251 status: crate::worker::Status::Starting,
6252 result: None,
6253 pid: None,
6254 created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
6255 finished_at: None,
6256 };
6257 let dir = home.join("workers/jobs").join(&job.id);
6258 std::fs::create_dir_all(&dir).unwrap();
6259 std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
6260 job
6261 }
6262
6263 #[test]
6264 fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
6265 let home = tempfile::tempdir().unwrap();
6266 let request = TaskWorker {
6267 opts: Opts::default(),
6268 queue: home.path().join("queue"),
6269 task: "startup".into(),
6270 lane: PermitKind::Ordinary,
6271 standalone: false,
6272 };
6273 let job = starting_task_reservation(home.path(), &request);
6274 let error = task_worker_spawn_error(
6275 home.path(),
6276 &request,
6277 anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
6278 )
6279 .expect_err("our own reservation must not turn a failed spawn into a resync");
6280 let active = crate::worker::active(home.path()).unwrap();
6281 assert_eq!(active.len(), 1);
6282 assert_eq!(active[0].id, job.id);
6283 assert_eq!(active[0].status, crate::worker::Status::Starting);
6284 assert!(
6285 crate::worker::control(home.path(), &job.key)
6286 .unwrap()
6287 .is_none()
6288 );
6289 let notices = notices::Notices::at(home.path().join("notifications")).list();
6290 assert_eq!(notices.len(), 1);
6291 assert_eq!(notices[0].key, "loop:worker-startup");
6292 assert!(!notices[0].message.contains("private-error-detail"));
6293 assert!(notices[0].message.contains(&request.task));
6294 assert!(
6295 notices[0]
6296 .message
6297 .contains("could not be started or acknowledged")
6298 );
6299 assert!(notices[0].message.contains("worker.log"));
6300 assert_eq!(
6301 notices[0].link,
6302 Some(Link::Task {
6303 id: request.task.clone()
6304 })
6305 );
6306 assert!(format!("{error:#}").contains("private-error-detail"));
6307 }
6308
6309 #[test]
6310 fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
6311 let home = tempfile::tempdir().unwrap();
6312 let mut request = TaskWorker {
6313 opts: Opts::default(),
6314 queue: home.path().join("queue"),
6315 task: "handoff".into(),
6316 lane: PermitKind::Ordinary,
6317 standalone: true,
6318 };
6319 let job = starting_task_reservation(home.path(), &request);
6320 request.standalone = false;
6321 task_worker_spawn_error(
6322 home.path(),
6323 &request,
6324 anyhow::anyhow!("operation key is already reserved for a different request"),
6325 )
6326 .expect("a different standalone request is the handoff race, not our startup failure");
6327 let active = crate::worker::active(home.path()).unwrap();
6328 assert_eq!(active.len(), 1);
6329 assert_eq!(active[0].id, job.id);
6330 assert_eq!(active[0].payload, job.payload);
6331 assert!(
6332 notices::Notices::at(home.path().join("notifications"))
6333 .list()
6334 .is_empty()
6335 );
6336 }
6337
6338 #[test]
6339 fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
6340 let home = tempfile::tempdir().unwrap();
6341 let queue = Queue::at(home.path().join("queue"));
6342 let mut task = task();
6343 task.runs = vec!["previous".into()];
6344 queue.put(&mut task).unwrap();
6345 let request = TaskWorker {
6346 opts: Opts::default(),
6347 queue: home.path().join("queue"),
6348 task: task.id.clone(),
6349 lane: PermitKind::Ordinary,
6350 standalone: false,
6351 };
6352 let job = starting_task_reservation(home.path(), &request);
6353 let claims = current_work(home.path(), Timestamp::now());
6354 assert_eq!(claims.len(), 1);
6355 assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
6356 assert_eq!(claims[0].run, "previous");
6357 assert!(other_claims_run(&claims, "previous", None));
6358 assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
6361 assert!(is_working_on(home.path(), "previous", Timestamp::now()));
6362 }
6363
6364 #[test]
6365 fn admission_excludes_only_the_callers_exact_reservation() {
6366 let own = Current {
6367 worker: Some("own".into()),
6368 task: "same-task".into(),
6369 run: "previous".into(),
6370 };
6371 assert!(!other_claims_run(
6372 std::slice::from_ref(&own),
6373 "previous",
6374 Some("own")
6375 ));
6376 assert!(other_claims_run(
6377 std::slice::from_ref(&own),
6378 "previous",
6379 None
6380 ));
6381 for worker in [None, Some("other".into())] {
6382 let other = Current {
6383 worker,
6384 ..own.clone()
6385 };
6386 assert!(other_claims_run(
6387 &[own.clone(), other],
6388 "previous",
6389 Some("own")
6390 ));
6391 }
6392 let legacy: Current =
6393 serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
6394 assert!(other_claims_run(&[legacy], "previous", Some("own")));
6395 }
6396
6397 #[test]
6398 fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
6399 let mut task = task();
6400 let mut run = run_state(RunStatus::Reviewing);
6401 run.task_instruction = Some(task.instruction.clone());
6402 run.reviewed_commits = Some(vec!["committed-fix".into()]);
6403 let branch = "magi/test/B";
6404 run.candidates.push(crate::run::Candidate {
6405 branch: branch.into(),
6406 ..candidate('B', "preserved work", false, None)
6407 });
6408 task.runs = vec![run.id.clone()];
6409 let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
6410 assert_eq!(
6411 review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
6412 Starter::Resume(run.id.clone())
6413 );
6414 assert!(matches!(
6415 review_retry_starter(
6416 &task,
6417 Some(&run),
6418 Some("different"),
6419 true,
6420 unfinished.as_deref()
6421 ),
6422 Starter::Review(_)
6423 ));
6424 assert_eq!(
6425 review_retry_starter(
6426 &task,
6427 Some(&run),
6428 Some(branch),
6429 false,
6430 unfinished.as_deref()
6431 ),
6432 Starter::Start
6433 );
6434 task.instruction.push_str(" changed criteria");
6435 assert!(matches!(
6436 review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
6437 Starter::Review(_)
6438 ));
6439 assert!(matches!(
6440 review_retry_starter(&task, Some(&run), Some(branch), true, None),
6441 Starter::Review(_)
6442 ));
6443 }
6444
6445 #[test]
6446 fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
6447 let dir = tempfile::tempdir().unwrap();
6448 let queue = Queue::at(dir.path().join("queue"));
6449 let mut task = task();
6450 task.status = TaskStatus::Running;
6451 task.attempts = 1;
6452 queue.put(&mut task).unwrap();
6453 let live = std::collections::BTreeSet::from([task.id.clone()]);
6454 assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
6455 drop(queue.claim(&task.id).unwrap());
6456 let saved = queue.get(&task.id).unwrap();
6457 assert_eq!(saved.status, TaskStatus::Running);
6458 assert_eq!(saved.attempts, 1);
6459 assert!(saved.last_error.is_none());
6460 }
6461
6462 #[test]
6463 fn standalone_workers_do_not_consume_scheduler_lanes() {
6464 let request = |task: &str, lane, standalone| TaskWorker {
6465 opts: Opts::default(),
6466 queue: PathBuf::from("/queue"),
6467 task: task.to_owned(),
6468 lane,
6469 standalone,
6470 };
6471 let mut jobs = vec![
6472 request("ordinary", PermitKind::Ordinary, false),
6473 request("standalone-urgent", PermitKind::Urgent, true),
6474 request("standalone-ordinary", PermitKind::Ordinary, true),
6475 request("decision", PermitKind::None, false),
6476 ];
6477 assert_eq!(available_slots(&jobs, 2), (1, 1));
6478 jobs.push(request("urgent", PermitKind::Urgent, false));
6479 assert_eq!(available_slots(&jobs, 2), (1, 0));
6480 assert_eq!(available_slots(&jobs, 0), (0, 0));
6481 }
6482
6483 #[test]
6484 fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
6485 let now = Timestamp::now();
6486 let mut reading = Reading {
6487 pid: Some(std::process::id()),
6488 updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
6489 ..Reading::default()
6490 };
6491 assert!(!reading.running(now));
6492 assert!(legacy_scheduler_running(&reading, now, 0));
6493 reading.worker_protocol = Some(1);
6494 assert!(!legacy_scheduler_running(&reading, now, 0));
6495 }
6496
6497 #[test]
6498 fn selected_public_head_overrides_historical_resume_and_pin() {
6499 let mut t = task();
6500 let mut old = run_state(RunStatus::Blocked);
6501 let selection = crate::pr_recovery::Selection {
6502 url: "url".into(),
6503 branch: format!("magi/task-{}", t.id),
6504 head: "a".repeat(40),
6505 source_head: None,
6506 source_run: None,
6507 source_proof: None,
6508 disposition: Some(crate::pr_recovery::Disposition::Review),
6509 instruction: t.instruction.clone(),
6510 approved_at: Timestamp::now(),
6511 };
6512 t.resume_override = Some(crate::queue::OperatorResume {
6513 pinned_run: Some(old.id.clone()),
6514 question_id: "choice".into(),
6515 at: Timestamp::now(),
6516 conductor_rehold: None,
6517 forced: false,
6518 });
6519 assert_eq!(
6520 selected_starter(&selection, Some(&old), Some(&old.id)),
6521 Starter::Review(selection.branch.clone())
6522 );
6523 old.pr_recovery = Some(selection.clone());
6524 assert_eq!(
6525 selected_starter(&selection, Some(&old), Some(&old.id)),
6526 Starter::Review(selection.branch.clone())
6527 );
6528 old.reviewed_commits = Some(vec!["implementation".into()]);
6529 assert_eq!(
6530 selected_starter(&selection, Some(&old), Some(&old.id)),
6531 Starter::Resume(old.id.clone())
6532 );
6533 let mut changed = selection.clone();
6534 changed.head = "b".repeat(40);
6535 assert_eq!(
6536 selected_starter(&changed, Some(&old), Some(&old.id)),
6537 Starter::Review(changed.branch)
6538 );
6539 }
6540
6541 #[test]
6542 fn candidate_transplant_failure_is_one_actionable_hold() {
6543 let dir = tempfile::tempdir().unwrap();
6544 let q = Queue::at(dir.path().join("queue"));
6545 let mut t = task();
6546 let mut state = run_state(RunStatus::Blocked);
6547 state.event("prep", "cannot apply referenced commit: conflict");
6548 state.prep_failure = Some("conflict".into());
6549 t.start(state.id.clone());
6550 finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
6551 assert_eq!(t.attempts, 1);
6552 assert_eq!(t.status, TaskStatus::Held);
6553 assert!(t.operator_held());
6554 assert!(!t.status.runnable());
6555 assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
6556 let first = t.chat_notice_key().unwrap();
6557 t.chat_notices.push(first.clone());
6558 t.release_operator("test", None);
6559 state.id = "another-unprepared-run".into();
6560 t.start(state.id.clone());
6561 finish_attempt(
6562 3,
6563 &q,
6564 &mut t,
6565 &state,
6566 &[],
6567 Err(anyhow::anyhow!("still conflicts")),
6568 );
6569 assert_eq!(
6570 t.chat_notice_key().as_ref(),
6571 Some(&first),
6572 "no work happened"
6573 );
6574 t.release_operator("test", None);
6575 state.prep_failure = None;
6576 state.status = RunStatus::Failed;
6577 state.begin_pass();
6578 t.start(state.id.clone());
6579 finish_attempt(
6580 1,
6581 &q,
6582 &mut t,
6583 &state,
6584 &[],
6585 Err(anyhow::anyhow!("new gate failure")),
6586 );
6587 let failure = t.chat_notice_key().unwrap();
6588 assert_ne!(failure, first, "approved recovery reached a real failure");
6589 t.release_operator("test", None);
6590 state.begin_pass();
6591 t.start(state.id.clone());
6592 finish_attempt(
6593 1,
6594 &q,
6595 &mut t,
6596 &state,
6597 &[],
6598 Err(anyhow::anyhow!("new failure on resume")),
6599 );
6600 assert_ne!(
6601 t.chat_notice_key().as_ref(),
6602 Some(&failure),
6603 "a new settled pass"
6604 );
6605 }
6606
6607 #[test]
6608 fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
6609 for source in ["cli", "web"] {
6610 let mut t = task();
6611 let mut run = run_state(RunStatus::Blocked);
6612 run.instruction = "Run A original criteria".into();
6613 run.task_instruction = Some(run.instruction.clone());
6614 t.start(run.id.clone());
6615 t.release_operator("choice", Some("resume-question"));
6616 t.resume_override = Some(crate::queue::OperatorResume {
6617 question_id: "resume-question".into(),
6618 at: Timestamp::now(),
6619 conductor_rehold: None,
6620 forced: true,
6621 pinned_run: Some(run.id.clone()),
6622 });
6623 t.hold_machine(Some("not enough free space to start a run".into()));
6624 let mut unchanged = t.clone();
6625 unchanged
6626 .edit("title changed".into(), unchanged.instruction.clone())
6627 .unwrap();
6628 unchanged.release_operator(source, None);
6629 assert_eq!(
6630 unchanged
6631 .resume_override
6632 .as_ref()
6633 .unwrap()
6634 .pinned_run
6635 .as_deref(),
6636 Some(run.id.as_str())
6637 );
6638 assert!(!compatible_run_instruction(&run, &unchanged));
6639 assert!(may_resume_run(&run, &unchanged));
6640
6641 t.edit(
6642 "approved recovery".into(),
6643 "Reuse measured PR head B; fix Clippy; review".into(),
6644 )
6645 .unwrap();
6646 assert!(t.resume_override.is_none());
6647 t.release_operator(source, None);
6648 let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
6649 assert!(reloaded.resume_override.is_none());
6650 assert!(!may_resume_run(&run, &reloaded));
6651 let unfinished =
6652 unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
6653 .filter(|_| may_resume_run(&run, &reloaded));
6654 assert_eq!(
6655 choose_starter(None, false, unfinished.as_deref()),
6656 Starter::Start
6657 );
6658 assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
6659 assert_eq!(
6660 reloaded.resumption_history[0].question_id.as_deref(),
6661 Some("resume-question")
6662 );
6663
6664 unchanged.instruction = "Reuse measured PR head B".into();
6667 unchanged.hold_machine(Some("disk hold".into()));
6668 unchanged.release_operator(source, None);
6669 assert!(unchanged.resume_override.is_none());
6670 assert!(!may_resume_run(&run, &unchanged));
6671 }
6672 }
6673
6674 #[test]
6675 fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
6676 let mut t = task();
6677 let mut run = run_state(RunStatus::Blocked);
6678 t.review_of = Some("approved-head".into());
6679 t.instruction =
6680 "Review the branch `approved-head` (review-only: no implementation, no judging)."
6681 .into();
6682 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();
6683 run.reviewed_commits = Some(vec!["Commit log".into()]);
6684 t.start(run.id.clone());
6685 t.hold_machine(Some("interrupted review".into()));
6686 t.release_operator("cli", None);
6687 assert!(
6688 compatible_run_instruction(&run, &t),
6689 "legacy explicit review remains resumable"
6690 );
6691 let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
6692 .filter(|_| compatible_run_instruction(&run, &t));
6693 assert_eq!(
6694 choose_starter(None, false, unfinished.as_deref()),
6695 Starter::Resume(run.id.clone())
6696 );
6697 run.task_instruction = Some(t.instruction.clone());
6698 assert!(compatible_run_instruction(&run, &t));
6699 let reloaded: RunState =
6700 serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
6701 assert!(compatible_run_instruction(&reloaded, &t));
6702 t.edit(
6703 "new approved head".into(),
6704 "Reuse measured PR head B".into(),
6705 )
6706 .unwrap();
6707 assert!(!compatible_run_instruction(&run, &t));
6708
6709 t.review_of = None;
6711 t.instruction = "Fix Clippy on approved head".into();
6712 run.task_instruction = None;
6713 run.instruction = format!(
6714 "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
6715 t.instruction
6716 );
6717 assert!(compatible_run_instruction(&run, &t));
6718 t.instruction.push('\n');
6719 assert!(
6720 compatible_run_instruction(&run, &t),
6721 "legacy generated review trimmed the original criteria"
6722 );
6723 t.hold_for_handover(Some("approved-head".into()), "refused".into());
6724 let mut unchanged = t.clone();
6725 assert_eq!(
6726 take_review_branch(&mut unchanged, Some(&run)).as_deref(),
6727 Some("approved-head")
6728 );
6729 t.edit("new plan".into(), "Reuse measured PR head B".into())
6730 .unwrap();
6731 assert!(take_review_branch(&mut t, Some(&run)).is_none());
6732 assert!(!compatible_run_instruction(&run, &t));
6733 t.review_branch = Some("approved-head".into());
6734 t.review_instruction = None;
6735 assert!(
6736 take_review_branch(&mut t, Some(&run)).is_none(),
6737 "legacy retained candidate cannot replace a revised approved head"
6738 );
6739 }
6740
6741 #[test]
6742 fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
6743 crate::run::pin_test_home();
6744 let dir = tempfile::tempdir().unwrap();
6745 let queue = Queue::at(dir.path().join("queue"));
6746 for resume in [true, false] {
6747 let state = run_state(RunStatus::Blocked);
6748 let mut t = task();
6749 t.start(state.id.clone());
6750 let action = if resume {
6751 ask::ChoiceAction::Resume {
6752 run: state.id.clone(),
6753 }
6754 } else {
6755 ask::ChoiceAction::Requeue
6756 };
6757 let mut q = action_question(&state.id, action);
6758 q.status = ask::QuestionStatus::Open;
6759 q.answer = None;
6760 q.answered_at = None;
6761 t.fail("run stopped with a question", 3);
6762 hold_if_runnable(&queue, &mut t);
6763 assert!(t.operator_decided_at.is_none());
6764 assert!(t.operator_held());
6765 q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
6766 let expected = if resume {
6767 ActionDecision::Resume(state.id.clone())
6768 } else {
6769 ActionDecision::Requeue
6770 };
6771 assert_eq!(
6772 decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
6773 expected
6774 );
6775 t.hold_manual(Some("later explicit hold".into()));
6776 assert_eq!(
6777 decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
6778 ActionDecision::Stale
6779 );
6780 }
6781 }
6782
6783 #[test]
6784 fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
6785 let mut t = task();
6786 t.answers.push(crate::queue::AnsweredQuestion {
6787 question: "Inspect the remote?".into(),
6788 answer: "Inspect then wait".into(),
6789 });
6790 let old = instruction_for(&t);
6791 assert!(compatible_instruction(&old, &t));
6792 t.instruction = "Reuse approved PR head and review".into();
6793 t.release_operator("cli", None);
6794 assert!(!compatible_instruction(&old, &t));
6795 let approved = instruction_for(&t);
6796 assert!(approved.contains("waiting premises are superseded"));
6797 assert!(compatible_instruction(&approved, &t));
6798 assert_eq!(resumed_instruction(&approved, &t), approved);
6799 t.release_operator("web", None);
6800 assert!(compatible_instruction(&approved, &t));
6801 assert_eq!(t.resumption_history.len(), 1);
6802 t.start("run".into());
6803 assert!(instruction_for(&t).contains("Explicit operator resumption"));
6804 }
6805
6806 #[test]
6810 fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
6811 let mut state = RunState::new(
6812 PathBuf::from("/repo"),
6813 "main".into(),
6814 "base".into(),
6815 "task".into(),
6816 Config::default(),
6817 );
6818 state.status = RunStatus::Landing;
6819 state.parked = true;
6820 state.pr_pushed_head = Some("head".into());
6821 state.land_unrelated = Some(
6822 serde_json::from_value(serde_json::json!({
6823 "head": "head", "question": "ci-question",
6824 "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
6825 }))
6826 .unwrap(),
6827 );
6828 let mut t = task();
6829 t.start(state.id.clone());
6830 let verdict = Verdict {
6831 status: RunStatus::Landing,
6832 left_pr: true,
6833 quota_hit: false,
6834 parked: true,
6835 no_viable_candidates: false,
6836 };
6837 settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
6838 assert_eq!(t.attempts, 0);
6839 assert_eq!(t.status, TaskStatus::Held);
6840 assert!(!t.operator_held());
6841 assert!(
6842 t.hold_reason
6843 .as_deref()
6844 .unwrap()
6845 .starts_with("[ci-unrelated]")
6846 );
6847 t.attempts = 1;
6849 settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
6850 assert_eq!(t.attempts, 1);
6851 assert_eq!(t.passes.len(), 1);
6852 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
6853 state.pr_pushed_head = Some("new-head".into());
6854 state.parked = false;
6855 state.status = RunStatus::Blocked;
6856 let stale = Verdict {
6857 status: RunStatus::Blocked,
6858 parked: false,
6859 ..verdict
6860 };
6861 settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
6862 assert_eq!(t.attempts, 1);
6863 state.begin_pass();
6865 state.begin_pass();
6866 state.status = RunStatus::Landing;
6867 state.parked = true;
6868 state.pr_pushed_head = Some("head".into());
6869 settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
6870 assert_eq!(t.attempts, 0);
6871 assert_eq!(t.passes.len(), 2);
6872 }
6873
6874 #[test]
6875 fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
6876 let mut state = RunState::new(
6877 PathBuf::from("/repo"),
6878 "main".to_owned(),
6879 "abc1234".to_owned(),
6880 "task".to_owned(),
6881 Config::default(),
6882 );
6883 state.status = RunStatus::Blocked;
6884 state.resource_block = Some(crate::run::ResourceBlock {
6885 cause: crate::run::ResourceBlockCause::Other,
6886 node: "graft".to_owned(),
6887 kind: "shared build cache".to_owned(),
6888 detail: "timed out".to_owned(),
6889 at: jiff::Timestamp::now(),
6890 });
6891 let mut t = task();
6892 t.start("20260902-000000-aaaa".to_owned());
6893 assert_eq!(t.attempts, 1);
6894 let verdict = Verdict {
6895 status: RunStatus::Blocked,
6896 left_pr: false,
6897 quota_hit: false,
6898 parked: false,
6899 no_viable_candidates: false,
6900 };
6901 settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
6902 assert_eq!(t.status, TaskStatus::Held);
6903 assert_eq!(t.attempts, 0, "the attempt is refunded");
6904 assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
6905 assert!(
6906 !t.operator_held(),
6907 "a machine hold, released without a human"
6908 );
6909
6910 let mut selected = task();
6911 selected.start("20260902-000000-cccc".into());
6912 selected.replacement = Some(crate::merge_decision::Replacement {
6913 question: "fixture".into(),
6914 run: "earlier".into(),
6915 pr: "https://example.invalid/pr/1".into(),
6916 agent: "selected".into(),
6917 context: "fixture".into(),
6918 });
6919 state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
6920 settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
6921 assert_eq!(selected.attempts, 0);
6922 assert!(
6923 !selected.operator_held(),
6924 "a selected agent also retains a machine resource hold"
6925 );
6926 assert!(
6927 selected
6928 .hold_reason
6929 .as_deref()
6930 .unwrap()
6931 .starts_with("[resource] ")
6932 );
6933
6934 let mut p = task();
6936 p.start("20260902-000000-bbbb".to_owned());
6937 settle_and_diagnose(
6938 &mut p,
6939 Verdict {
6940 parked: true,
6941 ..verdict
6942 },
6943 "parked",
6944 2,
6945 &state,
6946 );
6947 assert_eq!(p.status, TaskStatus::Parked);
6948 assert_eq!(
6949 p.attempts, 0,
6950 "parking refunds once rather than also settling the resource hold"
6951 );
6952 }
6953
6954 #[test]
6955 fn record_failure_notice_links_the_task() {
6956 let dir = tempfile::tempdir().unwrap();
6957 std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
6960 let queue = Queue::at(dir.path().join("queue"));
6961 let mut t = interrupt_task("rec-fail-1");
6962 record(&queue, &mut t);
6963
6964 let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
6965 assert_eq!(found.len(), 1);
6966 assert_eq!(found[0].key, "loop:record");
6967 assert_eq!(
6968 found[0].link,
6969 Some(Link::Task {
6970 id: "rec-fail-1".to_owned()
6971 })
6972 );
6973 }
6974
6975 fn interrupt_task(id: &str) -> Task {
6978 let mut t = task();
6979 t.id = id.to_owned();
6980 t.interrupt = true;
6981 t
6982 }
6983
6984 fn task_with_id(id: &str) -> Task {
6986 let mut t = task();
6987 t.id = id.to_owned();
6988 t
6989 }
6990
6991 fn urgent_task(id: &str) -> Task {
6993 let mut t = task();
6994 t.id = id.to_owned();
6995 t.urgent = true;
6996 t
6997 }
6998
6999 #[test]
7000 fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
7001 let dir = tempfile::tempdir().unwrap();
7002 let queue = Queue::at(dir.path().join("queue"));
7003 let mut parked = task_with_id("parked");
7004 parked.start("run".into());
7005 parked.park("upgrade");
7006 parked.record_pass_at(
7007 "run",
7008 0,
7009 Some(Timestamp::now()),
7010 1,
7011 Some(crate::run::ParkCause::Upgrade {
7012 from: "old".into(),
7013 to: None,
7014 }),
7015 );
7016 let mut fresh = task_with_id("fresh");
7017 fresh.priority = 100;
7018 let mut urgent_task = urgent_task("urgent");
7019 for t in [&mut parked, &mut fresh, &mut urgent_task] {
7020 queue.put(t).unwrap();
7021 }
7022 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7023 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7024 let candidates = runnable(&queue);
7025 assert_eq!(candidates[0].id, parked.id);
7026 let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
7027 assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_none());
7028 assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_some());
7029 drop(first);
7030 let claimed_elsewhere = queue.claim(&parked.id).unwrap();
7031 let next = runnable(&queue)
7032 .into_iter()
7033 .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent))
7034 .unwrap();
7035 assert_eq!(next.task.id, fresh.id);
7036 assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
7037 drop(claimed_elsewhere);
7038 drop(next);
7039 assert!(claim_dispatch(&queue, &parked, true, &ordinary, &urgent).is_none());
7040 }
7041
7042 #[test]
7043 fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
7044 let dir = tempfile::tempdir().unwrap();
7045 let queue = Queue::at(dir.path().join("queue"));
7046 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7047 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7048 let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
7049 let mut first = task();
7050 queue.put(&mut first).unwrap();
7051 let stale_plain = queue.get(&first.id).unwrap();
7052 first.set_urgent(true).unwrap();
7053 queue.put(&mut first).unwrap();
7054 let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
7055 let mut second = urgent_task("second");
7056 queue.put(&mut second).unwrap();
7057 assert!(claim_dispatch(&queue, &second, false, &ordinary, &urgent).is_none());
7058 drop(queue.claim(&second.id).unwrap());
7059 assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
7060 drop(dispatched);
7061 let stale_urgent = queue.get(&first.id).unwrap();
7062 first.set_urgent(false).unwrap();
7063 queue.put(&mut first).unwrap();
7064 assert!(claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent).is_none());
7065 assert_eq!(urgent.available_permits(), 1);
7066 drop(queue.claim(&first.id).unwrap());
7067 drop(occupied);
7068 }
7069
7070 #[test]
7071 fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
7072 let dir = tempfile::tempdir().unwrap();
7073 let queue = Queue::at(dir.path().join("queue"));
7074 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7075 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7076 let mut t = task();
7077 queue.put(&mut t).unwrap();
7078 for enabled in [true, false] {
7079 let stale = queue.get(&t.id).unwrap();
7080 t.set_urgent(enabled).unwrap();
7081 queue.put(&mut t).unwrap();
7082 assert_ne!(stale.urgent, enabled);
7083 let DispatchClaim {
7084 task: fresh,
7085 claim,
7086 permit,
7087 } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
7088 assert_eq!(fresh.urgent, enabled);
7089 assert_eq!(ordinary.available_permits(), usize::from(enabled));
7090 assert_eq!(urgent.available_permits(), usize::from(!enabled));
7091 assert!(queue.claim(&t.id).is_err());
7092 assert_eq!(fresh.attempts, stale.attempts);
7093 drop((claim, permit));
7094 assert_eq!(ordinary.available_permits(), 1);
7095 assert_eq!(urgent.available_permits(), 1);
7096 }
7097 t.set_urgent(true).unwrap();
7098 queue.put(&mut t).unwrap();
7099 let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
7100 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7101 assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
7102 drop(queue.claim(&t.id).unwrap());
7103 assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
7104 drop(occupied);
7105 assert!(claim_dispatch(&queue, &t, true, &ordinary, &urgent).is_none());
7106 drop(queue.claim(&t.id).unwrap());
7107 let held = queue.claim(&t.id).unwrap();
7108 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7109 drop(held);
7110 t.status = TaskStatus::Held;
7111 queue.put(&mut t).unwrap();
7112 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7113 drop(queue.claim(&t.id).unwrap());
7114 std::fs::remove_file(queue.path_of(&t.id)).unwrap();
7115 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7116 drop(queue.claim(&t.id).unwrap());
7117 assert_eq!(urgent.available_permits(), 1);
7118 }
7119
7120 #[test]
7125 fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
7126 assert_eq!(permit_kind(true, false), PermitKind::None);
7127 assert_eq!(permit_kind(true, true), PermitKind::None);
7128 }
7129
7130 #[test]
7135 fn permit_kind_separates_urgent_from_ordinary() {
7136 assert_eq!(permit_kind(false, true), PermitKind::Urgent);
7137 assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
7138 }
7139
7140 #[test]
7147 fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
7148 let cfg = Config::default();
7149 let repo = Path::new("/any/repo/path");
7150
7151 let reason =
7152 disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
7153 assert!(reason.contains("1024"), "{reason}");
7154 assert!(
7155 reason.contains(&cfg.disk.min_free_bytes.to_string()),
7156 "{reason}"
7157 );
7158
7159 assert_eq!(
7160 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
7161 None,
7162 "exactly at the floor is open"
7163 );
7164 assert_eq!(
7165 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
7166 None,
7167 "comfortably above the floor is open"
7168 );
7169 }
7170
7171 #[test]
7172 fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
7173 let mut cfg = Config::default();
7174 cfg.disk.min_free_bytes = 0;
7175 let repo = Path::new("/any/repo/path");
7176 assert_eq!(
7177 disk_gate_with(repo, &cfg, |_| Ok(0)),
7178 None,
7179 "a zero floor never measures at all"
7180 );
7181 }
7182
7183 #[test]
7184 fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
7185 let cfg = Config::default();
7186 let repo = Path::new("/any/repo/path");
7187 let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
7188 .expect("a measurement failure must close the gate, not open it");
7189 assert!(reason.contains("could not measure"), "{reason}");
7190 }
7191
7192 #[test]
7193 fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
7194 let ordinary = task();
7195 let next = advance_interrupt(
7196 Interrupt::Idle,
7197 std::slice::from_ref(&ordinary.id),
7198 std::slice::from_ref(&ordinary),
7199 );
7200 assert_eq!(next, Interrupt::Idle);
7201 }
7202
7203 #[test]
7204 fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
7205 let marked = interrupt_task("marked");
7208 let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7209 assert_eq!(next, Interrupt::Idle);
7210 }
7211
7212 #[test]
7213 fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
7214 let marked = interrupt_task("marked");
7215 let next = advance_interrupt(
7216 Interrupt::Idle,
7217 &["running".to_owned()],
7218 std::slice::from_ref(&marked),
7219 );
7220 assert_eq!(
7221 next,
7222 Interrupt::Parking {
7223 parked: vec!["running".to_owned()],
7224 interrupt_task: "marked".to_owned(),
7225 }
7226 );
7227 }
7228
7229 #[test]
7238 fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
7239 let marked = interrupt_task("marked");
7240
7241 let two = advance_interrupt(
7242 Interrupt::Idle,
7243 &["a".to_owned(), "b".to_owned()],
7244 std::slice::from_ref(&marked),
7245 );
7246 assert_eq!(two, Interrupt::Idle);
7247
7248 let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7249 assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
7250 }
7251
7252 #[test]
7253 fn parking_holds_until_every_parked_id_has_actually_left_flight() {
7254 let state = Interrupt::Parking {
7255 parked: vec!["running".to_owned()],
7256 interrupt_task: "marked".to_owned(),
7257 };
7258 let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
7260 assert_eq!(still_going, state);
7261
7262 let stopped_but_not_yet_dispatched =
7266 advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
7267 assert_eq!(stopped_but_not_yet_dispatched, state);
7268
7269 let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
7271 assert_eq!(
7272 dispatched,
7273 Interrupt::Running {
7274 parked: vec!["running".to_owned()],
7275 interrupt_task: "marked".to_owned(),
7276 }
7277 );
7278 }
7279
7280 #[test]
7281 fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
7282 let state = Interrupt::Running {
7283 parked: vec!["running".to_owned()],
7284 interrupt_task: "marked".to_owned(),
7285 };
7286 let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
7287 assert_eq!(still_running, state);
7288
7289 let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
7296 assert_eq!(
7297 ended,
7298 Interrupt::Resuming {
7299 parked: vec!["running".to_owned()]
7300 }
7301 );
7302 }
7303
7304 #[test]
7305 fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
7306 let state = Interrupt::Resuming {
7307 parked: vec!["running".to_owned()],
7308 };
7309 let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
7310 assert_eq!(still_waiting, state);
7311
7312 let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
7313 assert_eq!(dispatched, Interrupt::Idle);
7314 }
7315
7316 #[test]
7322 fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
7323 {
7324 let state = Interrupt::Parking {
7325 parked: vec!["running".to_owned()],
7326 interrupt_task: "marked".to_owned(),
7327 };
7328 let next = advance_interrupt(state, &[], &[]);
7331 assert_eq!(
7332 next,
7333 Interrupt::Resuming {
7334 parked: vec!["running".to_owned()]
7335 },
7336 "abandoning the interrupt must not abandon the resume it owes"
7337 );
7338 }
7339
7340 #[test]
7343 fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
7344 let state = Interrupt::Resuming {
7345 parked: vec!["running".to_owned()],
7346 };
7347 let next = advance_interrupt(state, &[], &[]);
7348 assert_eq!(
7349 next,
7350 Interrupt::Idle,
7351 "nothing is left to wait for; the loop must not stay wedged"
7352 );
7353 }
7354
7355 #[test]
7356 fn disabled_by_config_the_sequence_can_never_leave_idle() {
7357 let marked = interrupt_task("marked");
7358 let next = advance_interrupt_tick(
7359 false,
7360 Interrupt::Idle,
7361 &["running".to_owned()],
7362 std::slice::from_ref(&marked),
7363 );
7364 assert_eq!(
7365 next,
7366 Interrupt::Idle,
7367 "an unmarked, unconfigured daemon must behave exactly as before"
7368 );
7369 }
7370
7371 #[test]
7372 fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
7373 let state = Interrupt::Parking {
7374 parked: vec!["running".to_owned()],
7375 interrupt_task: "marked".to_owned(),
7376 };
7377 let candidates = vec![interrupt_task("marked"), task()];
7378 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
7379 assert!(
7380 allowed.is_empty(),
7381 "nothing may dispatch - not even the interrupt task itself - \
7382 until the parked run has actually stopped"
7383 );
7384 }
7385
7386 #[test]
7400 fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
7401 for state in [
7402 Interrupt::Parking {
7403 parked: vec!["running".to_owned()],
7404 interrupt_task: "marked".to_owned(),
7405 },
7406 Interrupt::Running {
7407 parked: vec!["running".to_owned()],
7408 interrupt_task: "marked".to_owned(),
7409 },
7410 Interrupt::Resuming {
7411 parked: vec!["running".to_owned()],
7412 },
7413 ] {
7414 let candidates = vec![
7415 interrupt_task("marked"),
7416 urgent_task("hot"),
7417 task_with_id("ordinary"),
7418 ];
7419 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
7420 assert!(
7421 !allowed.iter().any(|t| t.id == "hot"),
7422 "an urgent candidate must wait out the same gate as anything \
7423 else while the run it would run alongside has not actually \
7424 left flight, for state {state:?}: {allowed:?}"
7425 );
7426 }
7427 }
7428
7429 #[test]
7435 fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
7436 let state = Interrupt::Resuming {
7437 parked: vec!["hot".to_owned()],
7438 };
7439 let candidates = vec![urgent_task("hot"), task()];
7440 let allowed = interrupt_gate(&state, &[], candidates);
7441 assert_eq!(
7442 allowed.iter().filter(|t| t.id == "hot").count(),
7443 1,
7444 "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
7445 );
7446 }
7447
7448 #[test]
7449 fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
7450 let state = Interrupt::Parking {
7451 parked: vec!["running".to_owned()],
7452 interrupt_task: "marked".to_owned(),
7453 };
7454 let other = task();
7455 let candidates = vec![interrupt_task("marked"), other.clone()];
7456 let allowed = interrupt_gate(&state, &[], candidates);
7457 assert_eq!(allowed.len(), 1);
7458 assert_eq!(allowed[0].id, "marked");
7459 }
7460
7461 #[test]
7462 fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
7463 let state = Interrupt::Running {
7464 parked: vec!["running".to_owned()],
7465 interrupt_task: "marked".to_owned(),
7466 };
7467 let candidates = vec![task(), task()];
7468 let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
7469 assert!(allowed.is_empty());
7470 }
7471
7472 #[test]
7479 fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
7480 let state = Interrupt::Resuming {
7481 parked: vec!["a".to_owned(), "c".to_owned()],
7482 };
7483 let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
7484 let allowed = interrupt_gate(&state, &[], candidates);
7485 assert_eq!(
7486 allowed.len(),
7487 1,
7488 "at most one candidate may be offered while resuming: {allowed:?}"
7489 );
7490 assert_eq!(allowed[0].id, "a");
7491 }
7492
7493 #[test]
7494 fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
7495 let state = Interrupt::Resuming {
7496 parked: vec!["a".to_owned()],
7497 };
7498 let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
7499 assert!(allowed.is_empty());
7500 }
7501
7502 #[test]
7508 fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
7509 let running = task(); let marked = interrupt_task("marked");
7511
7512 let mut state = Interrupt::Idle;
7513 let in_flight = vec![running.id.clone()];
7515 state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
7516 let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
7517 assert!(gated.is_empty(), "still waiting on `running` to park");
7518
7519 state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
7521 let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
7522 assert_eq!(
7523 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7524 vec!["marked"],
7525 "only the interrupt task may be offered to the dispatcher now"
7526 );
7527
7528 state = advance_interrupt_tick(
7530 true,
7531 state,
7532 &["marked".to_owned()],
7533 std::slice::from_ref(&running),
7534 );
7535 let gated = interrupt_gate(
7536 &state,
7537 &["marked".to_owned()],
7538 vec![marked.clone(), running.clone()],
7539 );
7540 assert!(
7541 gated.is_empty(),
7542 "the parked run must not be offered back while the interrupt \
7543 task is still running"
7544 );
7545
7546 let other = task_with_id("other");
7550 state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
7551 assert_eq!(
7552 state,
7553 Interrupt::Resuming {
7554 parked: vec![running.id.clone()]
7555 }
7556 );
7557 let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
7558 assert_eq!(
7559 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7560 vec![running.id.as_str()],
7561 "exactly the parked run resumes - not the unrelated task, even \
7562 though it was offered first"
7563 );
7564
7565 state = advance_interrupt_tick(
7569 true,
7570 state,
7571 std::slice::from_ref(&running.id),
7572 std::slice::from_ref(&other),
7573 );
7574 assert_eq!(state, Interrupt::Idle);
7575 let gated = interrupt_gate(
7576 &state,
7577 std::slice::from_ref(&running.id),
7578 vec![other.clone()],
7579 );
7580 assert_eq!(
7581 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7582 vec![other.id.as_str()],
7583 "ordinary dispatch is unrestricted again"
7584 );
7585 }
7586
7587 #[test]
7588 fn every_run_status_settles_the_task_it_came_from() {
7589 let table = [
7591 (RunStatus::Merged, TaskStatus::Done, 1),
7592 (RunStatus::Ready, TaskStatus::Done, 1),
7593 (RunStatus::Stalled, TaskStatus::Failed, 0),
7594 (RunStatus::Blocked, TaskStatus::Failed, 1),
7595 (RunStatus::Failed, TaskStatus::Failed, 1),
7596 (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
7597 (RunStatus::Prep, TaskStatus::Failed, 1),
7598 (RunStatus::Implementing, TaskStatus::Failed, 1),
7599 (RunStatus::Judging, TaskStatus::Failed, 1),
7600 (RunStatus::Deliberating, TaskStatus::Failed, 1),
7601 (RunStatus::Voting, TaskStatus::Failed, 1),
7602 (RunStatus::Reviewing, TaskStatus::Failed, 1),
7603 (RunStatus::Gating, TaskStatus::Failed, 1),
7604 ];
7605 for (run, want, attempts) in table {
7606 let mut t = task();
7607 t.start("20260902-000000-aaaa".to_owned());
7608 settle(
7609 &mut t,
7610 Verdict {
7611 status: run,
7612 left_pr: false,
7613 parked: false,
7614 quota_hit: matches!(run, RunStatus::Stalled),
7615 no_viable_candidates: false,
7616 },
7617 "why",
7618 2,
7619 );
7620 assert_eq!(t.status, want, "task status after {}", label(run));
7621 assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
7622 }
7623 }
7624
7625 #[test]
7626 fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
7627 let mut stalled = task();
7628 stalled.start("20260902-000000-aaaa".to_owned());
7629 settle(
7630 &mut stalled,
7631 Verdict {
7632 status: RunStatus::Stalled,
7633 left_pr: false,
7634 parked: false,
7635 quota_hit: true,
7636 no_viable_candidates: false,
7637 },
7638 "quota",
7639 1,
7640 );
7641 assert_eq!(stalled.attempts, 0);
7642 assert!(
7643 stalled.status.runnable(),
7644 "a machine problem must leave the task in line"
7645 );
7646
7647 let mut blocked = task();
7648 blocked.start("20260902-000000-aaaa".to_owned());
7649 settle(
7650 &mut blocked,
7651 Verdict {
7652 status: RunStatus::Blocked,
7653 left_pr: false,
7654 parked: false,
7655 quota_hit: false,
7656 no_viable_candidates: false,
7657 },
7658 "findings open",
7659 1,
7660 );
7661 assert_eq!(blocked.attempts, 1);
7662 assert_eq!(
7663 blocked.status,
7664 TaskStatus::Held,
7665 "the last attempt hands the task to a human"
7666 );
7667 }
7668
7669 #[test]
7670 fn a_run_that_opened_a_pull_request_is_never_re_competed() {
7671 let mut delivered = task();
7674 delivered.start("20260903-080619-01c2".to_owned());
7675 settle(
7676 &mut delivered,
7677 Verdict {
7678 status: RunStatus::Blocked,
7679 left_pr: true,
7680 parked: false,
7681 quota_hit: false,
7682 no_viable_candidates: false,
7683 },
7684 "no check status",
7685 4,
7686 );
7687 assert_eq!(
7688 delivered.status,
7689 TaskStatus::Held,
7690 "a pull request waiting on CI or a person is not a retryable failure"
7691 );
7692 assert!(
7693 !delivered.status.runnable(),
7694 "the loop must not pick this task up again"
7695 );
7696 assert_eq!(
7697 delivered.last_error.as_deref(),
7698 Some("no check status"),
7699 "the operator needs to be told what the gate was waiting for"
7700 );
7701
7702 let mut empty_handed = task();
7705 empty_handed.start("20260903-080619-01c2".to_owned());
7706 settle(
7707 &mut empty_handed,
7708 Verdict {
7709 status: RunStatus::Blocked,
7710 left_pr: false,
7711 parked: false,
7712 quota_hit: false,
7713 no_viable_candidates: false,
7714 },
7715 "findings open",
7716 4,
7717 );
7718 assert_eq!(empty_handed.status, TaskStatus::Failed);
7719 assert!(empty_handed.status.runnable());
7720 }
7721
7722 #[test]
7723 fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
7724 let mut noop = task();
7730 noop.start("20260912-131304-391f".to_owned());
7731 settle(
7732 &mut noop,
7733 Verdict {
7734 status: RunStatus::VerifiedNoop,
7735 left_pr: false,
7736 parked: false,
7737 quota_hit: false,
7738 no_viable_candidates: true,
7739 },
7740 "candidate A: already fixed by b32cfc4, on main",
7741 4,
7742 );
7743 assert_eq!(
7744 noop.status,
7745 TaskStatus::Held,
7746 "an unverified claim is a request for a human, not a failure"
7747 );
7748 assert!(
7749 !noop.status.runnable(),
7750 "the loop must not requeue this on the same unverified claim"
7751 );
7752 assert_eq!(noop.attempts, 1);
7757 }
7758
7759 #[test]
7760 fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
7761 let mut parked = task();
7766 parked.start("20260903-183634-2d98".to_owned());
7767 settle(
7768 &mut parked,
7769 Verdict {
7770 status: RunStatus::Implementing,
7771 left_pr: false,
7772 quota_hit: false,
7773 parked: true,
7774 no_viable_candidates: false,
7775 },
7776 "parked after `implementing`",
7777 2,
7778 );
7779 assert_eq!(parked.attempts, 0, "a park is refunded");
7780 assert!(
7781 parked.status.runnable(),
7782 "and the task stays in line so the next loop resumes its run"
7783 );
7784 assert_eq!(parked.status, TaskStatus::Parked);
7785 assert_eq!(
7786 parked.park_reason.as_deref(),
7787 Some("parked after `implementing`"),
7788 "the card says where it stopped"
7789 );
7790 assert_eq!(parked.last_error, None, "nothing failed");
7791
7792 let mut broken = task();
7796 broken.start("20260903-183634-2d98".to_owned());
7797 settle(
7798 &mut broken,
7799 Verdict {
7800 status: RunStatus::Implementing,
7801 left_pr: false,
7802 quota_hit: false,
7803 parked: false,
7804 no_viable_candidates: false,
7805 },
7806 "returned mid-flight",
7807 2,
7808 );
7809 assert_eq!(broken.attempts, 1);
7810 }
7811
7812 #[test]
7813 fn only_a_rate_limit_buys_the_task_its_attempt_back() {
7814 let mut flaky = task();
7819 flaky.start("20260903-123023-e633".to_owned());
7820 settle(
7821 &mut flaky,
7822 Verdict {
7823 status: RunStatus::Stalled,
7824 left_pr: false,
7825 parked: false,
7826 quota_hit: false,
7827 no_viable_candidates: false,
7828 },
7829 "verdict rests on 1 of 3 judges",
7830 2,
7831 );
7832 assert_eq!(
7833 flaky.attempts, 1,
7834 "flakiness spends an attempt, so `max_attempts` still bounds it"
7835 );
7836 assert!(flaky.status.runnable(), "and it is still worth retrying");
7837
7838 let mut limited = task();
7840 limited.start("20260903-123023-e633".to_owned());
7841 settle(
7842 &mut limited,
7843 Verdict {
7844 status: RunStatus::Stalled,
7845 left_pr: false,
7846 parked: false,
7847 quota_hit: true,
7848 no_viable_candidates: false,
7849 },
7850 "judge-2, judge-3 out of quota",
7851 2,
7852 );
7853 assert_eq!(limited.attempts, 0, "a quota window is refunded");
7854 assert!(limited.status.runnable());
7855
7856 let mut worn = task();
7859 for _ in 0..2 {
7860 worn.release();
7861 }
7862 worn.start("20260903-123023-e633".to_owned());
7863 worn.attempts = 2;
7864 settle(
7865 &mut worn,
7866 Verdict {
7867 status: RunStatus::Stalled,
7868 left_pr: false,
7869 parked: false,
7870 quota_hit: false,
7871 no_viable_candidates: false,
7872 },
7873 "no quorum again",
7874 2,
7875 );
7876 assert_eq!(worn.status, TaskStatus::Held);
7877 assert!(!worn.status.runnable());
7878 }
7879
7880 #[test]
7881 fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
7882 let mut wiped_out = task();
7889 wiped_out.start("20260907-025000-a1b2".to_owned());
7890 settle(
7891 &mut wiped_out,
7892 Verdict {
7893 status: RunStatus::Failed,
7894 left_pr: false,
7895 parked: false,
7896 quota_hit: true,
7897 no_viable_candidates: true,
7898 },
7899 "no candidate produced a change; nothing to judge",
7900 2,
7901 );
7902 assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
7903 assert!(
7904 wiped_out.status.runnable(),
7905 "a machine problem must leave the task in line"
7906 );
7907
7908 let mut partial_progress = task();
7914 partial_progress.start("20260907-025500-c3d4".to_owned());
7915 settle(
7916 &mut partial_progress,
7917 Verdict {
7918 status: RunStatus::Failed,
7919 left_pr: false,
7920 parked: false,
7921 quota_hit: true,
7922 no_viable_candidates: false,
7923 },
7924 "gate failed on the winning candidate",
7925 2,
7926 );
7927 assert_eq!(
7928 partial_progress.attempts, 1,
7929 "a candidate that actually produced a change spends the attempt \
7930 even though some other seat hit its quota"
7931 );
7932 assert!(partial_progress.status.runnable());
7933 }
7934
7935 #[test]
7936 fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
7937 let mut t = task();
7943 t.start("20260907-025000-a1b2".to_owned());
7944 let mut state = run_state(RunStatus::Failed);
7945 state.quota.push(QuotaLoss {
7946 seat: "cand-a".to_owned(),
7947 node: "implement".to_owned(),
7948 at: Timestamp::now(),
7949 reset: None,
7950 });
7951 assert!(
7952 state.viable().is_empty(),
7953 "no candidate was added, so nothing is viable"
7954 );
7955 reclaim(&mut t, Some(state), 2, "en");
7956 assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
7957 assert!(t.status.runnable());
7958 }
7959
7960 #[test]
7961 fn a_held_task_is_never_offered_to_the_loop() {
7962 let dir = tempfile::tempdir().unwrap();
7963 let queue = Queue::at(dir.path().to_path_buf());
7964 for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
7965 let mut t = task();
7966 t.id = format!("2026090{n}-000000-000{n}");
7967 t.priority = priority;
7968 queue.put(&mut t).unwrap();
7969 }
7970 let mut held = task();
7971 held.id = "20260909-000000-9999".to_owned();
7972 held.priority = 99;
7973 held.hold_machine(None);
7974 queue.put(&mut held).unwrap();
7975
7976 let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
7977 assert_eq!(order.len(), 3);
7978 assert!(!order.contains(&held.id));
7979 assert_eq!(
7980 order.first().cloned(),
7981 queue.next_runnable().map(|t| t.id),
7982 "the loop's first candidate is exactly what the queue offers"
7983 );
7984 assert_eq!(
7985 order,
7986 vec![
7987 "20260902-000000-0002".to_owned(),
7988 "20260903-000000-0003".to_owned(),
7989 "20260901-000000-0001".to_owned(),
7990 ],
7991 "priority first, then oldest, so nothing starves"
7992 );
7993 }
7994
7995 #[test]
7996 fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
7997 let dir = tempfile::tempdir().unwrap();
7998 let queue = Queue::at(dir.path().to_path_buf());
7999 let mut old = task();
8000 old.id = "20260101-000000-old0".to_owned();
8001 queue.put(&mut old).unwrap();
8002 let mut fresh = task();
8003 fresh.id = "20260101-000000-new0".to_owned();
8004 queue.put(&mut fresh).unwrap();
8005
8006 std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
8010 std::thread::sleep(Duration::from_millis(60));
8011 let live = queue.claim(&fresh.id).unwrap();
8012
8013 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8014 assert_eq!(swept, vec![old.id.clone()]);
8015 assert!(
8016 queue.claim(&old.id).is_ok(),
8017 "an unparseable lock older than the threshold is swept"
8018 );
8019 assert!(
8020 queue.claim(&fresh.id).is_err(),
8021 "a live pid protects its lock regardless of age"
8022 );
8023 drop(live);
8024 }
8025
8026 #[test]
8027 fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
8028 let dir = tempfile::tempdir().unwrap();
8031 let queue = Queue::at(dir.path().to_path_buf());
8032 let mut t = task();
8033 t.id = "20260101-000000-live".to_owned();
8034 queue.put(&mut t).unwrap();
8035
8036 let claim = queue.claim(&t.id).unwrap();
8037 std::thread::sleep(Duration::from_millis(60));
8038
8039 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8040 assert!(
8041 swept.is_empty(),
8042 "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
8043 );
8044 assert!(
8045 queue.claim(&t.id).is_err(),
8046 "the lock still protects its task"
8047 );
8048 drop(claim);
8049 }
8050
8051 fn injected_dead_pid() -> u32 {
8054 std::process::id().checked_add(1).unwrap_or(1)
8055 }
8056
8057 #[test]
8058 fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
8059 let dir = tempfile::tempdir().unwrap();
8060 let queue = Queue::at(dir.path().to_path_buf());
8061 let mut t = task();
8062 t.id = "20260101-000000-dead".to_owned();
8063 queue.put(&mut t).unwrap();
8064 let dead_pid = injected_dead_pid();
8065
8066 std::fs::write(
8071 dir.path().join(format!("{}.lock", t.id)),
8072 dead_pid.to_string(),
8073 )
8074 .unwrap();
8075
8076 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8077 pid != dead_pid
8078 });
8079 assert_eq!(
8080 swept,
8081 vec![t.id.clone()],
8082 "a dead owner is reclaimed immediately, not after STALE_CLAIM"
8083 );
8084 assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
8085 }
8086
8087 #[test]
8088 fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
8089 let dir = tempfile::tempdir().unwrap();
8090 let queue = Queue::at(dir.path().to_path_buf());
8091 let mut t = task();
8092 t.id = "20260101-000000-late".to_owned();
8093 queue.put(&mut t).unwrap();
8094 let dead_pid = injected_dead_pid();
8095
8096 assert!(
8099 sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
8100 "nothing has claimed the task yet"
8101 );
8102
8103 std::fs::write(
8106 dir.path().join(format!("{}.lock", t.id)),
8107 dead_pid.to_string(),
8108 )
8109 .unwrap();
8110
8111 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8115 pid != dead_pid
8116 });
8117 assert_eq!(swept, vec![t.id.clone()]);
8118 }
8119
8120 #[test]
8121 fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
8122 crate::run::pin_test_home();
8127 let dir = tempfile::tempdir().unwrap();
8128 let queue = Queue::at(dir.path().to_path_buf());
8129 let mut t = task();
8130 t.id = "20260101-000000-crsh".to_owned();
8131 t.status = TaskStatus::Running;
8132 t.attempts = 1;
8133 t.runs.push("20260904-000000-4043".to_owned());
8137 queue.put(&mut t).unwrap();
8138 let dead_pid = injected_dead_pid();
8139
8140 std::fs::write(
8143 dir.path().join(format!("{}.lock", t.id)),
8144 dead_pid.to_string(),
8145 )
8146 .unwrap();
8147
8148 assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
8154 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
8155
8156 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8157 pid != dead_pid
8158 });
8159 assert_eq!(swept, vec![t.id.clone()]);
8160
8161 let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
8162 assert_eq!(reclaimed, vec![t.id.clone()]);
8163 let after = queue.get(&t.id).unwrap();
8164 assert_eq!(
8165 after.status,
8166 TaskStatus::Held,
8167 "no run.json to recover from, so a human is asked"
8168 );
8169 assert_eq!(
8170 after.runs,
8171 vec!["20260904-000000-4043".to_owned()],
8172 "the crashed run's id is kept as evidence, not discarded"
8173 );
8174 }
8175
8176 #[test]
8177 fn a_lock_is_kept_when_the_process_query_is_unavailable() {
8178 let dir = tempfile::tempdir().unwrap();
8179 let queue = Queue::at(dir.path().to_path_buf());
8180 let mut t = task();
8181 t.id = "20260101-000000-unknown".to_owned();
8182 queue.put(&mut t).unwrap();
8183 let dead_pid = injected_dead_pid();
8184 std::fs::write(
8185 dir.path().join(format!("{}.lock", t.id)),
8186 dead_pid.to_string(),
8187 )
8188 .unwrap();
8189
8190 let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
8191 assert!(swept.is_empty(), "an unknown pid must keep its lock");
8192 assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
8193 }
8194
8195 fn run_state_in(status: RunStatus, language: &str) -> RunState {
8196 let mut s = run_state(status);
8197 s.config.graph.language = language.to_owned();
8198 s
8199 }
8200
8201 fn unstarted_verdict(status: RunStatus) -> Verdict {
8202 Verdict {
8203 status,
8204 left_pr: false,
8205 quota_hit: false,
8206 parked: false,
8207 no_viable_candidates: false,
8208 }
8209 }
8210
8211 #[test]
8212 fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
8213 let mut t = task();
8214 t.attempts = 1;
8215 settle_in(
8216 &mut t,
8217 unstarted_verdict(RunStatus::AlreadyInBase),
8218 "already in main",
8219 1,
8220 phrases("en"),
8221 );
8222 assert_eq!(t.status, TaskStatus::Done);
8223 assert_eq!(t.attempts, 0);
8224 }
8225
8226 #[test]
8227 fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
8228 let reason = |language: &str| {
8229 let mut t = task();
8230 settle_in(
8231 &mut t,
8232 unstarted_verdict(RunStatus::Judging),
8233 "boom",
8234 1,
8235 phrases(language),
8236 );
8237 t.last_error.or(t.hold_reason).unwrap_or_default()
8238 };
8239 assert!(
8240 reason("en").starts_with("the graph stopped at `"),
8241 "{}",
8242 reason("en")
8243 );
8244 assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
8245 assert!(reason("日本語").contains("boom"));
8246 assert_eq!(reason("fr"), reason("en"));
8247 }
8248
8249 #[test]
8250 fn describe_follows_the_run_language_and_keeps_the_run_id() {
8251 let en = describe(&run_state_in(RunStatus::Stalled, "en"));
8252 assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
8253 let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
8254 assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
8255 assert!(ja.contains("[run "), "{ja}");
8256 let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
8257 assert!(ended.starts_with("run 終了: "), "{ended}");
8258 let mut de = run_state_in(RunStatus::Failed, "de");
8259 let mut en = run_state_in(RunStatus::Failed, "en");
8260 de.id = "same".to_owned();
8261 en.id = "same".to_owned();
8262 assert_eq!(describe(&de), describe(&en));
8263 }
8264
8265 #[test]
8266 fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
8267 use crate::handover::Refused;
8268 let cases = [
8269 Refused::Foreign {
8270 branch: "b".into(),
8271 path: "/w/x".into(),
8272 why: "made by hand".into(),
8273 },
8274 Refused::Unsafe {
8275 branch: "b".into(),
8276 path: "/w/x".into(),
8277 why: "its worktree has uncommitted changes (a.rs)".into(),
8278 },
8279 Refused::ReleaseFailed {
8280 branch: "b".into(),
8281 path: "/w/x".into(),
8282 run: "ab12".into(),
8283 },
8284 ];
8285 for r in &cases {
8286 let en = (phrases("en").handover_refused)(r);
8287 assert_eq!(en, r.to_string());
8288 let ja = (phrases("ja").handover_refused)(r);
8289 assert!(
8290 !ja.contains("is checked out") && !ja.contains("try again"),
8291 "{ja}"
8292 );
8293 assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
8294 if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
8295 assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
8296 }
8297 }
8298 assert!(phrases("en").handover_hint.contains("release the task"));
8299 assert!(phrases("ja").handover_hint.contains("解放"));
8300 }
8301
8302 #[test]
8303 fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
8304 let build = |lang: &str| {
8305 let mut s = run_state_in(RunStatus::Blocked, lang);
8306 s.id = "same".to_owned();
8307 s.config.graph.review_rounds = 3;
8308 let mut r = review_round(3);
8309 r.expected = 3;
8310 r.answered = 1;
8311 s.reviews.push(r);
8312 s.event(
8313 "review",
8314 "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
8315 );
8316 s
8317 };
8318 let en = describe(&build("en"));
8319 assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
8320 let ja = describe(&build("ja"));
8321 assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
8322 assert!(!ja.contains("never answered"), "{ja}");
8323 assert!(ja.contains("[run "), "{ja}");
8324
8325 let mut failed = build("ja");
8328 failed.reviews[0].e2e.push(crate::run::CommandOutcome {
8329 command: "cargo test".to_owned(),
8330 code: Some(1),
8331 output_tail: String::new(),
8332 duration_ms: 0,
8333 resource_blocked: false,
8334 });
8335 failed.event("review", "stopped; e2e failed: cargo test");
8336 let ja = describe(&failed);
8337 assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
8338 assert!(!ja.contains("席のレビュアー"), "{ja}");
8339 }
8340
8341 #[test]
8342 fn refusals_and_recovery_prose_follow_the_language() {
8343 let t = held_task_with("r1");
8344 let q = action_question(
8345 "r1",
8346 ask::ChoiceAction::Resume {
8347 run: "r1".to_owned(),
8348 },
8349 );
8350 let refuse = |p: &Phrases| match decide_action(&t, &q, p, |_: &str| bail!("gone")) {
8351 ActionDecision::Refuse(s) => s,
8352 other => panic!("{other:?}"),
8353 };
8354 assert!(refuse(phrases("en")).contains("could not be read: gone"));
8355 assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
8356 assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
8357
8358 let mut held = task();
8359 reclaim(&mut held, None, 2, "ja");
8360 assert!(held.hold_reason.unwrap().contains("保留にしました"));
8361 let mut held = task();
8362 reclaim(&mut held, None, 2, "xx");
8363 assert!(held.hold_reason.unwrap().contains("held for a human"));
8364 }
8365
8366 fn run_state(status: RunStatus) -> RunState {
8367 let mut state = RunState::new(
8368 PathBuf::from("/repo"),
8369 "main".to_owned(),
8370 "abc1234def".to_owned(),
8371 "add retries".to_owned(),
8372 Config::default(),
8373 );
8374 state.status = status;
8375 state
8376 }
8377
8378 fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
8379 Candidate {
8380 index: 0,
8381 label,
8382 agent: "claude".to_owned(),
8383 branch: format!("magi/x/{label}"),
8384 worktree: PathBuf::from("/repo"),
8385 summary: summary.to_owned(),
8386 stat: String::new(),
8387 files: 0,
8388 commits: usize::from(!empty),
8389 empty,
8390 failed: failed.map(str::to_owned),
8391 verified_noop: None,
8392 duration_ms: 0,
8393 folded: false,
8394 }
8395 }
8396
8397 #[test]
8398 fn diagnostic_names_the_failing_gate_checks_and_their_output() {
8399 let mut state = run_state(RunStatus::Blocked);
8400 state.gate = vec![
8401 CommandOutcome {
8402 command: "cargo make check".to_owned(),
8403 code: Some(0),
8404 output_tail: "ok".to_owned(),
8405 duration_ms: 0,
8406 resource_blocked: false,
8407 },
8408 CommandOutcome {
8409 command: "cargo test".to_owned(),
8410 code: Some(101),
8411 output_tail: "thread 'x' panicked: assertion failed".to_owned(),
8412 duration_ms: 0,
8413 resource_blocked: false,
8414 },
8415 ];
8416 let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
8417 assert!(d.contains("cargo test"), "{d}");
8418 assert!(
8419 !d.contains("cargo make check"),
8420 "a passing check is not a diagnostic: {d}"
8421 );
8422 assert!(d.contains("assertion failed"), "{d}");
8423 }
8424
8425 #[test]
8426 fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
8427 let mut state = run_state(RunStatus::Blocked);
8428 state.event(
8429 "land",
8430 "stopped: the fixer produced no commit while 2 check(s) were failing \
8431 (build, lint); stopping instead of looping on an unchanged tree",
8432 );
8433 let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
8434 assert!(d.contains("build"), "{d}");
8435 assert!(d.contains("lint"), "{d}");
8436 assert!(d.contains("fixer produced no commit"), "{d}");
8437 }
8438
8439 #[test]
8440 fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
8441 let state = run_state(RunStatus::VerifiedNoop);
8446 let d = describe(&state);
8447 assert!(
8448 d.contains("agent-verified no-op"),
8449 "expected the display label, not the wire spelling: {d}"
8450 );
8451 assert!(!d.contains("verified_noop"), "{d}");
8452 }
8453
8454 #[test]
8455 fn diagnostic_keeps_gate_panic_before_large_backtrace() {
8456 let mut state = run_state(RunStatus::Failed);
8457 state.gate.push(crate::run::CommandOutcome {
8458 command: "cargo test".into(),
8459 code: Some(101),
8460 output_tail: format!(
8461 "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
8462 " 41: 0x1234 - backtrace frame\n".repeat(10000)
8463 ),
8464 duration_ms: 1,
8465 resource_blocked: false,
8466 });
8467 let d = diagnostic(&state).unwrap();
8468 assert!(d.contains("panicked at widget.rs:12"), "{d}");
8469 assert!(d.contains("assertion failed: widget missing"));
8470 assert!(d.contains("widget log"));
8471 }
8472
8473 #[test]
8474 fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
8475 let mut state = run_state(RunStatus::Failed);
8481 state.candidates = vec![candidate(
8482 'A',
8483 "opened pull request #42, merged it, tagged v1.2.3 and published the release",
8484 true,
8485 None,
8486 )];
8487 let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
8488 assert!(d.contains("candidate A"), "{d}");
8489 assert!(d.contains("tagged v1.2.3"), "{d}");
8490 }
8491
8492 #[test]
8493 fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
8494 let mut state = run_state(RunStatus::Failed);
8495 state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
8496 let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
8497 assert!(d.contains("candidate A"), "{d}");
8498 assert!(d.contains("agent timed out"), "{d}");
8499 }
8500
8501 #[test]
8502 fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
8503 let mut state = run_state(RunStatus::Failed);
8506 state.candidates = vec![candidate('A', "did the work", false, None)];
8507 assert!(diagnostic(&state).is_none());
8508 }
8509
8510 #[test]
8511 fn diagnostic_is_bounded_however_much_a_run_printed() {
8512 let mut state = run_state(RunStatus::Blocked);
8513 state.gate = vec![
8514 CommandOutcome {
8515 command: "cargo test".to_owned(),
8516 code: Some(101),
8517 output_tail: "x".repeat(50_000),
8518 duration_ms: 0,
8519 resource_blocked: false,
8520 },
8521 CommandOutcome {
8522 command: "cargo clippy".to_owned(),
8523 code: Some(1),
8524 output_tail: "y".repeat(50_000),
8525 duration_ms: 0,
8526 resource_blocked: false,
8527 },
8528 ];
8529 state.candidates = vec![
8530 candidate('A', &"z".repeat(50_000), true, None),
8531 candidate('B', &"w".repeat(50_000), true, None),
8532 ];
8533 let d = diagnostic(&state).expect("plenty here to diagnose");
8534 assert!(
8535 d.len() <= DIAGNOSTIC_MAX,
8536 "diagnostic grew to {} bytes, unbounded",
8537 d.len()
8538 );
8539 }
8540
8541 #[test]
8542 fn selected_delivery_guards_survive_recovery_failure_accounting() {
8543 for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
8544 let mut t = task();
8545 let mut state = run_state(status);
8546 t.pr_recovery = Some(crate::pr_recovery::Selection {
8547 url: "url".into(),
8548 branch: format!("magi/task-{}", t.id),
8549 head: "a".repeat(40),
8550 source_head: None,
8551 source_run: None,
8552 source_proof: None,
8553 disposition: Some(crate::pr_recovery::Disposition::Land),
8554 instruction: t.instruction.clone(),
8555 approved_at: Timestamp::now(),
8556 });
8557 state.pr_recovery = t.pr_recovery.clone();
8558 t.start(state.id.clone());
8559 settle_and_diagnose(
8560 &mut t,
8561 Verdict {
8562 status,
8563 left_pr: false,
8564 quota_hit: false,
8565 parked: false,
8566 no_viable_candidates: false,
8567 },
8568 "delivery stopped",
8569 5,
8570 &state,
8571 );
8572 assert_eq!(t.status, TaskStatus::Held);
8573 let reason = t.hold_reason.as_deref().unwrap();
8574 if status == RunStatus::Ready {
8575 assert!(reason.contains("Selected PR delivery is incomplete"));
8576 assert!(t.recovery_budget.is_none());
8577 } else {
8578 assert!(reason.contains("Selected recovery stopped"));
8579 assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
8580 }
8581 assert!(t.pr_recovery.is_some());
8582 }
8583 }
8584
8585 #[test]
8586 fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
8587 let mut state = run_state(RunStatus::Voting);
8588 state.base_sync = Some(crate::run::BaseSync {
8589 tip: "base-tip".into(),
8590 behind: 3,
8591 attempts: 4,
8592 conflict: Some("base stopped".into()),
8593 already_in: None,
8594 });
8595 state.record_base_sync_stop("candidate-head");
8596 let mut t = task();
8597 t.start(state.id.clone());
8598 let verdict = Verdict {
8599 status: RunStatus::Blocked,
8600 left_pr: false,
8601 quota_hit: false,
8602 parked: false,
8603 no_viable_candidates: false,
8604 };
8605 settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
8606 assert_eq!(
8607 t.status,
8608 TaskStatus::Held,
8609 "unspent task attempts cannot start another competition"
8610 );
8611 let at = t.held_at;
8612 let cause = t.hold_notice_cause.clone();
8613 state.begin_pass();
8614 t.release_operator("test-resume", None);
8615 t.start(state.id.clone());
8616 settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
8617 assert_eq!(t.status, TaskStatus::Held);
8618 assert_eq!(t.held_at, at);
8619 assert_eq!(t.hold_notice_cause, cause);
8620 }
8621
8622 #[test]
8623 fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
8624 let mut state = run_state(RunStatus::Blocked);
8625 state.gate = vec![CommandOutcome {
8626 command: "cargo test".to_owned(),
8627 code: Some(101),
8628 output_tail: "assertion failed".to_owned(),
8629 duration_ms: 0,
8630 resource_blocked: false,
8631 }];
8632 let verdict = Verdict {
8633 status: RunStatus::Blocked,
8634 left_pr: false,
8635 quota_hit: false,
8636 parked: false,
8637 no_viable_candidates: false,
8638 };
8639
8640 let mut t = task();
8643 t.start("run-1".to_owned());
8644 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
8645 assert_eq!(t.status, TaskStatus::Failed);
8646 assert!(t.diagnostic.is_none());
8647
8648 t.start("run-2".to_owned());
8651 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
8652 assert_eq!(t.status, TaskStatus::Held);
8653 let d = t.diagnostic.expect("a held task must carry its diagnostic");
8654 assert!(d.contains("cargo test"), "{d}");
8655 }
8656
8657 #[test]
8658 fn a_held_task_names_the_open_question_it_is_waiting_on() {
8659 crate::run::pin_test_home();
8664 let home = crate::run::home();
8665 let state = run_state(RunStatus::VerifiedNoop);
8666 let mut q = ask::Question::new(
8667 state.id.clone(),
8668 "implement".to_owned(),
8669 "impl-A".to_owned(),
8670 "is this really a no-op?".to_owned(),
8671 String::new(),
8672 Vec::new(),
8673 );
8674 Questions::at(home.join("questions")).put(&mut q).unwrap();
8675
8676 let verdict = Verdict {
8677 status: RunStatus::VerifiedNoop,
8678 left_pr: false,
8679 quota_hit: false,
8680 parked: false,
8681 no_viable_candidates: false,
8682 };
8683 let mut t = task();
8684 t.start(state.id.clone());
8685 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
8686
8687 assert_eq!(t.status, TaskStatus::Held);
8688 let reason = t.hold_reason.expect("a held task must record why");
8689 assert!(
8690 reason.starts_with("run ended agent-verified no-op"),
8691 "the original settle reason must survive unchanged: {reason}"
8692 );
8693 assert!(
8694 reason.contains(q.short()),
8695 "the open question's id must be named so the notice is actionable: {reason}"
8696 );
8697 }
8698
8699 #[test]
8700 fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
8701 crate::run::pin_test_home();
8702 let state = run_state(RunStatus::VerifiedNoop);
8703
8704 let verdict = Verdict {
8705 status: RunStatus::VerifiedNoop,
8706 left_pr: false,
8707 quota_hit: false,
8708 parked: false,
8709 no_viable_candidates: false,
8710 };
8711 let mut t = task();
8712 t.start(state.id.clone());
8713 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
8714
8715 assert_eq!(t.status, TaskStatus::Held);
8716 assert_eq!(
8717 t.hold_reason.as_deref(),
8718 Some("run ended agent-verified no-op"),
8719 "nothing to append when the question was already answered or never asked"
8720 );
8721 }
8722
8723 #[test]
8724 fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
8725 crate::run::pin_test_home();
8726 let mut first = run_state(RunStatus::Blocked);
8727 first.id = "20260101-000000-sup1".to_owned();
8728 first.save().unwrap();
8729 let mut second = run_state(RunStatus::Merged);
8730 second.id = "20260101-000000-sup2".to_owned();
8731 second.save().unwrap();
8732
8733 let mut t = task();
8734 t.runs = vec![first.id.clone(), second.id.clone()];
8735 t.status = TaskStatus::Done;
8736
8737 supersede_prior_runs(&t, &crate::run::home());
8738
8739 assert_eq!(
8740 RunState::load(&first.id).unwrap().status,
8741 RunStatus::Superseded,
8742 "the first attempt's Blocked no longer needs anyone's attention"
8743 );
8744 assert_eq!(
8745 RunState::load(&second.id).unwrap().status,
8746 RunStatus::Merged,
8747 "the run that actually succeeded is left exactly as it was"
8748 );
8749 }
8750
8751 #[test]
8752 fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
8753 crate::run::pin_test_home();
8759 let mut first = run_state(RunStatus::Blocked);
8760 first.id = "20260101-000000-sup9".to_owned();
8761 first.driver_pid = Some(std::process::id());
8764 first.driver_started_at = Some(
8765 crate::proc::process_started_at(std::process::id())
8766 .expect("this test process's own start time must be queryable"),
8767 );
8768 first.save().unwrap();
8769 let mut second = run_state(RunStatus::Merged);
8770 second.id = "20260101-000000-supa".to_owned();
8771 second.save().unwrap();
8772
8773 let mut t = task();
8774 t.runs = vec![first.id.clone(), second.id.clone()];
8775 t.status = TaskStatus::Done;
8776
8777 supersede_prior_runs(&t, &crate::run::home());
8778
8779 assert_eq!(
8780 RunState::load(&first.id).unwrap().status,
8781 RunStatus::Blocked,
8782 "a live driver_pid means something is still actually working this run, \
8783 even though no daemon claims it - rewriting under it would just be \
8784 undone the next time that process saves"
8785 );
8786 }
8787
8788 #[test]
8789 fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
8790 let dir = tempfile::tempdir().unwrap();
8796 let home = dir.path().to_path_buf();
8797 let queue = Queue::at(dir.path().join("queue"));
8798
8799 let mut first = run_state(RunStatus::Blocked);
8800 first.id = "20260101-000000-supd".to_owned();
8801 first.driver_pid = Some(std::process::id());
8802 first.driver_started_at = Some(
8803 crate::proc::process_started_at(std::process::id())
8804 .expect("this test process's own start time must be queryable"),
8805 );
8806 first.save_under(&home).unwrap();
8807 let mut second = run_state(RunStatus::Merged);
8808 second.id = "20260101-000000-supe".to_owned();
8809 second.save_under(&home).unwrap();
8810
8811 let mut t = task();
8812 t.runs = vec![first.id.clone(), second.id.clone()];
8813 t.status = TaskStatus::Done;
8814 queue.put(&mut t).unwrap();
8815
8816 resweep_superseded_attempts(&queue, &home);
8817 assert_eq!(
8818 RunState::load_under(&first.id, &home).unwrap().status,
8819 RunStatus::Blocked,
8820 "still live on the first pass, so still untouched"
8821 );
8822
8823 let mut stale = RunState::load_under(&first.id, &home).unwrap();
8829 stale.driver_started_at = Some("1".to_owned());
8830 stale.save_under(&home).unwrap();
8831
8832 resweep_superseded_attempts(&queue, &home);
8833 assert_eq!(
8834 RunState::load_under(&first.id, &home).unwrap().status,
8835 RunStatus::Superseded,
8836 "the second pass catches up what the first one correctly skipped"
8837 );
8838 }
8839
8840 #[test]
8841 fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
8842 crate::run::pin_test_home();
8843 let mut first = run_state(RunStatus::Blocked);
8844 first.id = "20260101-000000-sup3".to_owned();
8845 first.save().unwrap();
8846 let mut second = run_state(RunStatus::Blocked);
8847 second.id = "20260101-000000-sup4".to_owned();
8848 second.save().unwrap();
8849
8850 let mut t = task();
8851 t.runs = vec![first.id.clone(), second.id.clone()];
8852 t.status = TaskStatus::Failed;
8856
8857 supersede_prior_runs(&t, &crate::run::home());
8858
8859 assert_eq!(
8860 RunState::load(&first.id).unwrap().status,
8861 RunStatus::Blocked
8862 );
8863 assert_eq!(
8864 RunState::load(&second.id).unwrap().status,
8865 RunStatus::Blocked
8866 );
8867 }
8868
8869 #[test]
8870 fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
8871 crate::run::pin_test_home();
8875 let mut first = run_state(RunStatus::Blocked);
8876 first.id = "20260101-000000-sup5".to_owned();
8877 first.save().unwrap();
8878
8879 let mut t = task();
8880 t.runs = vec![first.id.clone()];
8881 t.status = TaskStatus::Done;
8882
8883 supersede_prior_runs(&t, &crate::run::home());
8884
8885 assert_eq!(
8886 RunState::load(&first.id).unwrap().status,
8887 RunStatus::Blocked,
8888 "a single-attempt task has no earlier run to supersede"
8889 );
8890 }
8891
8892 #[test]
8893 fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
8894 crate::run::pin_test_home();
8901 let mut first = run_state(RunStatus::Blocked);
8902 first.id = "20260101-000000-supb".to_owned();
8903 first.save().unwrap();
8904 let mut second = run_state(RunStatus::Failed);
8905 second.id = "20260101-000000-supc".to_owned();
8906 second.save().unwrap();
8907
8908 let mut t = task();
8909 t.runs = vec![first.id.clone(), second.id.clone()];
8910 t.status = TaskStatus::Done;
8911
8912 supersede_prior_runs(&t, &crate::run::home());
8913
8914 assert_eq!(
8915 RunState::load(&first.id).unwrap().status,
8916 RunStatus::Blocked,
8917 "the task's last attempt never landed, so there is nothing here \
8918 actually superseding it"
8919 );
8920 }
8921
8922 #[test]
8923 fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
8924 crate::run::pin_test_home();
8928 let mut failed = run_state(RunStatus::Failed);
8929 failed.id = "20260101-000000-sup6".to_owned();
8930 failed.save().unwrap();
8931 let mut noop = run_state(RunStatus::VerifiedNoop);
8932 noop.id = "20260101-000000-sup7".to_owned();
8933 noop.save().unwrap();
8934 let mut winner = run_state(RunStatus::Ready);
8935 winner.id = "20260101-000000-sup8".to_owned();
8936 winner.save().unwrap();
8937
8938 let mut t = task();
8939 t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
8940 t.status = TaskStatus::Done;
8941
8942 supersede_prior_runs(&t, &crate::run::home());
8943
8944 assert_eq!(
8945 RunState::load(&failed.id).unwrap().status,
8946 RunStatus::Failed
8947 );
8948 assert_eq!(
8949 RunState::load(&noop.id).unwrap().status,
8950 RunStatus::VerifiedNoop
8951 );
8952 }
8953
8954 fn approval_question(run: &str) -> ask::Question {
8955 ask::Question::new(
8956 run.to_owned(),
8957 land::APPROVAL_NODE.to_owned(),
8958 "land".to_owned(),
8959 "merge?".to_owned(),
8960 String::new(),
8961 vec!["merge".to_owned(), "hold".to_owned()],
8962 )
8963 }
8964
8965 #[test]
8966 fn land_resume_state_leaves_a_fresh_open_question_waiting() {
8967 crate::run::pin_test_home();
8968 let mut state = run_state(RunStatus::Landing);
8969 state.id = "20260101-000000-fre1".to_owned();
8970 state.parked = true;
8971 state.save().unwrap();
8972 ask::Questions::open()
8973 .put(&mut approval_question(&state.id))
8974 .unwrap();
8975
8976 let mut t = task();
8977 t.runs.push(state.id.clone());
8978 assert_eq!(
8979 land_resume_state(&t),
8980 LandResume::StillWaiting,
8981 "nobody has answered and the timeout has not passed"
8982 );
8983 }
8984
8985 #[test]
8986 fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
8987 crate::run::pin_test_home();
8988 let mut state = run_state(RunStatus::Gating);
8989 state.id = "20260101-000000-gt01".to_owned();
8990 state.parked = true;
8991 state.config.graph.answer_timeout = 60;
8992 state.github_text = Some(crate::run::GithubTextAsk {
8993 rewrite: None,
8994 fingerprint: "f".into(),
8995 title: true,
8996 body: false,
8997 categories: vec!["title-language".into()],
8998 question: None,
8999 asks: 1,
9000 resolved: false,
9001 chosen_title: None,
9002 choice: None,
9003 });
9004 state.save().unwrap();
9005 let store = ask::Questions::open();
9006 let mut q = ask::Question::new(
9007 state.id.clone(),
9008 crate::github_text::ASK_NODE.to_owned(),
9009 crate::github_text::ASK_SEAT.to_owned(),
9010 "s".into(),
9011 String::new(),
9012 vec!["use fallback".into()],
9013 );
9014 store.put(&mut q).unwrap();
9015 let mut t = task();
9016 t.runs.push(state.id.clone());
9017 assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
9018 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9019 store.put(&mut q).unwrap();
9020 assert_eq!(land_resume_state(&t), LandResume::Ready);
9021 assert!(!store.get(&q.id).unwrap().status.open());
9022 state.github_text.as_mut().unwrap().resolved = true;
9024 state.save().unwrap();
9025 assert_eq!(land_resume_state(&t), LandResume::NotLanding);
9026 }
9027
9028 #[test]
9029 fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
9030 crate::run::pin_test_home();
9035 let mut state = run_state(RunStatus::Landing);
9036 state.id = "20260101-000000-exp1".to_owned();
9037 state.parked = true;
9038 state.config.graph.answer_timeout = 60;
9039 state.save().unwrap();
9040
9041 let store = ask::Questions::open();
9042 let mut q = approval_question(&state.id);
9043 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9044 store.put(&mut q).unwrap();
9045
9046 let mut t = task();
9047 t.runs.push(state.id.clone());
9048 assert_eq!(
9049 land_resume_state(&t),
9050 LandResume::Ready,
9051 "an expired question must not be waited on forever"
9052 );
9053
9054 let after = store.get(&q.id).unwrap();
9055 assert!(
9056 !after.status.open(),
9057 "the question is abandoned, not silently ignored"
9058 );
9059 assert!(
9060 after.resolution().is_none(),
9061 "an abandoned question is not read as a decision"
9062 );
9063 }
9064
9065 #[test]
9066 fn reclaim_settles_a_running_task_against_its_last_run() {
9067 let mut t = task();
9068 t.start("20260904-000000-4043".to_owned());
9069 reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
9070 assert_eq!(
9071 t.status,
9072 TaskStatus::Done,
9073 "a run that actually finished must not stay `running` forever"
9074 );
9075 }
9076
9077 #[test]
9078 fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
9079 let mut t = task();
9080 t.start("20260904-000000-4043".to_owned());
9081 t.last_error = Some("earlier trouble".to_owned());
9082 let mut state = run_state(RunStatus::Judging);
9083 state.parked = true;
9084 reclaim(&mut t, Some(state), 1, "en");
9085 assert_eq!(t.status, TaskStatus::Parked);
9086 assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
9087 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9088 assert!(t.park_reason.is_some());
9089 assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
9090 assert!(!t.fresh_start);
9091 assert!(t.status.runnable());
9092 }
9093
9094 #[test]
9095 fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
9096 let mut t = task();
9097 t.start("20260904-000000-4043".to_owned());
9098 t.last_error = Some("earlier trouble".to_owned());
9099 settle(
9100 &mut t,
9101 Verdict {
9102 status: RunStatus::Judging,
9103 left_pr: false,
9104 quota_hit: false,
9105 parked: true,
9106 no_viable_candidates: false,
9107 },
9108 "parked after `judging`",
9109 1,
9110 );
9111 assert_eq!(t.status, TaskStatus::Parked);
9112 assert_eq!(t.attempts, 0);
9113 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9114 assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
9115 assert_eq!(t.schema, crate::queue::SCHEMA);
9116 assert!(
9117 crate::notices::task_held(&t).is_none(),
9118 "a park is not news"
9119 );
9120 t.start("20260904-000000-4043".to_owned());
9121 assert_eq!(t.park_reason, None);
9122 }
9123
9124 #[test]
9125 fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
9126 let mut t = task();
9130 t.start("20260904-000000-4043".to_owned());
9131 reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
9132 assert_eq!(t.status, TaskStatus::Failed);
9133 assert!(t.status.runnable());
9134 }
9135
9136 #[test]
9137 fn a_settled_parked_pass_records_its_cause_and_the_refund() {
9138 let mut t = task();
9139 t.start("20260904-000000-4043".to_owned());
9140 assert_eq!(t.attempts, 1);
9141 let mut run = run_state(RunStatus::Implementing);
9142 run.id = "20260904-000000-4043".to_owned();
9143 run.begin_pass();
9144 let cause = crate::run::ParkCause::Upgrade {
9145 from: "0.121.0".to_owned(),
9146 to: Some("0.121.1".to_owned()),
9147 };
9148 run.end_pass_parked(cause.clone());
9149 run.parked = true;
9150 let verdict = Verdict {
9151 status: run.status,
9152 left_pr: false,
9153 quota_hit: false,
9154 parked: true,
9155 no_viable_candidates: false,
9156 };
9157 let mut orphan = t.clone();
9160 reclaim(&mut orphan, Some(run.clone()), 2, "en");
9161 assert_eq!(orphan.status, TaskStatus::Parked);
9162 assert_eq!(orphan.attempts, 0);
9163 assert_eq!(
9164 orphan.upgrade_resume_key(),
9165 Some((run.passes[0].started_at, orphan.id.as_str()))
9166 );
9167 settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
9168 assert_eq!(t.attempts, 0);
9169 assert_eq!(t.passes.len(), 1);
9170 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9171 assert_eq!(t.passes[0].parked, Some(cause));
9172 assert_eq!(t.passes[0].pass_index, 0);
9173 assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
9174 assert!(t.upgrade_resume_key().is_some());
9175
9176 t.start("20260904-000000-4043".to_owned());
9179 run.begin_pass();
9180 run.status = RunStatus::Failed;
9181 let verdict = Verdict {
9182 status: RunStatus::Failed,
9183 left_pr: false,
9184 quota_hit: false,
9185 parked: false,
9186 no_viable_candidates: false,
9187 };
9188 settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
9189 assert_eq!(t.passes.len(), 2);
9190 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9191 assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
9192 assert_eq!(t.passes[1].pass_index, 1);
9193 assert_eq!(t.attempts, 1);
9194 }
9195
9196 #[test]
9197 fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
9198 let mut t = task();
9199 t.start("20260904-000000-4043".to_owned());
9200 reclaim(&mut t, None, 2, "en");
9201 assert_eq!(t.status, TaskStatus::Held);
9202 assert!(
9203 t.last_error
9204 .as_deref()
9205 .is_some_and(|e| e.contains("running")),
9206 "the operator needs to know why this task was held"
9207 );
9208 }
9209
9210 #[test]
9211 fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
9212 let dir = tempfile::tempdir().unwrap();
9213 let queue = Queue::at(dir.path().to_path_buf());
9214
9215 let mut orphaned = task();
9217 orphaned.id = "20260904-000000-orph".to_owned();
9218 orphaned.status = TaskStatus::Running;
9219 orphaned.attempts = 1;
9220 queue.put(&mut orphaned).unwrap();
9221
9222 let mut alive = task();
9223 alive.id = "20260904-000000-live".to_owned();
9224 alive.status = TaskStatus::Running;
9225 alive.attempts = 1;
9226 queue.put(&mut alive).unwrap();
9227 let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
9228
9229 let mut queued = task();
9230 queued.id = "20260904-000000-wait".to_owned();
9231 queue.put(&mut queued).unwrap();
9232
9233 let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
9234 assert_eq!(reclaimed, vec![orphaned.id.clone()]);
9235
9236 assert_eq!(
9237 queue.get(&orphaned.id).unwrap().status,
9238 TaskStatus::Held,
9239 "nothing was driving it and there was no run to recover"
9240 );
9241 assert_eq!(
9242 queue.get(&alive.id).unwrap().status,
9243 TaskStatus::Running,
9244 "a live claim must protect the task it belongs to"
9245 );
9246 assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
9247 }
9248
9249 fn read_run_under(home: &Path, id: &str) -> RunState {
9255 let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
9256 serde_json::from_str(&body).unwrap()
9257 }
9258
9259 #[test]
9260 fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
9261 let dir = tempfile::tempdir().unwrap();
9262 let home = dir.path().to_path_buf();
9263 let now = Timestamp::now();
9264 let overrun_seat = || crate::run::ActiveSeat {
9265 node: "implement".to_owned(),
9266 started_at: now - jiff::SignedDuration::new(21_000, 0),
9267 timeout_secs: 3_600,
9268 attempt: 0,
9269 task: None,
9270 command: None,
9271 index: None,
9272 total: None,
9273 };
9274
9275 let mut dead = run_state(RunStatus::Implementing);
9276 dead.id = "20260101-000000-dead".to_owned();
9277 dead.active.insert("impl-A".to_owned(), overrun_seat());
9278 dead.driver_pid = Some(4242);
9281 dead.save_under(&home).unwrap();
9282
9283 let mut alive = run_state(RunStatus::Implementing);
9286 alive.id = "20260101-000000-aliv".to_owned();
9287 alive.active.insert("impl-A".to_owned(), overrun_seat());
9288 alive.save_under(&home).unwrap();
9289 let mut status = Status::new();
9290 status.current = vec![Current {
9291 worker: None,
9292 task: "20260101-000000-task".to_owned(),
9293 run: alive.id.clone(),
9294 }];
9295 write_status_to(&home.join("daemon.json"), &status).unwrap();
9296
9297 let questions = Questions::at(home.join("questions"));
9301 let mut q = ask::Question::new(
9302 dead.id.clone(),
9303 "implement".to_owned(),
9304 "impl-A".to_owned(),
9305 "Which storage backend?".to_owned(),
9306 String::new(),
9307 vec!["SQLite".to_owned(), "Redis".to_owned()],
9308 );
9309 questions.put(&mut q).unwrap();
9310
9311 let abandoned = reclaim_abandoned_runs_with(
9312 &home,
9313 now,
9314 |pid| if pid == 4242 { Some(false) } else { None },
9315 |_| panic!("a query answering Dead outright needs no identity corroboration"),
9316 );
9317 assert_eq!(abandoned, vec![dead.id.clone()]);
9318
9319 let reloaded = read_run_under(&home, &dead.id);
9320 assert_eq!(reloaded.status, RunStatus::Failed);
9321 assert!(reloaded.active.is_empty());
9322 assert!(
9323 !questions.get(&q.id).unwrap().status.open(),
9324 "the failed run's own open question must be settled in the same pass"
9325 );
9326
9327 let still_alive = read_run_under(&home, &alive.id);
9328 assert_eq!(
9329 still_alive.status,
9330 RunStatus::Implementing,
9331 "a live daemon's claim protects it"
9332 );
9333 assert!(!still_alive.active.is_empty());
9334 }
9335
9336 #[test]
9346 fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
9347 let dir = tempfile::tempdir().unwrap();
9348 let home = dir.path().to_path_buf();
9349 let now = Timestamp::now();
9350
9351 let mut manual = run_state(RunStatus::Reviewing);
9352 manual.id = "20260101-000000-manl".to_owned();
9353 manual.active.insert(
9354 "review-1".to_owned(),
9355 crate::run::ActiveSeat {
9356 node: "review".to_owned(),
9357 started_at: now - jiff::SignedDuration::new(21_000, 0),
9358 timeout_secs: 3_600,
9359 attempt: 0,
9360 task: None,
9361 command: None,
9362 index: None,
9363 total: None,
9364 },
9365 );
9366 manual.driver_pid = Some(4242);
9370 manual.driver_started_at = Some("1790000000".to_owned());
9371 manual.save_under(&home).unwrap();
9372
9373 let abandoned = reclaim_abandoned_runs_with(
9374 &home,
9375 now,
9376 |pid| if pid == 4242 { Some(true) } else { None },
9377 |pid| {
9378 if pid == 4242 {
9379 Some("1790000000".to_owned())
9380 } else {
9381 None
9382 }
9383 },
9384 );
9385 assert!(
9386 abandoned.is_empty(),
9387 "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
9388 );
9389
9390 let reloaded = read_run_under(&home, &manual.id);
9391 assert_eq!(reloaded.status, RunStatus::Reviewing);
9392 assert!(!reloaded.active.is_empty());
9393 }
9394
9395 #[test]
9396 fn an_already_claimed_task_is_skipped_rather_than_failed() {
9397 let dir = tempfile::tempdir().unwrap();
9398 let queue = Queue::at(dir.path().to_path_buf());
9399 let mut only = task();
9400 queue.put(&mut only).unwrap();
9401
9402 let _elsewhere = queue.claim(&only.id).unwrap();
9403 let candidates = runnable(&queue);
9404 assert_eq!(candidates.len(), 1, "the task is still runnable");
9405 assert!(
9406 queue.claim(&candidates[0].id).is_err(),
9407 "the loop cannot take a claim somebody else holds"
9408 );
9409
9410 let after = queue.get(&only.id).unwrap();
9411 assert_eq!(after.status, TaskStatus::Queued);
9412 assert_eq!(
9413 after.attempts, 0,
9414 "losing the race is not an attempt at the task"
9415 );
9416 assert_eq!(after.last_error, None);
9417 }
9418
9419 #[test]
9420 fn the_status_file_round_trips_and_its_heartbeat_advances() {
9421 let dir = tempfile::tempdir().unwrap();
9422 let path = dir.path().join("daemon.json");
9423
9424 let mut status = Status::new();
9425 status.idle = false;
9426 status.completed = 7;
9427 status.current = vec![Current {
9428 worker: None,
9429 task: "20260902-000000-t111".to_owned(),
9430 run: "20260902-000001-r111".to_owned(),
9431 }];
9432 write_status_to(&path, &status).unwrap();
9433 let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9434 assert_eq!(first.schema, SCHEMA);
9435 assert_eq!(first.pid, std::process::id());
9436 assert!(!first.idle);
9437 assert_eq!(first.completed, 7);
9438 assert_eq!(first.current, status.current);
9439 assert!(
9440 !path.with_extension("json.tmp").exists(),
9441 "the temp file is renamed, not left behind"
9442 );
9443
9444 std::thread::sleep(Duration::from_millis(5));
9445 status.updated_at = Timestamp::now();
9446 status.polls = 3;
9447 write_status_to(&path, &status).unwrap();
9448 let second: Status =
9449 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9450 assert!(
9451 second.updated_at > first.updated_at,
9452 "a reader can only detect staleness if the heartbeat moves"
9453 );
9454 assert_eq!(
9455 second.started_at, first.started_at,
9456 "the start time is not a heartbeat"
9457 );
9458 assert_eq!(second.polls, 3);
9459 }
9460
9461 #[test]
9462 fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
9463 let dir = tempfile::tempdir().unwrap();
9464
9465 assert!(read_status(dir.path()).is_none(), "no file, no daemon");
9466
9467 let mut status = Status::new();
9468 status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
9469 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9470 let stale = read_status(dir.path()).unwrap();
9471 assert!(
9472 !stale.running(Timestamp::now()),
9473 "a minute without a heartbeat is a dead daemon, not a busy one"
9474 );
9475 assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
9476
9477 status.updated_at = Timestamp::now();
9478 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9479 let fresh = read_status(dir.path()).unwrap();
9480 assert!(fresh.running(Timestamp::now()));
9481 }
9482
9483 #[test]
9484 fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
9485 let dir = tempfile::tempdir().unwrap();
9486 let now = Timestamp::now();
9487 let mine = "20260903-080619-01c2";
9488
9489 assert!(
9490 !is_working_on(dir.path(), mine, now),
9491 "no status file means nobody is working on anything"
9492 );
9493
9494 let mut status = Status::new();
9495 status.current = vec![Current {
9496 worker: None,
9497 task: "20260903-080340-0167".to_owned(),
9498 run: mine.to_owned(),
9499 }];
9500 status.updated_at = now;
9501 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9502 assert!(is_working_on(dir.path(), mine, now));
9503 assert!(
9504 !is_working_on(dir.path(), "20260903-105039-3cbf", now),
9505 "a daemon busy with one run is not working on another"
9506 );
9507
9508 status.updated_at = now - jiff::SignedDuration::from_secs(600);
9511 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9512 assert!(
9513 !is_working_on(dir.path(), mine, now),
9514 "a stale heartbeat is a dead daemon, so its run is a leftover"
9515 );
9516 }
9517
9518 #[test]
9519 fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
9520 let dir = tempfile::tempdir().unwrap();
9521 let now = Timestamp::now();
9522
9523 assert!(
9524 !is_working_on_short(dir.path(), "01c2", now),
9525 "no status file means nobody is working on anything"
9526 );
9527
9528 let mut status = Status::new();
9529 status.current = vec![Current {
9530 worker: None,
9531 task: "20260903-080340-0167".to_owned(),
9532 run: "20260903-080619-01c2".to_owned(),
9533 }];
9534 status.updated_at = now;
9535 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9536 assert!(
9537 is_working_on_short(dir.path(), "01c2", now),
9538 "the run's short id is the last block of its full id"
9539 );
9540 assert!(
9541 !is_working_on_short(dir.path(), "3cbf", now),
9542 "a daemon busy with one worktree bay is not working on another"
9543 );
9544 }
9545
9546 #[test]
9547 fn a_newer_status_file_still_yields_a_reading() {
9548 let dir = tempfile::tempdir().unwrap();
9549 std::fs::write(
9552 dir.path().join("daemon.json"),
9553 serde_json::json!({
9554 "schema": 2,
9555 "updated_at": Timestamp::now().to_string(),
9556 "idle": true,
9557 "surprise": { "nested": [1, 2, 3] },
9558 })
9559 .to_string(),
9560 )
9561 .unwrap();
9562
9563 let reading = read_status(dir.path()).expect("a forward-compatible read");
9564 assert!(reading.running(Timestamp::now()));
9565 assert!(reading.idle);
9566 assert!(reading.current.is_empty());
9567 }
9568
9569 #[test]
9570 fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
9571 let dir = tempfile::tempdir().unwrap();
9577 std::fs::write(
9578 dir.path().join("daemon.json"),
9579 serde_json::json!({
9580 "schema": 1,
9581 "pid": 4242,
9582 "updated_at": Timestamp::now().to_string(),
9583 "idle": false,
9584 "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
9585 "completed": 3,
9586 "polls": 9,
9587 })
9588 .to_string(),
9589 )
9590 .unwrap();
9591
9592 let reading = read_status(dir.path()).expect("an older shape must still parse");
9593 assert!(reading.running(Timestamp::now()));
9594 assert_eq!(
9595 reading.current,
9596 vec![Current {
9597 worker: None,
9598 task: "20260902-140501-aaaa".to_owned(),
9599 run: "20260902-140502-bbbb".to_owned(),
9600 }]
9601 );
9602 }
9603
9604 #[test]
9605 fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
9606 let dir = tempfile::tempdir().unwrap();
9607 std::fs::write(
9608 dir.path().join("daemon.json"),
9609 serde_json::json!({
9610 "schema": 1,
9611 "updated_at": Timestamp::now().to_string(),
9612 "idle": true,
9613 "current": null,
9614 })
9615 .to_string(),
9616 )
9617 .unwrap();
9618 let with_null = read_status(dir.path()).expect("null must still parse");
9619 assert!(with_null.current.is_empty());
9620
9621 std::fs::write(
9622 dir.path().join("daemon.json"),
9623 serde_json::json!({
9624 "schema": 1,
9625 "updated_at": Timestamp::now().to_string(),
9626 "idle": true,
9627 })
9628 .to_string(),
9629 )
9630 .unwrap();
9631 let absent = read_status(dir.path()).expect("a missing field must still parse");
9632 assert!(absent.current.is_empty());
9633 }
9634
9635 #[test]
9636 fn a_task_without_a_repository_runs_in_the_daemons_default() {
9637 let fallback = Path::new("/default");
9638 let mut blank = task();
9639 blank.repo = PathBuf::new();
9640 assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
9641 let mut dot = task();
9642 dot.repo = PathBuf::from(".");
9643 assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
9644 assert_eq!(
9645 repo_for(&task(), fallback),
9646 PathBuf::from("/repo"),
9647 "a task that names a repository keeps it"
9648 );
9649 }
9650
9651 #[test]
9652 fn task_implementers_edit_inherits_daemon_config_and_merge() {
9653 let dir = tempfile::tempdir().unwrap();
9654 let path = dir.path().join("explicit.toml");
9655 std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
9656 let opts = Opts {
9657 config: Some(path),
9658 merge: Some("none".into()),
9659 ..Default::default()
9660 };
9661 let mut t = task();
9662 t.set_implementers(
9663 2,
9664 &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9665 .unwrap(),
9666 )
9667 .unwrap();
9668 let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
9669 assert_eq!(cfg.graph.implementers, 2);
9670 assert_eq!(cfg.graph.judges, 1);
9671 assert_eq!(cfg.merge.mode, MergeMode::None);
9672 t.set_implementers(1, &cfg).unwrap();
9673 let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
9674 apply_task_implementers(&mut cfg, &t);
9675 assert_eq!(cfg.graph.implementers, 1);
9676 assert_eq!(cfg.graph.judges, 1);
9677 assert_eq!(cfg.merge.mode, MergeMode::None);
9678 }
9679
9680 #[test]
9681 fn task_implementers_direct_overrides_stay_isolated_after_edits() {
9682 let dir = tempfile::tempdir().unwrap();
9683 let repo = dir.path().join("repo");
9684 std::fs::create_dir(&repo).unwrap();
9685 std::fs::write(
9686 repo.join("magi.toml"),
9687 "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
9688 )
9689 .unwrap();
9690 let daemon_config = dir.path().join("daemon.toml");
9691 std::fs::write(
9692 &daemon_config,
9693 "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
9694 )
9695 .unwrap();
9696 let opts = Opts {
9697 config: Some(daemon_config),
9698 merge: Some("pr".into()),
9699 ..Default::default()
9700 };
9701 let q = Queue::at(dir.path().join("queue"));
9702 let validation: Config =
9703 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9704 .unwrap();
9705 for record in ["{}", r#"{"candidates":2}"#] {
9707 let overrides = serde_json::from_str(record).unwrap();
9708 let filing = crate::direct::Filing {
9709 instruction: "work".into(),
9710 title: "direct".into(),
9711 repo: repo.clone(),
9712 source: crate::queue::Source::Human,
9713 solo: false,
9714 overrides,
9715 review_of: None,
9716 sources: Default::default(),
9717 };
9718 let filed =
9719 crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
9720 let crate::direct::Filed::Standalone {
9721 mut task,
9722 claim: _claim,
9723 } = filed
9724 else {
9725 panic!("local filing")
9726 };
9727 let before = prepare_for(&repo, &opts, &task).unwrap();
9728 assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
9729 assert_eq!(
9730 before.merge.mode,
9731 MergeMode::None,
9732 "daemon --merge must not leak"
9733 );
9734 for n in [2, 1, 2] {
9735 task.set_implementers(n, &validation).unwrap();
9736 q.put(&mut task).unwrap();
9737 task = q.get(&task.id).unwrap();
9738 assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
9739 let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
9740 apply_task_implementers(&mut cfg, &task);
9741 assert_eq!(cfg.graph.implementers, usize::from(n));
9742 assert_eq!(cfg.graph.judges, 2);
9743 assert_eq!(cfg.merge.mode, MergeMode::None);
9744 }
9745 }
9746 }
9747
9748 #[test]
9749 fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
9750 let cfg: Config =
9751 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9752 .unwrap();
9753 let mut t = task();
9754 t.review_of = Some("review-target".into());
9755 t.hold_manual(Some("retry".into()));
9756 let mut previous = RunState::new(
9757 PathBuf::from("/repo"),
9758 "main".into(),
9759 "abc1234".into(),
9760 "review".into(),
9761 cfg.clone(),
9762 );
9763 previous.config.graph.implementers = 2;
9764 for count in [1, 3] {
9765 t.set_implementers(count, &cfg).unwrap();
9766 t.release();
9767 assert_eq!(t.review_of.as_deref(), Some("review-target"));
9768 for proposed in [
9769 Starter::Resume(previous.id.clone()),
9770 Starter::Review("recovery-target".into()),
9771 ] {
9772 assert_eq!(
9773 starter_with_implementers(&t, Some(&previous), proposed),
9774 Starter::Review("review-target".into())
9775 );
9776 }
9777 let mut configured = cfg.clone();
9778 apply_task_implementers(&mut configured, &t);
9779 assert_eq!(configured.graph.implementers, usize::from(count));
9780 assert_eq!(previous.config.graph.implementers, 2);
9781 }
9782 }
9783
9784 #[test]
9785 fn task_implementers_dispatch_and_resume_agree() {
9786 let mut t = task();
9787 let cfg: crate::config::Config =
9788 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9789 .unwrap();
9790 let mut run = RunState::new(
9791 PathBuf::from("/repo"),
9792 "main".into(),
9793 "abc1234".into(),
9794 "work".into(),
9795 cfg.clone(),
9796 );
9797 run.config.graph.implementers = 2;
9798 for n in [2, 1, 3, 2] {
9799 t.set_implementers(n, &cfg).unwrap();
9800 let mut dispatched = cfg.clone();
9801 apply_task_implementers(&mut dispatched, &t);
9802 assert_eq!(dispatched.graph.implementers, usize::from(n));
9803 assert_eq!(implementers_match(&t, &run), n == 2);
9804 for proposed in [
9805 Starter::Resume(run.id.clone()),
9806 Starter::Review("old-branch".into()),
9807 ] {
9808 let expected = if n == 2 {
9809 proposed.clone()
9810 } else {
9811 Starter::Start
9812 };
9813 assert_eq!(
9814 starter_with_implementers(&t, Some(&run), proposed),
9815 expected
9816 );
9817 }
9818 assert_eq!(
9819 run.config.graph.implementers, 2,
9820 "history must not be rewritten"
9821 );
9822 }
9823 t.solo = false;
9824 t.overrides = None;
9825 assert!(implementers_match(&t, &run));
9826 }
9827
9828 #[test]
9829 fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
9830 let mut solo_cfg = Config::default();
9836 solo_cfg.graph.implementers = 3;
9837 let mut solo_task = task();
9838 solo_task.solo = true;
9839 apply_task_implementers(&mut solo_cfg, &solo_task);
9840 assert_eq!(solo_cfg.graph.implementers, 1);
9841
9842 let mut plain_cfg = Config::default();
9843 plain_cfg.graph.implementers = 3;
9844 let plain_task = task();
9845 assert!(!plain_task.solo);
9846 apply_task_implementers(&mut plain_cfg, &plain_task);
9847 assert_eq!(
9848 plain_cfg.graph.implementers, 3,
9849 "a task that did not ask to run alone keeps the config's candidates"
9850 );
9851 }
9852
9853 fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
9854 QuotaLoss {
9855 seat: seat.into(),
9856 node: "judge".into(),
9857 at: at.parse().unwrap(),
9858 reset: reset.map(str::to_string),
9859 }
9860 }
9861
9862 #[test]
9863 fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
9864 let old: Vec<QuotaLoss> = (1..=4)
9865 .map(|i| {
9866 loss(
9867 &format!("judge-{i}"),
9868 "2026-09-23T05:23:00Z",
9869 Some("2:40pm (Asia/Tokyo)"),
9870 )
9871 })
9872 .collect();
9873 let fresh = losses_this_attempt(&old, &old);
9874 assert!(fresh.is_empty());
9875 assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
9876 }
9878
9879 #[test]
9880 fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
9881 let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
9882 let now = Timestamp::now();
9883 let mut after = old.clone();
9884 after.push(loss("judge-2", &now.to_string(), None));
9885 let fresh = losses_this_attempt(&old, &after);
9886 assert_eq!(fresh, vec![after[1].clone()]);
9887 let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
9888 assert_eq!(
9889 until,
9890 now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
9891 );
9892 }
9893
9894 #[test]
9895 fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
9896 let before = vec![
9899 loss("judge-1", "2026-09-23T05:23:00Z", None),
9900 loss("judge-2", "2026-09-23T05:24:00Z", None),
9901 ];
9902 let after = vec![
9903 loss("judge-2", "2026-09-23T05:24:00Z", None),
9904 loss("judge-1", "2026-09-24T01:00:00Z", None),
9905 ];
9906 assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
9907 }
9908
9909 #[test]
9910 fn merge_overrides_are_parsed_or_refused() {
9911 assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
9912 assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
9913 assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
9914 assert!(merge_mode("squash").is_err());
9915 }
9916
9917 #[test]
9918 fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
9919 let now = Timestamp::now();
9920 let fallback = Duration::from_secs(300);
9921 let cap = Duration::from_secs(1800);
9922
9923 assert_eq!(quota_wait(None, now, fallback, cap), fallback);
9925
9926 let soon = now + jiff::SignedDuration::from_secs(600);
9928 assert_eq!(
9929 quota_wait(Some(soon), now, fallback, cap),
9930 Duration::from_secs(600)
9931 );
9932
9933 let past = now - jiff::SignedDuration::from_secs(60);
9936 assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
9937
9938 let far = now + jiff::SignedDuration::from_secs(3 * 3600);
9941 assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
9942 }
9943
9944 #[test]
9945 fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
9946 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
9947
9948 let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
9949 assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
9950
9951 let already_past =
9955 parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
9956 assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
9957
9958 assert!(
9959 parse_reset_hint("session limit reached", now, now).is_none(),
9960 "free text with no recognised shape is not guessed at"
9961 );
9962 assert!(
9963 parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
9964 "an unresolvable zone name is not guessed at either"
9965 );
9966 }
9967
9968 #[test]
9969 fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
9970 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
9971
9972 let at = parse_reset_hint(
9973 "You've hit your usage limit. Visit \
9974 https://chatgpt.com/codex/settings/usage to purchase more \
9975 credits or try again at Sep 19th, 2026 5:10 PM.",
9976 now,
9977 now,
9978 )
9979 .expect("the codex reset wording is a recognised shape");
9980 assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
9981
9982 let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
9987 .expect("an explicit year needs no rollover");
9988 assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
9989
9990 assert!(
9991 parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
9992 "a two-digit year is not the documented shape and is not guessed at"
9993 );
9994 assert!(
9995 parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
9996 "a four-letter month name is not the documented three-letter abbreviation"
9997 );
9998 assert!(
9999 parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
10000 "an explicit zone on the dated shape is a format nobody has \
10001 documented, and is refused rather than guessed at as UTC"
10002 );
10003 }
10004
10005 #[test]
10006 fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
10007 let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
10008 let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
10009
10010 let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
10011 assert_eq!(at.as_second() - recorded.as_second(), 3769);
10012
10013 let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
10014 assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
10015
10016 for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
10017 assert!(
10018 parse_reset_hint(bad, now, recorded).is_none(),
10019 "{bad:?} must not be guessed at"
10020 );
10021 }
10022 }
10023
10024 fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
10028 let config = dir.join("magi.toml");
10029 std::fs::write(
10030 &config,
10031 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
10032 )
10033 .unwrap();
10034 let opts = Opts {
10035 poll: Duration::from_secs(30),
10036 config: Some(config),
10037 repo: dir.join("repo"),
10041 ..Opts::default()
10042 };
10043 let home = dir.join("home");
10052 let stamps = home.join("service-ticks");
10055 std::fs::create_dir_all(&stamps).unwrap();
10056 for service in ["waiter", "deputies", "release-watch"] {
10057 std::fs::write(
10058 stamps.join(service),
10059 Timestamp::now().as_second().to_string(),
10060 )
10061 .unwrap();
10062 }
10063 for operation in [
10064 "conductor",
10065 "maintenance",
10066 "housekeeping",
10067 "disk-pressure",
10068 "cache",
10069 "fetch",
10070 ] {
10071 std::fs::write(
10072 stamps.join(format!("daemon-{operation}")),
10073 serde_json::to_vec(&Timestamp::now()).unwrap(),
10074 )
10075 .unwrap();
10076 }
10077 let worktrees = dir.join("wt");
10078 (
10079 opts,
10080 Queue::at(dir.join("queue")),
10081 home.join("daemon.json"),
10082 home,
10083 worktrees,
10084 )
10085 }
10086
10087 #[test]
10088 fn a_stop_is_idempotent_and_once_set_stays_set() {
10089 let stop = Stop::new();
10090 assert!(!stop.stopped());
10091
10092 stop.stop();
10093 assert!(stop.stopped());
10094 stop.stop();
10095 assert!(stop.stopped(), "a second stop is not a toggle");
10096
10097 let shared = stop.clone();
10098 assert!(
10099 shared.stopped(),
10100 "a clone is the same stop; that is how the loop and its caller share one"
10101 );
10102 }
10103
10104 #[tokio::test]
10105 async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
10106 for operation in ["conductor", "maintenance", "housekeeping"] {
10107 let dir = tempfile::tempdir().unwrap();
10108 let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
10109 opts.once = true;
10110 opts.poll = Duration::from_millis(1);
10111 let mut task = task();
10112 task.runs.push("fixture-run".into());
10113 queue.put(&mut task).unwrap();
10114 let claim = queue.claim(&task.id).unwrap();
10115
10116 let directory = home.join("workers/jobs/abcdef");
10119 std::fs::create_dir_all(&directory).unwrap();
10120 let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
10121 crate::pr_head::try_lock_file(&lease).unwrap();
10122 let mut job = crate::worker::Job {
10123 id: "abcdef".into(),
10124 sequence: 1,
10125 kind: "daemon-service".into(),
10126 key: format!("service:daemon-{operation}"),
10127 payload: serde_json::Value::Null,
10128 generation: "fixture".into(),
10129 version: None,
10130 status: crate::worker::Status::Running,
10131 result: None,
10132 pid: Some(std::process::id()),
10133 created_at: Timestamp::now().as_second() as u64,
10134 finished_at: None,
10135 };
10136 let record = directory.join("job.json");
10137 std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10138
10139 let status = Arc::new(Mutex::new(Status::new()));
10140 let stop = Stop::new();
10141 let mut drain = Box::pin(poll(
10142 &opts,
10143 &queue,
10144 &status,
10145 &home,
10146 &worktrees,
10147 &stop,
10148 DispatchLimits {
10149 max_concurrent: 1,
10150 pause_for_interrupts: false,
10151 recovery_cfg: None,
10152 },
10153 ));
10154 std::future::poll_fn(|cx| {
10155 use std::future::Future;
10156 assert!(
10157 drain.as_mut().poll(cx).is_pending(),
10158 "--once must wait for {operation} to release its queue claim"
10159 );
10160 std::task::Poll::Ready(())
10161 })
10162 .await;
10163 assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
10164
10165 let questions = Questions::at(home.join("questions"));
10168 let mut q = action_question("fixture-run", ask::ChoiceAction::Done);
10169 questions.put(&mut q).unwrap();
10170 drop(claim);
10171 let expired =
10175 serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
10176 for service in [operation, "housekeeping"] {
10177 std::fs::write(
10178 home.join("service-ticks").join(format!("daemon-{service}")),
10179 &expired,
10180 )
10181 .unwrap();
10182 }
10183 job.status = crate::worker::Status::Finished;
10184 std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10185 drop(lease);
10186 tokio::time::timeout(Duration::from_secs(2), drain)
10187 .await
10188 .expect("the settled service must allow the drain to finish")
10189 .unwrap();
10190 let after = queue.get(&task.id).unwrap();
10191 assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
10192 assert!(after.action_applied(&q.id));
10193 for service in [operation, "housekeeping"] {
10194 assert_eq!(
10195 std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
10196 .unwrap(),
10197 expired,
10198 "the final once rescan must not restart {service}"
10199 );
10200 }
10201 }
10202 }
10203
10204 #[test]
10205 fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
10206 let stop = Stop::new();
10207 stop.busy.store(1, Ordering::SeqCst);
10208 assert!(
10209 !stop.finishing(),
10210 "a busy loop nobody has asked to stop is just running"
10211 );
10212
10213 stop.stop();
10214 assert!(
10215 stop.finishing(),
10216 "a stop asked for mid-run has not landed until the run is settled"
10217 );
10218
10219 stop.busy.store(0, Ordering::SeqCst);
10220 assert!(
10221 !stop.finishing(),
10222 "once the run is settled the stop has landed and there is nothing to finish"
10223 );
10224 }
10225
10226 #[test]
10227 fn finishing_stays_true_until_the_last_of_several_runs_exits() {
10228 let stop = Stop::new();
10229 stop.busy.store(2, Ordering::SeqCst);
10230 stop.stop();
10231 assert!(stop.finishing(), "two runs still in flight");
10232
10233 stop.busy.store(1, Ordering::SeqCst);
10234 assert!(
10235 stop.finishing(),
10236 "one run finished, but a sibling is still working"
10237 );
10238
10239 stop.busy.store(0, Ordering::SeqCst);
10240 assert!(
10241 !stop.finishing(),
10242 "the last run out is what actually lands the stop"
10243 );
10244 }
10245
10246 #[tokio::test]
10247 async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
10248 let dir = tempfile::tempdir().unwrap();
10249 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10250 let stop = Stop::new();
10251 stop.stop();
10252
10253 let began = std::time::Instant::now();
10254 tokio::time::timeout(
10255 Duration::from_secs(2),
10256 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10257 )
10258 .await
10259 .expect("a stopped loop must return, not sit out its poll interval")
10260 .expect("the loop's own setup and teardown must not fail");
10261 assert!(
10262 began.elapsed() < opts.poll,
10263 "returned only after {:?}, which is a poll interval, not a stop",
10264 began.elapsed()
10265 );
10266 }
10267
10268 #[tokio::test]
10269 async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
10270 let dir = tempfile::tempdir().unwrap();
10271 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10272 let stop = Stop::new();
10273
10274 let asker = {
10277 let stop = stop.clone();
10278 tokio::spawn(async move {
10279 tokio::time::sleep(Duration::from_millis(20)).await;
10280 stop.stop();
10281 })
10282 };
10283
10284 let began = std::time::Instant::now();
10285 tokio::time::timeout(
10286 Duration::from_secs(2),
10287 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10288 )
10289 .await
10290 .expect("a stop asked for while idle must wake the wait")
10291 .expect("the loop's own setup and teardown must not fail");
10292 asker.await.unwrap();
10293 assert!(
10294 began.elapsed() < opts.poll,
10295 "returned only after {:?}, so the stop waited on the sleep",
10296 began.elapsed()
10297 );
10298 }
10299
10300 #[tokio::test]
10301 async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
10302 let dir = tempfile::tempdir().unwrap();
10303 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10304 let stop = Stop::new();
10305 stop.stop();
10306
10307 tokio::time::timeout(
10308 Duration::from_secs(2),
10309 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10310 )
10311 .await
10312 .expect("a stopped loop must return")
10313 .expect("the loop's own setup and teardown must not fail");
10314
10315 assert!(
10316 home.is_dir(),
10317 "the loop did publish a status file, so its removal is the teardown and not an absence"
10318 );
10319 assert!(
10320 !status_file.exists(),
10321 "a stopped loop clears its status file"
10322 );
10323 assert!(
10324 read_status(&home).is_none(),
10325 "a reader must see no daemon at all, not a heartbeat that merely stopped"
10326 );
10327 }
10328
10329 #[tokio::test]
10330 async fn housekeeping_worker_settles_questions_without_a_scheduler() {
10331 let dir = tempfile::tempdir().unwrap();
10332 let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
10333
10334 let mut settled = RunState::new(
10335 dir.path().join("repo"),
10336 "main".to_owned(),
10337 "abc1234".to_owned(),
10338 "fixture".to_owned(),
10339 Config::default(),
10340 );
10341 settled.status = RunStatus::Ready;
10342 let run_dir = home.join("runs").join(&settled.id);
10343 std::fs::create_dir_all(&run_dir).unwrap();
10344 std::fs::write(
10345 run_dir.join("run.json"),
10346 serde_json::to_string_pretty(&settled).unwrap(),
10347 )
10348 .unwrap();
10349 let questions = Questions::at(home.join("questions"));
10350 let mut question = ask::Question::new(
10351 settled.id.clone(),
10352 "review".to_owned(),
10353 "reviewer-1".to_owned(),
10354 "Continue?".to_owned(),
10355 String::new(),
10356 Vec::new(),
10357 );
10358 questions.put(&mut question).unwrap();
10359
10360 run_service_worker(
10361 &home,
10362 serde_json::to_value(ServiceWorker {
10363 opts,
10364 queue: queue.root().to_path_buf(),
10365 worktrees_root: worktrees,
10366 operation: "housekeeping".to_owned(),
10367 })
10368 .unwrap(),
10369 )
10370 .await
10371 .unwrap();
10372
10373 assert_eq!(
10374 questions.get(&question.id).unwrap().status,
10375 ask::QuestionStatus::Abandoned,
10376 "the independent housekeeping worker settles ended-run questions"
10377 );
10378 }
10379
10380 #[test]
10381 fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
10382 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10383
10384 assert!(
10385 cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
10386 "never checked before: due at once"
10387 );
10388
10389 let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
10390 assert!(
10391 !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
10392 "well inside the interval: not due yet"
10393 );
10394
10395 let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
10396 assert!(
10397 !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
10398 "exactly at the edge: not yet due, same convention as `clean::due`"
10399 );
10400
10401 let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
10402 assert!(
10403 cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
10404 "past the interval: due again"
10405 );
10406 }
10407
10408 fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
10413 let config = dir.join("magi.toml");
10414 std::fs::write(
10420 &config,
10421 format!(
10422 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
10423 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
10424 cache_dir.display()
10425 ),
10426 )
10427 .unwrap();
10428 Opts {
10429 config: Some(config),
10430 repo: dir.join("repo"),
10431 ..Opts::default()
10432 }
10433 }
10434
10435 #[tokio::test]
10436 async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
10437 let dir = tempfile::tempdir().unwrap();
10438 let home = dir.path().join("home");
10439 let cache_dir = dir.path().join("cache");
10440 std::fs::create_dir_all(&cache_dir).unwrap();
10441 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
10442 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
10443
10444 let running = Stop::new();
10447 let mut last_checked = None;
10448 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10449 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
10450 .await;
10451 assert_eq!(
10452 crate::disk::dir_size(&cache_dir),
10453 0,
10454 "over the cap on the first check ever: pruned at once, no idle queue required"
10455 );
10456 assert_eq!(last_checked, Some(t0));
10457
10458 std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
10460 let too_soon = t0 + jiff::SignedDuration::from_secs(1);
10461 maybe_prune_cache_between_runs(
10462 &opts.repo,
10463 &opts,
10464 &home,
10465 &running,
10466 &mut last_checked,
10467 too_soon,
10468 )
10469 .await;
10470 assert_eq!(
10471 crate::disk::dir_size(&cache_dir),
10472 10,
10473 "too soon since the last check: left alone rather than rescanned every call"
10474 );
10475 assert_eq!(
10476 last_checked,
10477 Some(t0),
10478 "an idle check does not reset the clock"
10479 );
10480
10481 let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
10483 maybe_prune_cache_between_runs(
10484 &opts.repo,
10485 &opts,
10486 &home,
10487 &running,
10488 &mut last_checked,
10489 due_again,
10490 )
10491 .await;
10492 assert_eq!(
10493 crate::disk::dir_size(&cache_dir),
10494 0,
10495 "due again: pruned back under the cap"
10496 );
10497 }
10498
10499 #[tokio::test]
10507 async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
10508 let dir = tempfile::tempdir().unwrap();
10509 let home = dir.path().join("home");
10510 let cache_dir = dir.path().join("cache");
10511 std::fs::create_dir_all(&cache_dir).unwrap();
10512 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
10513 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
10514
10515 let stop = Stop::new();
10516 stop.stop();
10517 assert!(
10518 !stop.finishing(),
10519 "no run is in flight at a between-runs boundary, so nothing else \
10520 would tell the operator this stop had not taken effect yet"
10521 );
10522
10523 let mut last_checked = None;
10524 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10525 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
10526 .await;
10527 assert_eq!(
10528 crate::disk::dir_size(&cache_dir),
10529 10,
10530 "over its cap, and due for the first check ever, but a stop outranks \
10531 it: the cap is a standing policy the next start measures again"
10532 );
10533 assert_eq!(
10534 last_checked, None,
10535 "a check that never happened must not claim the interval"
10536 );
10537 }
10538
10539 #[tokio::test]
10542 async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
10543 let dir = tempfile::tempdir().unwrap();
10544 let cache_dir = dir.path().join("cache");
10545 std::fs::create_dir_all(&cache_dir).unwrap();
10546 std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
10547
10548 let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
10549 opts.poll = Duration::from_millis(20);
10550 opts.max_attempts = 1_000;
10551
10552 let queue = Queue::at(dir.path().join("queue"));
10553 for i in 0..128 {
10554 let mut task = Task::new(
10555 format!("queued work {i}"),
10556 format!("queued work {i}"),
10557 opts.repo.clone(),
10558 Source::Human,
10559 );
10560 queue.put(&mut task).unwrap();
10561 }
10562
10563 let home = dir.path().join("home");
10564 let worktrees = dir.path().join("wt");
10565 run_service_worker(
10566 &home,
10567 serde_json::to_value(ServiceWorker {
10568 opts,
10569 queue: queue.root().to_path_buf(),
10570 worktrees_root: worktrees,
10571 operation: "cache".to_owned(),
10572 })
10573 .unwrap(),
10574 )
10575 .await
10576 .unwrap();
10577 let after = queue.list();
10578 assert_eq!(after.len(), 128);
10579 assert!(
10580 after
10581 .iter()
10582 .all(|task| task.status.runnable() && task.attempts == 0)
10583 );
10584
10585 assert_eq!(
10586 crate::disk::dir_size(&cache_dir),
10587 0,
10588 "an oversized cache must not be left to grow unboundedly just because the \
10589 queue kept the loop busy the whole time"
10590 );
10591 }
10592
10593 #[test]
10594 fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
10595 let dir = tempfile::tempdir().unwrap();
10596 let queue = Queue::at(dir.path().join("queue"));
10597 let questions = Questions::at(dir.path().join("questions"));
10598 let mut task = task();
10599 queue.put(&mut task).unwrap();
10600
10601 let mut task_question = ask::Question::new(
10602 task.id.clone(),
10603 crate::conduct::NODE.to_owned(),
10604 "conduct".to_owned(),
10605 "Which backend?".to_owned(),
10606 String::new(),
10607 Vec::new(),
10608 );
10609 questions.put(&mut task_question).unwrap();
10610 task.block(vec![task_question.id.clone()], None);
10611 queue.put(&mut task).unwrap();
10612
10613 let mut run_question = ask::Question::new(
10614 "20260101-000000-run1".to_owned(),
10615 "review".to_owned(),
10616 "reviewer-1".to_owned(),
10617 "Run question".to_owned(),
10618 String::new(),
10619 Vec::new(),
10620 );
10621 questions.put(&mut run_question).unwrap();
10622
10623 let mut coincidental = ask::Question::new(
10628 task.id.clone(),
10629 "review".to_owned(),
10630 "reviewer-1".to_owned(),
10631 "Unrelated review question".to_owned(),
10632 String::new(),
10633 Vec::new(),
10634 );
10635 questions.put(&mut coincidental).unwrap();
10636
10637 reconcile_task_questions(&queue, &questions);
10638 assert!(questions.get(&task_question.id).unwrap().status.open());
10639 assert!(questions.get(&run_question.id).unwrap().status.open());
10640 assert!(questions.get(&coincidental.id).unwrap().status.open());
10641
10642 task.release();
10643 queue.put(&mut task).unwrap();
10644 reconcile_task_questions(&queue, &questions);
10645 assert_eq!(
10646 questions.get(&task_question.id).unwrap().status,
10647 ask::QuestionStatus::Abandoned
10648 );
10649 assert!(
10650 questions.get(&run_question.id).unwrap().status.open(),
10651 "run questions remain the run janitor's responsibility"
10652 );
10653 assert!(
10654 questions.get(&coincidental.id).unwrap().status.open(),
10655 "a non-conductor question must not be abandoned just because its \
10656 run id coincides with a task id"
10657 );
10658 }
10659
10660 #[test]
10661 fn a_freshly_started_running_task_is_never_stalled() {
10662 let dir = tempfile::tempdir().unwrap();
10663 let mut t = task();
10664 t.start("run-1".to_owned());
10665 assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
10668 }
10669
10670 #[test]
10671 fn a_long_running_task_with_no_live_daemon_is_stalled() {
10672 let dir = tempfile::tempdir().unwrap();
10673 let mut t = task();
10674 t.start("run-1".to_owned());
10675 t.updated_at = Timestamp::now()
10676 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
10677 assert!(is_stalled(&t, dir.path(), Timestamp::now()));
10678 assert_eq!(
10679 stalled_tasks(
10680 &Queue::at(dir.path().join("q")),
10681 dir.path(),
10682 Timestamp::now()
10683 )
10684 .len(),
10685 0,
10686 "the task was never written to this queue"
10687 );
10688 }
10689
10690 #[test]
10691 fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
10692 let dir = tempfile::tempdir().unwrap();
10693 let mut t = task();
10694 t.id = "20260903-080340-0167".to_owned();
10695 t.start("20260903-080619-01c2".to_owned());
10696 t.updated_at = Timestamp::now()
10697 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
10698
10699 let mut status = Status::new();
10700 status.current = vec![Current {
10701 worker: None,
10702 task: t.id.clone(),
10703 run: "20260903-080619-01c2".to_owned(),
10704 }];
10705 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10706
10707 assert!(
10708 !is_stalled(&t, dir.path(), Timestamp::now()),
10709 "a live daemon's own heartbeat rules out stalled, however long the task has run"
10710 );
10711 }
10712
10713 fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
10717 let path = queue.path_of(id);
10718 let body = std::fs::read_to_string(&path).unwrap();
10719 let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
10720 let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
10721 v["updated_at"] = serde_json::Value::String(old.to_string());
10722 std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
10723 }
10724
10725 #[test]
10726 fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
10727 let dir = tempfile::tempdir().unwrap();
10740 let queue = Queue::at(dir.path().join("queue"));
10741 let home = dir.path().join("home");
10742
10743 let mut t = task();
10744 t.id = "20260101-000001-lock".to_owned();
10745 t.start("run-1".to_owned());
10746 queue.put(&mut t).unwrap();
10747 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
10748 std::fs::write(
10749 dir.path().join("queue").join(format!("{}.lock", t.id)),
10750 "not a pid",
10751 )
10752 .unwrap();
10753
10754 let now = Timestamp::now();
10755 assert!(
10756 reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
10757 "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
10758 and reclaim must leave the task alone"
10759 );
10760 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
10761
10762 let stalled = stalled_tasks(&queue, &home, now);
10763 assert_eq!(
10764 stalled.len(),
10765 1,
10766 "reclaim's inability to claim it yet must not hide it from the conductor"
10767 );
10768 assert_eq!(stalled[0].id, t.id);
10769 }
10770
10771 #[test]
10772 fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
10773 let dir = tempfile::tempdir().unwrap();
10774 crate::run::set_home(dir.path().join("run-home"));
10775 let queue = Queue::at(dir.path().join("queue"));
10776 let home = dir.path().join("home");
10777 let questions = Questions::at(dir.path().join("questions"));
10778
10779 let mut t = task();
10780 t.id = "20260101-000003-dead".to_owned();
10781 t.start("missing-run".to_owned());
10782 queue.put(&mut t).unwrap();
10783 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
10784
10785 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
10788 assert_eq!(
10789 stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
10790 [&t.id]
10791 );
10792 assert_eq!(
10793 reclaim_orphaned_running(&queue, 2, &Default::default()),
10794 [t.id.clone()]
10795 );
10796 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10797
10798 crate::conduct::apply(
10801 &queue,
10802 &questions,
10803 &crate::conduct::Verdict {
10804 decisions: vec![crate::conduct::Decision {
10805 id: t.id.clone(),
10806 recovery: Some(crate::conduct::Recovery::Requeue),
10807 ..crate::conduct::Decision::default()
10808 }],
10809 },
10810 )
10811 .unwrap();
10812 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
10813 }
10814
10815 #[test]
10816 fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
10817 let dir = tempfile::tempdir().unwrap();
10818 let queue = Queue::at(dir.path().join("queue"));
10819 let home = dir.path().join("home");
10820
10821 let mut fresh = task();
10822 fresh.id = "20260101-000001-aaaa".to_owned();
10823 fresh.start("run-1".to_owned());
10824 queue.put(&mut fresh).unwrap();
10825
10826 let mut old = task();
10827 old.id = "20260101-000002-bbbb".to_owned();
10828 old.start("run-2".to_owned());
10829 queue.put(&mut old).unwrap();
10830 backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
10831
10832 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
10833 assert_eq!(stalled.len(), 1);
10834 assert_eq!(stalled[0].id, old.id);
10835 }
10836
10837 #[test]
10838 fn queued_and_finished_task_views_partition_by_status() {
10839 let dir = tempfile::tempdir().unwrap();
10840 let queue = Queue::at(dir.path().join("queue"));
10841
10842 let mut queued = task();
10843 queued.id = "20260101-000001-aaaa".to_owned();
10844 queue.put(&mut queued).unwrap();
10845
10846 let mut failed = task();
10847 failed.id = "20260101-000002-bbbb".to_owned();
10848 failed.start("run-1".to_owned());
10849 failed.fail("gate red", 5);
10850 queue.put(&mut failed).unwrap();
10851
10852 let mut held = task();
10853 held.id = "20260101-000003-cccc".to_owned();
10854 held.hold_machine(None);
10855 queue.put(&mut held).unwrap();
10856
10857 let mut running = task();
10858 running.id = "20260101-000004-dddd".to_owned();
10859 running.start("run-2".to_owned());
10860 queue.put(&mut running).unwrap();
10861
10862 let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
10863 assert_eq!(queued_ids, [queued.id.clone()]);
10864
10865 let mut finished_ids: Vec<String> =
10866 finished_tasks(&queue).into_iter().map(|t| t.id).collect();
10867 finished_ids.sort_unstable();
10868 let mut want = vec![failed.id.clone(), held.id.clone()];
10869 want.sort_unstable();
10870 assert_eq!(finished_ids, want);
10871 }
10872
10873 #[test]
10874 fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
10875 for short in [false, true] {
10876 let dir = tempfile::tempdir().unwrap();
10877 let queue = Queue::at(dir.path().join("queue"));
10878 let questions = ask::Questions::at(dir.path().join("questions"));
10879 let mut running = task();
10880 running.id = "20261013-192213-feb2".into();
10881 running.start("existing-run".into());
10882 queue.put(&mut running).unwrap();
10883 let mut middle = task();
10884 middle.id = "20261013-193611-ca5b".into();
10885 middle.block(
10886 vec![if short {
10887 "feb2".into()
10888 } else {
10889 running.id.clone()
10890 }],
10891 None,
10892 );
10893 queue.put(&mut middle).unwrap();
10894 let mut waiting = task();
10895 waiting.id = "20261013-202849-ee37".into();
10896 waiting.block(
10897 vec![if short {
10898 "ca5b".into()
10899 } else {
10900 middle.id.clone()
10901 }],
10902 Some("wait for implementation".into()),
10903 );
10904 queue.put(&mut waiting).unwrap();
10905 assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
10906 let inv = crate::blockers::Inventory::load(&queue, &questions);
10907 assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
10908 assert!(inv.stuck().is_empty());
10909 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
10910 assert!(report.quarantined.is_empty());
10911 assert!(report.asked.is_empty());
10912 resolve_blockers(&queue, &questions);
10913 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
10914 assert!(questions.list().is_empty());
10915 running.succeed();
10918 queue.put(&mut running).unwrap();
10919 resolve_blockers(&queue, &questions);
10920 assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
10921 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
10922 middle = queue.get(&middle.id).unwrap();
10923 middle.succeed();
10924 queue.put(&mut middle).unwrap();
10925 resolve_blockers(&queue, &questions);
10926 let after = queue.get(&waiting.id).unwrap();
10927 assert_eq!(after.status, TaskStatus::Queued);
10928 assert!(after.blocked_by.is_empty());
10929 assert_eq!(after.instruction, waiting.instruction);
10930 }
10931 }
10932
10933 #[test]
10934 fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
10935 for future_schema in [false, true] {
10936 let name = "20261013-193611-ca5b";
10937 let mut future = task();
10938 future.id = name.into();
10939 future.schema = crate::queue::SCHEMA + 1;
10940 let contents = if future_schema {
10941 serde_json::to_string(&future).unwrap()
10942 } else {
10943 "corrupt".into()
10944 };
10945 let dir = tempfile::tempdir().unwrap();
10946 let queue = Queue::at(dir.path().join("queue"));
10947 let questions = ask::Questions::at(dir.path().join("questions"));
10948 let mut waiting = task();
10949 waiting.id = "20261013-202849-ee37".into();
10950 waiting.block(vec!["ca5b".into()], None);
10951 queue.put(&mut waiting).unwrap();
10952 std::fs::write(queue.path_of(name), contents).unwrap();
10953 assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
10954 assert!(
10955 crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
10956 );
10957 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
10958 assert!(report.asked.is_empty());
10959 resolve_blockers(&queue, &questions);
10960 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
10961 assert!(questions.list().is_empty());
10962 }
10963 let dir = tempfile::tempdir().unwrap();
10964 let queue = Queue::at(dir.path().join("queue"));
10965 let questions = ask::Questions::at(dir.path().join("questions"));
10966 let mut waiting = task();
10967 waiting.id = "20261013-202849-ee37".into();
10968 waiting.block(vec!["ca5b".into()], None);
10969 queue.put(&mut waiting).unwrap();
10970 let mut done = task();
10971 done.id = "20261013-193611-ca5b".into();
10972 done.succeed();
10973 queue.put(&mut done).unwrap();
10974 std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
10977 assert!(queue.get("ca5b").is_err());
10978 assert_eq!(
10979 crate::queue::dependency(&queue, &questions, "ca5b"),
10980 crate::queue::Dependency::Ambiguous
10981 );
10982 resolve_blockers(&queue, &questions);
10983 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
10984 assert!(report.asked.is_empty());
10985 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
10986 assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
10987 }
10988
10989 #[test]
10990 fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
10991 for held in [false, true] {
10992 for question in [false, true] {
10993 for reference in ["ca5b", "20261013-193611-ca5b"] {
10994 let dir = tempfile::tempdir().unwrap();
10995 let queue = Queue::at(dir.path().join("queue"));
10996 let questions = ask::Questions::at(dir.path().join("questions"));
10997 let mut prerequisite = task();
10998 prerequisite.id = "20261013-193611-ca5b".into();
10999 prerequisite.start("existing-run".into());
11000 queue.put(&mut prerequisite).unwrap();
11001 let mut waiting = task();
11002 waiting.id = "20261013-202849-ee37".into();
11003 if held {
11004 waiting.hold_machine(Some("waiting for separate consent".into()));
11005 }
11006 queue.put(&mut waiting).unwrap();
11007 let reason = "Deleting saved data requires separate owner consent";
11008 crate::conduct::apply(
11009 &queue,
11010 &questions,
11011 &crate::conduct::Verdict {
11012 decisions: vec![crate::conduct::Decision {
11013 id: waiting.id.clone(),
11014 blocked_by: vec![reference.into()],
11015 question: question.then(|| "May the saved data be deleted?".into()),
11016 recovery: (!question).then_some(crate::conduct::Recovery::Hold),
11017 reason: Some(reason.into()),
11018 ..crate::conduct::Decision::default()
11019 }],
11020 },
11021 )
11022 .unwrap();
11023 let before = queue.get(&waiting.id).unwrap();
11024 if question {
11025 assert_eq!(before.status, TaskStatus::Blocked);
11026 let q = questions.get(&before.blocked_by[0]).unwrap();
11027 assert_eq!(q.summary, "May the saved data be deleted?");
11028 assert!(q.status.open());
11029 } else {
11030 assert_eq!(before.status, TaskStatus::Held);
11031 let recorded_reason = before.hold_reason.as_deref().unwrap();
11032 assert!(recorded_reason.starts_with(reason));
11033 if held {
11034 assert!(recorded_reason.contains("waiting for separate consent"));
11035 }
11036 }
11037 prerequisite.succeed();
11038 queue.put(&mut prerequisite).unwrap();
11039 resolve_blockers(&queue, &questions);
11040 let after = queue.get(&waiting.id).unwrap();
11041 assert_eq!(after.status, before.status);
11042 assert_eq!(after.blocked_by, before.blocked_by);
11043 assert_eq!(after.hold_reason, before.hold_reason);
11044 assert_eq!(after.instruction, waiting.instruction);
11045 if question {
11046 assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
11047 }
11048 assert!(
11049 queue.next_runnable().is_none(),
11050 "dependency completion is not consent"
11051 );
11052 }
11053 }
11054 }
11055 }
11056
11057 #[test]
11058 fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
11059 let dir = tempfile::tempdir().unwrap();
11060 let queue = Queue::at(dir.path().join("queue"));
11061 let questions = ask::Questions::at(dir.path().join("questions"));
11062
11063 let mut dep = task();
11064 dep.id = "20260101-000001-dep0".to_owned();
11065 dep.succeed();
11066 queue.put(&mut dep).unwrap();
11067
11068 let mut still_going = task();
11069 still_going.id = "20260101-000002-dep1".to_owned();
11070 queue.put(&mut still_going).unwrap();
11071
11072 let mut blocked = task();
11073 blocked.id = "20260101-000003-main".to_owned();
11074 blocked.block(
11075 vec![dep.id.clone(), still_going.id.clone()],
11076 Some("waits on both".to_owned()),
11077 );
11078 queue.put(&mut blocked).unwrap();
11079
11080 resolve_blockers(&queue, &questions);
11081
11082 let after = queue.get(&blocked.id).unwrap();
11083 assert_eq!(
11084 after.status,
11085 TaskStatus::Blocked,
11086 "one dependency is still outstanding"
11087 );
11088 assert_eq!(after.blocked_by, [still_going.id.clone()]);
11089 }
11090
11091 #[test]
11092 fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
11093 let dir = tempfile::tempdir().unwrap();
11094 let queue = Queue::at(dir.path().join("queue"));
11095 let questions = ask::Questions::at(dir.path().join("questions"));
11096
11097 let mut q = crate::ask::Question::new(
11098 "20260101-000001-main".to_owned(),
11099 crate::conduct::NODE.to_owned(),
11100 "conduct".to_owned(),
11101 "Which backend?".to_owned(),
11102 String::new(),
11103 Vec::new(),
11104 );
11105 questions.put(&mut q).unwrap();
11106 q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
11107 .unwrap();
11108 questions.put(&mut q).unwrap();
11109
11110 let mut blocked = task();
11111 blocked.id = "20260101-000001-main".to_owned();
11112 blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
11113 queue.put(&mut blocked).unwrap();
11114
11115 resolve_blockers(&queue, &questions);
11116
11117 let after = queue.get(&blocked.id).unwrap();
11118 assert_eq!(
11119 after.status,
11120 TaskStatus::Queued,
11121 "the only blocker resolved"
11122 );
11123 assert_eq!(after.answers.len(), 1);
11124 assert_eq!(after.answers[0].question, "Which backend?");
11125 assert_eq!(after.answers[0].answer, "SQLite");
11126
11127 let instruction = instruction_for(&after);
11129 assert!(instruction.contains("Which backend?"));
11130 assert!(instruction.contains("SQLite"));
11131 }
11132
11133 #[test]
11134 fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
11135 let dir = tempfile::tempdir().unwrap();
11136 let queue = Queue::at(dir.path().join("queue"));
11137 let questions = ask::Questions::at(dir.path().join("questions"));
11138
11139 let mut q = crate::ask::Question::new(
11140 "20260101-000001-main".to_owned(),
11141 crate::conduct::NODE.to_owned(),
11142 "conduct".to_owned(),
11143 "Is the setup done?".to_owned(),
11144 String::new(),
11145 Vec::new(),
11146 );
11147 q.abandon("no answer within 60s of asking");
11148 questions.put(&mut q).unwrap();
11149
11150 let mut blocked = task();
11151 blocked.id = "20260101-000001-main".to_owned();
11152 blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
11153 queue.put(&mut blocked).unwrap();
11154
11155 resolve_blockers(&queue, &questions);
11156
11157 let after = queue.get(&blocked.id).unwrap();
11158 assert_eq!(
11159 after.status,
11160 TaskStatus::Held,
11161 "never left blocked on nothing"
11162 );
11163 assert!(!after.operator_held(), "a machine hold, for triage");
11164 assert!(
11165 after
11166 .hold_reason
11167 .as_deref()
11168 .unwrap_or_default()
11169 .contains("went unanswered")
11170 );
11171 }
11172
11173 #[test]
11174 fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
11175 let dir = tempfile::tempdir().unwrap();
11181 let queue = Queue::at(dir.path().join("queue"));
11182 let questions = ask::Questions::at(dir.path().join("questions"));
11183
11184 let mut q = crate::ask::Question::new(
11185 "20260101-000001-main".to_owned(),
11186 crate::conduct::NODE.to_owned(),
11187 "conduct".to_owned(),
11188 "How should this be handled?".to_owned(),
11189 String::new(),
11190 Vec::new(),
11191 );
11192 questions.put(&mut q).unwrap();
11193 q.answer(crate::ask::Answer::Text(
11194 "leave it held, a human will look at it later".to_owned(),
11195 ))
11196 .unwrap();
11197 questions.put(&mut q).unwrap();
11198
11199 let mut held = task();
11200 held.id = "20260101-000001-main".to_owned();
11201 held.hold_machine(Some("out of attempts".to_owned()));
11202 held.block(vec![q.id.clone()], Some("what now?".to_owned()));
11203 queue.put(&mut held).unwrap();
11204
11205 resolve_blockers(&queue, &questions);
11206
11207 let after = queue.get(&held.id).unwrap();
11208 assert_eq!(after.status, TaskStatus::Held);
11209 assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
11210 assert_eq!(
11211 after.answers[0].answer,
11212 "leave it held, a human will look at it later"
11213 );
11214 }
11215
11216 #[test]
11217 fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
11218 let dir = tempfile::tempdir().unwrap();
11219 let queue = Queue::at(dir.path().join("queue"));
11220 let questions = ask::Questions::at(dir.path().join("questions"));
11221 let mut dep = task();
11222 dep.id = "20260101-000001-gone".to_owned();
11223 queue.put(&mut dep).unwrap();
11224 let mut blocked = task();
11225 blocked.id = "20260101-000003-main".to_owned();
11226 blocked.block(vec![dep.id.clone()], None);
11227 queue.put(&mut blocked).unwrap();
11228
11229 let claim = queue.claim(&blocked.id).unwrap();
11231 queue.remove(&dep.id, false, &questions).unwrap();
11232 drop(claim);
11233 resolve_blockers(&queue, &questions);
11234
11235 let after = queue.get(&blocked.id).unwrap();
11236 assert_eq!(after.status, TaskStatus::Queued);
11237 assert!(after.blocked_by.is_empty());
11238 }
11239
11240 #[test]
11241 fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
11242 let dir = tempfile::tempdir().unwrap();
11248 let queue = Queue::at(dir.path().join("queue"));
11249 let questions = ask::Questions::at(dir.path().join("questions"));
11250
11251 let mut still_going = task();
11252 still_going.id = "20260101-000002-dep1".to_owned();
11253 queue.put(&mut still_going).unwrap();
11254
11255 let mut blocked = task();
11256 blocked.id = "20260101-000003-main".to_owned();
11257 blocked.block(
11258 vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
11259 Some("waits on both".to_owned()),
11260 );
11261 queue.put(&mut blocked).unwrap();
11262
11263 resolve_blockers(&queue, &questions);
11264
11265 let after = queue.get(&blocked.id).unwrap();
11266 assert_eq!(
11267 after.status,
11268 TaskStatus::Held,
11269 "a missing dependency must not leave the task blocked forever"
11270 );
11271 assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
11272 assert!(after.blocked_by.is_empty());
11273 let reason = after.hold_reason.as_deref().unwrap_or_default();
11274 assert!(
11275 reason.contains("20260101-000001-gone"),
11276 "the missing id must be named so an operator can tell what happened: {reason}"
11277 );
11278 assert!(
11279 reason.contains(&still_going.id),
11280 "the still-valid dependency must not silently vanish from the record: {reason}"
11281 );
11282 }
11283
11284 #[test]
11285 fn instruction_for_is_unchanged_without_any_answers() {
11286 let t = task();
11287 assert_eq!(instruction_for(&t), t.instruction);
11288 }
11289
11290 #[test]
11291 fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
11292 let dir = tempfile::tempdir().unwrap();
11293 let q = Queue::at(dir.path().join("queue"));
11294 let src = dir.path().join("shot.png");
11295 std::fs::write(&src, "x").unwrap();
11296 let mut t = task();
11297 q.attach(&mut t, &[src]).unwrap();
11298 let paths = task_attachments(&q, &t).unwrap();
11299 assert_eq!(paths.len(), 1);
11300 assert!(paths[0].is_absolute() && paths[0].is_file());
11301 std::fs::remove_file(&paths[0]).unwrap();
11302 let err = task_attachments(&q, &t).unwrap_err().to_string();
11303 assert!(err.contains("shot.png"), "{err}");
11304 }
11305
11306 #[tokio::test]
11307 async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
11308 let dir = tempfile::tempdir().unwrap();
11309 let queue_path = dir.path().join("queue");
11310 let queue = Queue::at(queue_path.clone());
11311 let mut t = task();
11312 t.source = Source::Agent {
11313 run: "originating-chat".into(),
11314 node: crate::queue::CHAT_NODE.into(),
11315 };
11316 let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
11317 stage: "config-fetch",
11318 target: "origin/main".into(),
11319 });
11320 record_config_failure(&mut t, &fetch);
11321 t.hold_machine(Some(format!("{fetch:#}")));
11322 let fetch_key = t.chat_notice_due().unwrap();
11323 t.chat_notices.push(fetch_key.clone());
11324 queue.put(&mut t).unwrap();
11325
11326 let queue = Queue::at(queue_path);
11327 let mut t = queue.get(&t.id).unwrap();
11328 let a = dir.path().join("a.toml");
11329 let b = dir.path().join("b.toml");
11330 for (path, text, new_cause) in [
11331 (&a, "[graph", true),
11332 (&a, "[verify", false),
11333 (&a, "[graph]\nimplementers = 'invalid-type'", true),
11334 (&b, "[graph]\nimplementers = 'invalid-type'", true),
11335 ] {
11336 t.release_operator("test", None);
11337 std::fs::write(path, text).unwrap();
11338 let error = Config::discover_fetched(dir.path(), Some(path))
11339 .await
11340 .unwrap_err();
11341 record_config_failure(&mut t, &error);
11342 t.hold_machine(Some(format!("{error:#}")));
11343 let due = t.chat_notice_due();
11344 assert_eq!(due.is_some(), new_cause, "{error:#}");
11345 if let Some(key) = due {
11346 assert_ne!(key, fetch_key);
11347 t.chat_notices.push(key);
11348 }
11349 }
11350 t.succeed();
11351 assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
11352 }
11353
11354 #[test]
11355 fn different_missing_attachments_have_distinct_persisted_notice_causes() {
11356 let dir = tempfile::tempdir().unwrap();
11357 let queue_path = dir.path().join("queue");
11358 let queue = Queue::at(queue_path.clone());
11359 let mut t = task();
11360 t.source = crate::queue::Source::Agent {
11361 run: "originating-chat".into(),
11362 node: crate::queue::CHAT_NODE.into(),
11363 };
11364 let a = dir.path().join("a.png");
11365 let b = dir.path().join("b.png");
11366 std::fs::write(&a, "a").unwrap();
11367 std::fs::write(&b, "b").unwrap();
11368 queue.attach(&mut t, &[a, b]).unwrap();
11369 let paths = task_attachments(&queue, &t).unwrap();
11370 for path in &paths {
11371 std::fs::remove_file(path).unwrap();
11372 }
11373 let missing = task_attachments(&queue, &t).unwrap_err();
11374 t.attempts += 1;
11375 let reason = missing.to_string();
11376 t.fail_startup_target("startup-attachments", missing.name, reason, 1);
11377 let first = t.chat_notice_due().expect("first attachment notice");
11378 t.chat_notices.push(first.clone());
11379 queue.put(&mut t).unwrap();
11380
11381 let queue = Queue::at(queue_path.clone());
11382 let mut t = queue.get(&t.id).unwrap();
11383 assert!(t.chat_notice_due().is_none(), "restart does not replay");
11384 t.release_operator("test", None);
11385 t.attempts += 1;
11386 let missing = task_attachments(&queue, &t).unwrap_err();
11387 t.fail_startup_target(
11388 "startup-attachments",
11389 missing.name,
11390 "same missing attachment with regenerated wording",
11391 1,
11392 );
11393 assert!(t.chat_notice_due().is_none(), "same object stays quiet");
11394
11395 std::fs::write(&paths[0], "restored").unwrap();
11396 t.release_operator("test", None);
11397 t.attempts += 1;
11398 let missing = task_attachments(&queue, &t).unwrap_err();
11399 let reason = missing.to_string();
11400 t.fail_startup_target("startup-attachments", missing.name, reason, 1);
11401 let second = t
11402 .chat_notice_due()
11403 .expect("different attachment must notify");
11404 assert_ne!(first, second);
11405 assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
11406 }
11407
11408 #[test]
11409 fn resumed_instruction_is_unchanged_without_any_answers() {
11410 let t = task();
11411 assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
11412 }
11413
11414 #[test]
11415 fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
11416 let mut t = task();
11417 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11418 let old = t.instruction.clone();
11422
11423 let refreshed = resumed_instruction(&old, &t);
11424 assert!(refreshed.starts_with(&old), "the original text is kept");
11425 assert!(refreshed.contains("Which backend?"));
11426 assert!(refreshed.contains("SQLite"));
11427 }
11428
11429 #[test]
11430 fn resumed_instruction_keeps_an_original_answers_heading() {
11431 let mut t = task();
11432 t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
11433 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11434
11435 let refreshed = resumed_instruction(&t.instruction, &t);
11436
11437 assert!(
11438 refreshed.starts_with(&t.instruction),
11439 "an answers heading in the original instruction is not the appended block"
11440 );
11441 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
11442 assert!(refreshed.contains("Which backend?"));
11443 assert!(refreshed.contains("SQLite"));
11444
11445 let repeated = resumed_instruction(&refreshed, &t);
11446 assert_eq!(
11447 repeated, refreshed,
11448 "only the final appended block is refreshed"
11449 );
11450 }
11451
11452 #[test]
11453 fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
11454 let mut t = task();
11455 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11456
11457 let once = resumed_instruction(&t.instruction, &t);
11461 let twice = resumed_instruction(&once, &t);
11462 assert_eq!(once, twice);
11463 assert_eq!(once.matches("Which backend?").count(), 1);
11464
11465 t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
11467 let refreshed = resumed_instruction(&once, &t);
11468 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
11469 assert!(refreshed.contains("Which backend?"));
11470 assert!(refreshed.contains("Which cache?"));
11471 }
11472
11473 #[test]
11474 fn prepare_instruction_covers_all_three_starters() {
11475 let mut t = task();
11476 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11477
11478 assert_eq!(
11481 prepare_instruction(&Starter::Start, None, &t),
11482 Some(instruction_for(&t))
11483 );
11484
11485 let old = t.instruction.clone();
11488 assert_eq!(
11489 prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
11490 Some(resumed_instruction(&old, &t))
11491 );
11492
11493 assert_eq!(
11497 prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
11498 None
11499 );
11500 }
11501
11502 #[test]
11503 fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
11504 assert_eq!(
11505 choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
11506 Starter::Review("magi/eba2/A".to_owned())
11507 );
11508 }
11509
11510 #[test]
11511 fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
11512 assert_eq!(
11513 choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
11514 Starter::Start,
11515 "a vanished review branch must not fall back to resuming the old run either"
11516 );
11517 }
11518
11519 #[test]
11520 fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
11521 let mut t = task();
11522 t.start("old-run".to_owned());
11523 t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
11524 t.release();
11525 let branch = t.review_branch.take();
11526 assert_eq!(
11527 choose_starter(branch.as_deref(), true, Some("old-run")),
11528 Starter::Review("magi/eba2/A".to_owned()),
11529 "a review wins over resuming the old run"
11530 );
11531 }
11532
11533 #[test]
11534 fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
11535 assert_eq!(
11536 choose_starter(None, false, Some("some-run")),
11537 Starter::Resume("some-run".to_owned())
11538 );
11539 assert_eq!(choose_starter(None, false, None), Starter::Start);
11540 }
11541
11542 #[test]
11543 fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
11544 let mut released = task();
11545 released.start("stalled-run".to_owned());
11546 released.requeue();
11547 let unfinished = (!released.fresh_start)
11548 .then(|| Some("stalled-run".to_owned()))
11549 .flatten();
11550 assert_eq!(
11551 choose_starter(None, false, unfinished.as_deref()),
11552 Starter::Start,
11553 "release keeps run history but must not resume it"
11554 );
11555 assert_eq!(released.runs, ["stalled-run"]);
11556 }
11557
11558 fn stopped_public_run(status: RunStatus) -> RunState {
11559 let mut state = run_state(status);
11560 state.driver_exited = true;
11561 state.config.graph.land = true;
11562 state.config.graph.review_rounds = 1;
11563 state.reviews = vec![review_round(1)];
11564 state.merge = Some(crate::run::MergeOutcome {
11565 mode: MergeMode::Pr,
11566 ok: false,
11567 detail: "landing stopped".into(),
11568 empty: false,
11569 });
11570 state.pr = Some(crate::run::PrRecord {
11571 url: "https://example.test/pull/1".into(),
11572 number: 1,
11573 state: "open".into(),
11574 checks: "red".into(),
11575 round: 1,
11576 rounds: 1,
11577 red_at_merge: Vec::new(),
11578 });
11579 state
11580 }
11581
11582 #[test]
11583 fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
11584 for status in [RunStatus::Blocked, RunStatus::Gating] {
11585 let home = tempfile::tempdir().unwrap();
11586 let mut state = stopped_public_run(status);
11587 state.save_under(home.path()).unwrap();
11588 assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
11589 assert!(!exhausted_review_budget(&state));
11590 let mut task = held_task_with(&state.id);
11591 task.release();
11592 let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
11593 assert_eq!(
11594 choose_starter(None, false, unfinished.as_deref()),
11595 Starter::Resume(state.id.clone())
11596 );
11597 let question = action_question(&state.id, resume_action(&state.id));
11598 assert_eq!(
11599 decide_action(&task, &question, &PHRASES_EN, |_| Ok(state.clone())),
11600 ActionDecision::Resume(state.id.clone())
11601 );
11602 assert_eq!(
11604 crate::resume::validate(home.path(), &state.id).unwrap().id,
11605 state.id
11606 );
11607 let queue = Queue::at(home.path().join("queue"));
11608 let mut controlled = Task::new(
11609 "resume land".into(),
11610 state.instruction.clone(),
11611 state.repo.clone(),
11612 Source::Agent {
11613 run: "talk".into(),
11614 node: crate::queue::CHAT_NODE.into(),
11615 },
11616 );
11617 controlled.runs.push(state.id.clone());
11618 controlled.hold_machine(Some("land stopped".into()));
11619 queue.put(&mut controlled).unwrap();
11620 let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
11621 assert_eq!(resumed.status, TaskStatus::Queued);
11622 assert_eq!(
11623 resumed.resume_override.unwrap().pinned_run,
11624 Some(state.id.clone())
11625 );
11626 assert_eq!(resumed.attempts, 0);
11627 }
11628 }
11629
11630 #[test]
11631 fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
11632 for review_rounds in [0, 1] {
11633 let home = tempfile::tempdir().unwrap();
11634 let mut state = run_state(RunStatus::Blocked);
11635 state.config.graph.review_rounds = review_rounds;
11636 if review_rounds > 0 {
11637 let mut review = review_round(1);
11638 review.clean = true;
11639 state.reviews = vec![review];
11640 }
11641 state.gate_ran = true;
11642 state.gate = vec![crate::run::CommandOutcome {
11643 command: "verify".into(),
11644 code: Some(1),
11645 output_tail: "gate failed after repair budget exhausted".into(),
11646 duration_ms: 0,
11647 resource_blocked: false,
11648 }];
11649 state.save_under(home.path()).unwrap();
11650 assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
11651 assert!(exhausted_review_budget(&state));
11652 let mut task = held_task_with(&state.id);
11653 task.release();
11654 assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
11655 let question = action_question(&state.id, resume_action(&state.id));
11656 assert_ne!(
11657 decide_action(&task, &question, &PHRASES_EN, |_| Ok(state.clone())),
11658 ActionDecision::Resume(state.id.clone())
11659 );
11660 let error = crate::resume::validate(home.path(), &state.id)
11661 .unwrap_err()
11662 .to_string();
11663 assert!(!error.contains("review budget exhausted"), "{error}");
11664 assert!(
11665 error.contains(if review_rounds == 0 {
11666 "review is disabled"
11667 } else {
11668 "gate already ran"
11669 }),
11670 "{error}"
11671 );
11672
11673 state.gate_ran = false;
11675 state.gate.clear();
11676 assert!(!exhausted_review_budget(&state));
11677 assert_eq!(
11678 unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
11679 Some(state.id)
11680 );
11681 }
11682 }
11683
11684 #[test]
11685 fn resource_blocked_verification_resumes_the_same_run() {
11686 for (kind, stage) in [
11687 ("cache", "clean"),
11688 ("coordination", "clean"),
11689 ("cache", "review-e2e"),
11690 ("coordination", "no-reviews"),
11691 ("coordination", "handoff"),
11692 ] {
11693 let home = tempfile::tempdir().unwrap();
11694 let mut state = run_state(RunStatus::Blocked);
11695 state.config.graph.review_rounds = 1;
11696 let mut review = review_round(1);
11697 review.clean = true;
11698 state.reviews = vec![review];
11699 if stage == "review-e2e" {
11700 let review = &mut state.reviews[0];
11701 review.clean = false;
11702 review.blocking = 1;
11703 review.e2e = vec![crate::run::CommandOutcome {
11704 command: "verify".into(),
11705 code: None,
11706 output_tail: "resource wait expired".into(),
11707 duration_ms: 0,
11708 resource_blocked: true,
11709 }];
11710 } else if stage == "no-reviews" {
11711 state.config.graph.review_rounds = 0;
11712 state.reviews.clear();
11713 } else if stage == "handoff" {
11714 let review = &mut state.reviews[0];
11717 review.clean = false;
11718 review.blocking = 1;
11719 review.e2e = vec![crate::run::CommandOutcome {
11720 command: "verify".into(),
11721 code: Some(0),
11722 output_tail: String::new(),
11723 duration_ms: 0,
11724 resource_blocked: false,
11725 }];
11726 }
11727 state.gate_ran = false;
11728 state.resource_block = Some(crate::run::ResourceBlock {
11729 cause: crate::run::ResourceBlockCause::Other,
11730 node: if stage == "review-e2e" {
11731 "review"
11732 } else {
11733 "gate"
11734 }
11735 .into(),
11736 kind: kind.into(),
11737 detail: "resource wait expired".into(),
11738 at: jiff::Timestamp::now(),
11739 });
11740 state.save_under(home.path()).unwrap();
11741 assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
11742 assert!(!exhausted_review_budget(&state));
11743 let mut task = held_task_with(&state.id);
11744 task.release();
11745 let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
11746 assert_eq!(
11747 choose_starter(None, false, unfinished.as_deref()),
11748 Starter::Resume(state.id.clone())
11749 );
11750 let question = action_question(&state.id, resume_action(&state.id));
11751 assert_eq!(
11752 decide_action(&task, &question, &PHRASES_EN, |_| Ok(state.clone())),
11753 ActionDecision::Resume(state.id.clone())
11754 );
11755 assert_eq!(
11756 crate::resume::validate(home.path(), &state.id).unwrap().id,
11757 state.id
11758 );
11759 let queue = Queue::at(home.path().join("queue"));
11760 let mut controlled = Task::new(
11761 "resume verification".into(),
11762 state.instruction.clone(),
11763 state.repo.clone(),
11764 Source::Agent {
11765 run: "talk".into(),
11766 node: crate::queue::CHAT_NODE.into(),
11767 },
11768 );
11769 controlled.runs.push(state.id.clone());
11770 controlled.hold_machine(Some("verification resource unavailable".into()));
11771 queue.put(&mut controlled).unwrap();
11772 let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
11773 assert_eq!(resumed.status, TaskStatus::Queued);
11774 assert_eq!(
11775 resumed.resume_override.unwrap().pinned_run,
11776 Some(state.id.clone())
11777 );
11778 assert_eq!(resumed.attempts, 0);
11779
11780 state.config.graph.review_rounds = 1;
11782 let mut unresolved = review_round(1);
11783 unresolved.blocking = 1;
11784 state.reviews = vec![unresolved];
11785 state.resource_block = None;
11786 state.save_under(home.path()).unwrap();
11787 assert!(exhausted_review_budget(&state));
11788 assert!(crate::resume::validate(home.path(), &state.id).is_err());
11789 }
11790 }
11791
11792 #[tokio::test]
11793 async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
11794 if !crate::standalone_test(
11795 "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
11796 ) {
11797 return;
11798 }
11799 let home = tempfile::tempdir().unwrap();
11800 let mut owner = stopped_public_run(RunStatus::Blocked);
11801 owner.save_under(home.path()).unwrap();
11802 let history = vec![owner.id.clone()];
11803 let repo = owner.repo.clone();
11804 let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
11805 let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
11806 let initial =
11807 std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
11808 assert!(
11809 initial.is_pending(),
11810 "a busy record must not hold or resume the task"
11811 );
11812 owner.retired_to = Some("20260101-000001-bbbb".into());
11813 owner.save_under(home.path()).unwrap();
11814 drop(lock);
11815 let result = tokio::time::timeout(Duration::from_secs(10), lookup)
11816 .await
11817 .expect("ownership lock released")
11818 .expect("read settled owner");
11819 assert!(
11820 result.is_none(),
11821 "the retired owner must not be resumed from a stale read"
11822 );
11823 }
11824
11825 #[tokio::test]
11826 async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
11827 if !crate::standalone_test(
11828 "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
11829 ) {
11830 return;
11831 }
11832 let home = tempfile::tempdir().unwrap();
11833 let mut owner = stopped_public_run(RunStatus::Blocked);
11834 let repo = tempfile::tempdir().unwrap();
11835 crate::git::git(repo.path(), &["init"]).await.unwrap();
11836 owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
11837 owner.id = "20260101-000000-aaaa".into();
11838 owner.save_under(home.path()).unwrap();
11839 let mut successor = run_state(RunStatus::Blocked);
11840 successor.id = "20260101-000001-bbbb".into();
11841 successor.save_under(home.path()).unwrap();
11842 let runs = vec![owner.id.clone(), successor.id.clone()];
11843 assert_eq!(
11844 public_resume_owner(home.path(), &runs, &owner.repo)
11845 .await
11846 .unwrap()
11847 .unwrap()
11848 .id,
11849 owner.id
11850 );
11851 let subdir = owner.repo.join("nested");
11852 std::fs::create_dir(&subdir).unwrap();
11853 assert_eq!(
11854 public_resume_owner(home.path(), &runs, &subdir)
11855 .await
11856 .unwrap()
11857 .unwrap()
11858 .id,
11859 owner.id
11860 );
11861 #[cfg(unix)]
11862 {
11863 let alias = home.path().join("repo-alias");
11864 std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
11865 assert_eq!(
11866 public_resume_owner(home.path(), &runs, &alias.join("nested"))
11867 .await
11868 .unwrap()
11869 .unwrap()
11870 .id,
11871 owner.id
11872 );
11873 }
11874 let different = tempfile::tempdir().unwrap();
11875 crate::git::git(different.path(), &["init"]).await.unwrap();
11876 assert!(
11877 public_resume_owner(home.path(), &runs, different.path())
11878 .await
11879 .is_err()
11880 );
11881 std::fs::remove_file(
11882 home.path()
11883 .join("runs")
11884 .join(&successor.id)
11885 .join("run.json"),
11886 )
11887 .unwrap();
11888 assert!(
11889 public_resume_owner(home.path(), &runs, &owner.repo)
11890 .await
11891 .is_err()
11892 );
11893 }
11894
11895 #[test]
11896 fn an_ordinary_release_keeps_a_resumable_run_available() {
11897 let mut released = task();
11898 released.start("stalled-run".to_owned());
11899 released.release();
11900 let unfinished = (!released.fresh_start)
11901 .then(|| Some("stalled-run".to_owned()))
11902 .flatten();
11903 assert_eq!(
11904 choose_starter(None, false, unfinished.as_deref()),
11905 Starter::Resume("stalled-run".to_owned()),
11906 "manual release must preserve the normal resume path"
11907 );
11908 }
11909
11910 #[test]
11911 fn resume_refusals_explain_admission_without_changing_task_or_run() {
11912 crate::run::pin_test_home();
11913 use crate::handover::{ResumeRefusal, resume_refusal_under};
11914 let home = tempfile::tempdir().unwrap();
11915 let mut exhausted = run_state(RunStatus::Blocked);
11916 exhausted.driver_exited = true;
11917 exhausted.config.graph.review_rounds = 3;
11918 exhausted.reviews = (1..=3).map(review_round).collect();
11919 for refusal in [
11920 ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
11921 ResumeRefusal::Status(RunStatus::Ready),
11922 ResumeRefusal::Released("20261022-000000-aaaa".into()),
11923 ResumeRefusal::Retired("retirement-successor".into()),
11924 ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
11925 ] {
11926 let mut state = exhausted.clone();
11927 let expected = match refusal {
11928 ResumeRefusal::Status(_) => {
11929 state.status = RunStatus::Ready;
11930 "status `ready`"
11931 }
11932 ResumeRefusal::Released(ref target) => {
11933 state.released_to = Some(target.clone());
11934 "execution was released"
11935 }
11936 ResumeRefusal::Retired(ref target) => {
11937 state.retired_to = Some(target.clone());
11938 "execution was retired"
11939 }
11940 ResumeRefusal::OwnershipTransferred(ref target) => {
11941 state.pr_taken_over_by = Some(target.clone());
11942 "PR ownership was transferred"
11943 }
11944 _ => "review budget exhausted (3/3 rounds used)",
11945 };
11946 assert_eq!(
11947 resume_refusal_under(&state, Some(home.path())),
11948 Some(refusal.clone())
11949 );
11950 assert_eq!(
11951 refusal.successor(),
11952 state
11953 .released_to
11954 .as_deref()
11955 .or(state.retired_to.as_deref())
11956 .or(state.pr_taken_over_by.as_deref())
11957 );
11958 state.save_under(home.path()).unwrap();
11959 let queue = Queue::at(home.path().join("queue"));
11960 let mut task = Task::new(
11961 "retained implementation".into(),
11962 state.instruction.clone(),
11963 state.repo.clone(),
11964 Source::Agent {
11965 run: "talk".into(),
11966 node: crate::queue::CHAT_NODE.into(),
11967 },
11968 );
11969 task.runs.push(state.id.clone());
11970 task.hold_machine(Some("stopped".into()));
11971 queue.put(&mut task).unwrap();
11972 let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
11973 let before_run = serde_json::to_value(&state).unwrap();
11974 let error = crate::chat_control::resume(&queue, home.path(), &state.id)
11975 .unwrap_err()
11976 .to_string();
11977 assert!(error.contains(expected), "{error}");
11978 assert!(!error.contains("only a stalled or blocked"), "{error}");
11979 if matches!(refusal, ResumeRefusal::Status(_)) {
11980 assert!(
11981 error.contains("is final; there is nothing left to resume"),
11982 "{error}"
11983 );
11984 }
11985 if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
11986 assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
11987 assert!(error.contains("review-only successor with a new review budget"));
11988 assert!(error.contains("does not resume this run"));
11989 }
11990 for target in [
11991 &state.released_to,
11992 &state.retired_to,
11993 &state.pr_taken_over_by,
11994 ]
11995 .into_iter()
11996 .flatten()
11997 {
11998 let short = if state.retired_to.as_ref() == Some(target) {
11999 target.as_str()
12000 } else {
12001 crate::run::short_of(target)
12002 };
12003 assert!(
12004 error.contains(&format!("run {short}; inspect `magi show {short}`")),
12005 "{error}"
12006 );
12007 if short != target {
12008 assert!(!error.contains(target), "full successor id leaked: {error}");
12009 }
12010 }
12011 assert_eq!(
12012 serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
12013 before_task
12014 );
12015 assert_eq!(
12016 serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
12017 .unwrap(),
12018 before_run
12019 );
12020 let question = action_question(&state.id, resume_action(&state.id));
12021 for phrases in [&PHRASES_EN, &PHRASES_JA] {
12022 let ActionDecision::Refuse(detail) =
12023 decide_action(&task, &question, phrases, |_| Ok(state.clone()))
12024 else {
12025 panic!("refusal expected");
12026 };
12027 assert!(detail.contains(expected), "{detail}");
12028 }
12029 }
12030 exhausted.status = RunStatus::Ready;
12032 exhausted.released_to = Some("released".into());
12033 exhausted.retired_to = Some("retired".into());
12034 exhausted.pr_taken_over_by = Some("owner".into());
12035 let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
12036 assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
12037 let detail = reason.diagnostic(&exhausted);
12038 for target in ["released", "retired", "owner"] {
12039 assert!(detail.contains(&format!("magi show {target}")));
12040 }
12041 }
12042
12043 #[test]
12044 fn resume_checkpoint_admission_uses_the_supplied_question_store() {
12045 let home = tempfile::tempdir().unwrap();
12046 let mut state = run_state(RunStatus::Blocked);
12047 state.driver_exited = true;
12048 state.config.graph.review_rounds = 1;
12049 state.reviews = vec![review_round(1)];
12050 assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
12051 for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
12052 let mut saved = state.clone();
12053 match checkpoint {
12054 "publication" => saved.pr_publication_pending = true,
12055 "approval" => {
12056 saved.land_approval = Some(crate::run::LandApproval {
12057 question: "approval".into(),
12058 head: "head".into(),
12059 })
12060 }
12061 "armed" => saved.land_armed_head = Some("head".into()),
12062 "landing" => saved.status = RunStatus::Landing,
12063 _ => {
12064 let mut question = ask::Question::new(
12065 saved.id.clone(),
12066 "review".into(),
12067 "review-1".into(),
12068 "continue?".into(),
12069 String::new(),
12070 vec!["continue".into()],
12071 );
12072 ask::Questions::at(home.path().join("questions"))
12073 .put(&mut question)
12074 .unwrap();
12075 }
12076 }
12077 saved.save_under(home.path()).unwrap();
12078 assert!(
12079 crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
12080 "{checkpoint}"
12081 );
12082 assert!(
12083 crate::resume::validate(home.path(), &saved.id).is_ok(),
12084 "{checkpoint}"
12085 );
12086 }
12087 }
12088
12089 #[test]
12090 fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
12091 let mut state = run_state(RunStatus::Blocked);
12092 state.config.graph.review_rounds = 3;
12093 state.reviews = vec![review_round(1), review_round(2), review_round(3)];
12094 assert!(exhausted_review_budget(&state));
12095
12096 state.reviews.pop();
12098 assert!(!exhausted_review_budget(&state));
12099
12100 let mut stalled = run_state(RunStatus::Stalled);
12103 stalled.config.graph.review_rounds = 1;
12104 stalled.reviews = vec![review_round(1)];
12105 assert!(!exhausted_review_budget(&stalled));
12106 }
12107
12108 fn review_round(round: usize) -> crate::run::ReviewRound {
12109 crate::run::ReviewRound {
12110 round,
12111 head: "deadbeef".to_owned(),
12112 verified_head: None,
12113 verified_at: None,
12114 reviews: Vec::new(),
12115 e2e: Vec::new(),
12116 verify_retried: false,
12117 e2e_deferred: false,
12118 e2e_defer_reason: None,
12119 fix: None,
12120 blocking: 0,
12121 answered: 1,
12122 expected: 1,
12123 clean: false,
12124 progressed: true,
12125 vote_split: false,
12126 reconsideration: Vec::new(),
12127 verdict: None,
12128 }
12129 }
12130
12131 #[test]
12132 fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
12133 let mut run = RunState::new(
12134 PathBuf::from("/repo"),
12135 "main".to_owned(),
12136 "abc1234def".to_owned(),
12137 "add retries".to_owned(),
12138 Config::default(),
12139 );
12140 run.status = RunStatus::Judging;
12141 run.parked = true;
12142 let mut task = Task::new(
12143 "add retries".to_owned(),
12144 "add retries".to_owned(),
12145 PathBuf::from("/repo"),
12146 crate::queue::Source::Human,
12147 );
12148 task.status = TaskStatus::Failed;
12149 task.runs = vec![run.id.clone()];
12150 let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
12151 assert!(with(&task, &run), "parked after judging is the case");
12152 let mut parked_task = task.clone();
12153 parked_task.status = TaskStatus::Parked;
12154 assert!(with(&parked_task, &run), "the Parked status is the case");
12155
12156 let mut not_parked = run.clone();
12157 not_parked.parked = false;
12158 not_parked.status = RunStatus::Stalled;
12159 assert!(!with(&task, ¬_parked), "a stall is the conductor's");
12160
12161 let mut fresh = task.clone();
12162 fresh.fresh_start = true;
12163 assert!(!with(&fresh, &run), "a requeue asked for a new competition");
12164
12165 let mut review = task.clone();
12166 review.review_branch = Some("magi/x/A".to_owned());
12167 assert!(!with(&review, &run), "review is ranked before resume");
12168
12169 let mut held = task.clone();
12170 held.status = TaskStatus::Held;
12171 assert!(!with(&held, &run), "a hold stays visible to the conductor");
12172
12173 let mut released = run.clone();
12174 released.released_to = Some("20260901-000000-new1".to_owned());
12175 assert!(!with(&task, &released), "nothing left to resume into");
12176
12177 assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
12178 "unreadable"
12179 )));
12180 }
12181
12182 #[test]
12183 fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
12184 let mut released = RunState::new(
12185 PathBuf::from("/repo"),
12186 "main".to_owned(),
12187 "abc1234def".to_owned(),
12188 "add retries".to_owned(),
12189 Config::default(),
12190 );
12191 released.status = RunStatus::Blocked;
12192 assert_eq!(
12193 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
12194 Some(released.id.clone())
12195 );
12196 released.released_to = Some("20260901-000000-new1".to_owned());
12197 assert_eq!(
12198 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
12199 None,
12200 "there is nothing left to resume it into"
12201 );
12202 }
12203
12204 #[test]
12205 fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
12206 let mut exhausted = RunState::new(
12215 PathBuf::from("/repo"),
12216 "main".to_owned(),
12217 "abc1234def".to_owned(),
12218 "add retries".to_owned(),
12219 Config::default(),
12220 );
12221 exhausted.status = RunStatus::Blocked;
12222 exhausted.config.graph.review_rounds = 1;
12223 exhausted.reviews = vec![review_round(1)];
12224
12225 assert_eq!(
12226 unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
12227 None,
12228 "an exhausted `Blocked` run must not be offered as resumable"
12229 );
12230
12231 let mut has_budget_left = RunState::new(
12234 PathBuf::from("/repo"),
12235 "main".to_owned(),
12236 "abc1234def".to_owned(),
12237 "add retries".to_owned(),
12238 Config::default(),
12239 );
12240 has_budget_left.status = RunStatus::Blocked;
12241 has_budget_left.config.graph.review_rounds = 3;
12242 has_budget_left.reviews = vec![review_round(1)];
12243
12244 assert_eq!(
12245 unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
12246 Ok(has_budget_left.clone())
12247 }),
12248 Some(has_budget_left.id.clone())
12249 );
12250 }
12251
12252 #[test]
12253 fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
12254 let mut run = RunState::new(
12255 PathBuf::from("/repo"),
12256 "main".to_owned(),
12257 "abc1234def".to_owned(),
12258 "add retries".to_owned(),
12259 Config::default(),
12260 );
12261 run.status = RunStatus::Blocked;
12262 run.config.graph.review_rounds = 1;
12263 run.reviews = vec![review_round(1)];
12264 run.pr_publication_pending = true;
12265 assert_eq!(
12266 unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
12267 Some(run.id.clone()),
12268 "a spent review budget must not turn a failed publication into a re-competition"
12269 );
12270 }
12271
12272 #[test]
12273 fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
12274 let mut task = Task::new(
12275 "recover work".into(),
12276 "recover work".into(),
12277 PathBuf::from("/repo"),
12278 crate::queue::Source::Human,
12279 );
12280 let mut history = std::collections::BTreeMap::new();
12281 for index in 0..8 {
12282 let mut run = run_state(RunStatus::Blocked);
12283 run.id = format!("20260101-000000-{index:04}");
12284 run.base_commit = format!("upstream-{index}");
12285 if index > 0 {
12287 run.candidates.clear();
12288 }
12289 task.runs.extend([run.id.clone(), run.id.clone()]);
12290 history.insert(run.id.clone(), run);
12291 task.requeue();
12292 }
12293 let check = |task: &Task, starter: &Starter, limit| {
12294 retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
12295 };
12296 assert!(
12297 check(&task, &Starter::Start, 8)
12298 .unwrap()
12299 .contains("8 unretired")
12300 );
12301 assert!(check(&task, &Starter::Start, 9).is_none());
12302 assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
12303 task.release_operator("owner", None);
12304 assert_eq!(task.attempts, 0);
12305 let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
12306 assert!(check(&restored, &Starter::Start, 8).is_some());
12307 assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
12308 assert!(check(&restored, &Starter::Start, 0).is_none());
12309 }
12310
12311 #[test]
12312 fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
12313 let mut task = Task::new(
12314 "recover work".into(),
12315 "recover work".into(),
12316 PathBuf::from("/repo"),
12317 crate::queue::Source::Human,
12318 );
12319 let mut run = run_state(RunStatus::Superseded);
12320 run.candidates.clear();
12321 task.runs.push(run.id.clone());
12322 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
12323 run.retired_to = Some("authority".into());
12324 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
12325 run.retired_to = None;
12326 run.released_to = Some("authority".into());
12327 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
12328 assert!(
12329 retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
12330 .unwrap()
12331 .contains("Cannot verify")
12332 );
12333 assert!(
12335 retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
12336 panic!("resume must not load historical attempts")
12337 })
12338 .is_none()
12339 );
12340 }
12341
12342 #[test]
12343 fn retired_resume_requires_a_valid_same_repository_authority() {
12344 let mut source = run_state(RunStatus::Blocked);
12345 let mut empty = run_state(RunStatus::Blocked);
12346 empty.retired_to = Some(source.id.clone());
12347 let runs = vec![source.id.clone(), empty.id.clone()];
12348 let resolve = |source: &RunState, empty: &RunState| {
12349 unfinished_run_with(&runs, "fixture", |id| {
12350 if id == source.id {
12351 Ok(source.clone())
12352 } else if id == empty.id {
12353 Ok(empty.clone())
12354 } else {
12355 bail!("unreadable authority")
12356 }
12357 })
12358 };
12359 assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
12360 assert_eq!(
12361 choose_starter(None, false, resolve(&source, &empty).as_deref()),
12362 Starter::Resume(source.id.clone())
12363 );
12364 source.retired_to = Some(empty.id.clone());
12365 assert!(
12366 resolve(&source, &empty).is_none(),
12367 "cycles do not revive obsolete runs"
12368 );
12369 source.retired_to = None;
12370 source.repo = PathBuf::from("/another-repository");
12371 assert!(resolve(&source, &empty).is_none());
12372 source.repo = empty.repo.clone();
12373 source.released_to = Some("later".into());
12374 assert!(resolve(&source, &empty).is_none());
12375 empty.retired_to = Some("unlisted-run".into());
12376 assert!(resolve(&source, &empty).is_none());
12377 }
12378
12379 #[test]
12380 fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
12381 let mut older_stalled = RunState::new(
12389 PathBuf::from("/repo"),
12390 "main".to_owned(),
12391 "abc1234def".to_owned(),
12392 "add retries".to_owned(),
12393 Config::default(),
12394 );
12395 older_stalled.status = RunStatus::Stalled;
12396
12397 let mut newest_exhausted = RunState::new(
12398 PathBuf::from("/repo"),
12399 "main".to_owned(),
12400 "abc1234def".to_owned(),
12401 "add retries".to_owned(),
12402 Config::default(),
12403 );
12404 newest_exhausted.status = RunStatus::Blocked;
12405 newest_exhausted.config.graph.review_rounds = 1;
12406 newest_exhausted.reviews = vec![review_round(1)];
12407
12408 assert_eq!(
12409 unfinished_run_with(
12410 &[older_stalled.id.clone(), newest_exhausted.id.clone()],
12411 "t",
12412 |_| Ok(newest_exhausted.clone())
12413 ),
12414 None,
12415 "the newest run is exhausted, so nothing here is worth resuming - \
12416 least of all the older, already-superseded run"
12417 );
12418 }
12419
12420 #[test]
12421 fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
12422 assert_eq!(
12423 unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
12424 Err(anyhow::anyhow!("fixture is absent"))
12425 }),
12426 None
12427 );
12428 }
12429
12430 fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
12431 let mut q = ask::Question::new(
12432 run.to_owned(),
12433 "implement".to_owned(),
12434 "impl-A".to_owned(),
12435 "continue?".to_owned(),
12436 String::new(),
12437 vec!["resume で続行する".to_owned(), "other".to_owned()],
12438 );
12439 q.actions.insert("resume で続行する".to_owned(), action);
12440 q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
12441 .unwrap();
12442 q
12443 }
12444
12445 fn held_task_with(run: &str) -> Task {
12446 let mut t = task();
12447 t.runs = vec![run.to_owned()];
12448 t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
12449 t
12450 }
12451
12452 fn resume_action(run: &str) -> ask::ChoiceAction {
12453 ask::ChoiceAction::Resume { run: run.into() }
12454 }
12455
12456 #[test]
12457 fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
12458 for parked in [false, true] {
12459 let mut t = task();
12460 t.start("A".into());
12461 t.start("B".into());
12462 assert_eq!(t.runs, vec!["A", "B"]);
12463 t.start("A".into());
12464 let mut resumed = run_state(RunStatus::Blocked);
12465 resumed.id = "A".into();
12466 resumed.parked = parked;
12467 resumed.driver_exited = true;
12468 t.hold_machine(Some("resumed run stopped".into()));
12469 let q = action_question("A", resume_action("A"));
12470 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
12471 assert_eq!(
12472 decide_action(&t, &q, &PHRASES_EN, |id| {
12473 assert_eq!(id, "A");
12474 Ok(resumed.clone())
12475 }),
12476 ActionDecision::Resume("A".into())
12477 );
12478 assert_eq!(
12479 action_standing(&t, &action_question("B", resume_action("B"))),
12480 ActionStanding::Stale
12481 );
12482 t.release_operator("cli", None);
12483 let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
12484 assert_eq!(id, "A");
12485 Ok(resumed.clone())
12486 });
12487 assert_eq!(
12488 choose_starter(None, false, unfinished.as_deref()),
12489 Starter::Resume("A".into())
12490 );
12491 assert_eq!(t.runs, vec!["B", "A"]);
12492 }
12493 }
12494
12495 #[test]
12496 fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
12497 let mut state = crate::land::tests::repair_state(true, true);
12498 state.status = RunStatus::Landing;
12499 state.parked = true;
12500 state.driver_exited = true;
12501 let mut q = ask::Question::new(
12502 state.id.clone(),
12503 land::APPROVAL_NODE.into(),
12504 "land".into(),
12505 "Merge?".into(),
12506 String::new(),
12507 vec![land::APPROVE.into(), land::HOLD.into()],
12508 );
12509 q.id = state.id.clone();
12510 state.land_approval = Some(crate::run::LandApproval {
12511 question: q.id.clone(),
12512 head: "current-head".into(),
12513 });
12514 assert!(land::upgrade_repair_choice(&mut q, &state));
12515 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12516 let mut task = held_task_with(&state.id);
12517 task.status = TaskStatus::Parked;
12518 assert_eq!(
12519 decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
12520 ActionDecision::Resume(state.id.clone())
12521 );
12522 q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
12523 q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
12524 task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
12525 assert_eq!(
12526 decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
12527 ActionDecision::Resume(state.id.clone()),
12528 "a repair answer newer than the manual hold resumes the existing owner"
12529 );
12530 task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
12531 for answered_at in [q.answered_at, None] {
12532 let mut older = q.clone();
12533 older.answered_at = answered_at;
12534 let refused = decide_action(&task, &older, &PHRASES_EN, |_| {
12535 panic!("a later manual hold must prevent dispatch")
12536 });
12537 let ActionDecision::Refuse(reason) = refused else {
12538 panic!("expected an actionable refusal, got {refused:?}");
12539 };
12540 assert!(reason.contains("later operator decision"));
12541 assert!(reason.contains(&format!("magi task release {}", task.id)));
12542 }
12543 task.operator_decided_at = None;
12544 let mut superseded = state.clone();
12545 superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
12546 assert_eq!(
12547 decide_action(&task, &q, &PHRASES_EN, |_| Ok(superseded)),
12548 ActionDecision::Stale
12549 );
12550 for case in 1..4 {
12551 let mut changed = state.clone();
12552 match case {
12553 1 => changed.status = RunStatus::Blocked,
12554 2 => changed.released_to = Some("new-owner".into()),
12555 _ => changed.land_approval.as_mut().unwrap().head.clear(),
12556 }
12557 assert!(matches!(
12558 decide_action(&task, &q, &PHRASES_EN, |_| Ok(changed)),
12559 ActionDecision::Refuse(_)
12560 ));
12561 }
12562 assert!(matches!(
12563 decide_action(&task, &q, &PHRASES_EN, |_| anyhow::bail!("missing owner")),
12564 ActionDecision::Refuse(_)
12565 ));
12566 task.runs.push("replacement".into());
12567 task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
12568 assert_eq!(
12569 decide_action(&task, &q, &PHRASES_EN, |_| panic!(
12570 "old owner must not load"
12571 )),
12572 ActionDecision::Stale
12573 );
12574 }
12575
12576 #[test]
12577 fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
12578 let mut state = crate::land::tests::repair_state(true, true);
12579 state.status = RunStatus::Landing;
12580 state.parked = true;
12581 state.driver_exited = true;
12582 let mut q = ask::Question::new(
12583 state.id.clone(),
12584 land::APPROVAL_NODE.into(),
12585 "land".into(),
12586 "Merge?".into(),
12587 String::new(),
12588 vec![land::APPROVE.into(), land::HOLD.into()],
12589 );
12590 q.id = state.id.clone();
12591 state.land_approval = Some(crate::run::LandApproval {
12592 question: q.id.clone(),
12593 head: "current-head".into(),
12594 });
12595 state.save().unwrap();
12596 land::upgrade_repair_choice(&mut q, &state);
12597 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12598 Questions::open().put(&mut q).unwrap();
12599 let tmp = tempfile::tempdir().unwrap();
12600 let queue = Queue::at(tmp.path().join("queue"));
12601 let mut task = held_task_with(&state.id);
12602 task.status = TaskStatus::Parked;
12603 queue.put(&mut task).unwrap();
12604 let empty = Arc::new(tokio::sync::Semaphore::new(0));
12605 let free = Arc::new(tokio::sync::Semaphore::new(1));
12606 assert!(claim_dispatch(&queue, &task, false, &empty, &free).is_none());
12607 assert!(claim_dispatch(&queue, &task, true, &free, &free).is_none());
12608 let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
12609 assert!(claim.permit.is_some());
12610 assert!(claim_dispatch(&queue, &task, false, &free, &free).is_none());
12611 drop(claim);
12612 Questions::open()
12613 .update(&q.id, |q| {
12614 q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
12615 Ok(())
12616 })
12617 .unwrap();
12618 let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
12619 assert!(claim.permit.is_none());
12620 assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
12621 }
12622
12623 #[test]
12624 fn decide_action_resumes_only_the_latest_resumable_run() {
12625 let t = held_task_with("r1");
12626 let q = action_question("r1", resume_action("r1"));
12627 let load = |s: RunState| move |_: &str| Ok(s);
12628 assert_eq!(
12629 decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Blocked))),
12630 ActionDecision::Resume("r1".into())
12631 );
12632 let q_other = action_question("r1", resume_action("r0"));
12634 assert!(matches!(
12635 decide_action(
12636 &t,
12637 &q_other,
12638 &PHRASES_EN,
12639 load(run_state(RunStatus::Blocked))
12640 ),
12641 ActionDecision::Refuse(_)
12642 ));
12643 assert!(matches!(
12645 decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Ready))),
12646 ActionDecision::Refuse(_)
12647 ));
12648 let mut released = run_state(RunStatus::Blocked);
12650 released.released_to = Some("elsewhere".into());
12651 assert!(matches!(
12652 decide_action(&t, &q, &PHRASES_EN, load(released)),
12653 ActionDecision::Refuse(_)
12654 ));
12655 assert!(matches!(
12657 decide_action(&t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
12658 ActionDecision::Refuse(_)
12659 ));
12660 }
12661
12662 #[test]
12663 fn decide_action_ignores_a_question_about_an_earlier_run() {
12664 let mut t = held_task_with("r1");
12665 t.runs.push("r2".to_owned());
12666 let never = |_: &str| -> Result<RunState> { bail!("not read") };
12667 assert_eq!(
12668 decide_action(
12669 &t,
12670 &action_question("r1", ask::ChoiceAction::Done),
12671 &PHRASES_EN,
12672 never
12673 ),
12674 ActionDecision::Stale
12675 );
12676 }
12677
12678 #[test]
12679 fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
12680 let mut t = held_task_with("r1");
12681 let never = |_: &str| -> Result<RunState> { bail!("not read") };
12682 assert_eq!(
12683 decide_action(
12684 &t,
12685 &action_question("r1", ask::ChoiceAction::Requeue),
12686 &PHRASES_EN,
12687 never
12688 ),
12689 ActionDecision::Requeue
12690 );
12691 let done_q = action_question("r1", ask::ChoiceAction::Done);
12692 assert_eq!(
12693 decide_action(&t, &done_q, &PHRASES_EN, never),
12694 ActionDecision::Done
12695 );
12696 t.mark_action_applied(&done_q.id);
12697 assert_eq!(
12698 decide_action(&t, &done_q, &PHRASES_EN, never),
12699 ActionDecision::Skip
12700 );
12701
12702 let mut plain = action_question("r1", ask::ChoiceAction::Done);
12704 plain.actions.clear();
12705 assert_eq!(
12706 decide_action(&held_task_with("r1"), &plain, &PHRASES_EN, never),
12707 ActionDecision::Skip
12708 );
12709 let mut running = held_task_with("r1");
12711 running.status = TaskStatus::Running;
12712 assert_eq!(
12713 decide_action(
12714 &running,
12715 &action_question("r1", ask::ChoiceAction::Done),
12716 &PHRASES_EN,
12717 never
12718 ),
12719 ActionDecision::Skip
12720 );
12721 }
12722
12723 #[test]
12724 fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
12725 crate::run::pin_test_home();
12726 for legacy in [false, true] {
12727 let dir = tempfile::tempdir().unwrap();
12728 let queue = Queue::at(dir.path().join("queue"));
12729 let questions = Questions::at(dir.path().join("questions"));
12730 let run = "20260101-000000-hold";
12731 let mut task = held_task_with(run);
12732 task.status = TaskStatus::Parked;
12733 let mut q = ask::Question::new(
12734 run.into(),
12735 land::APPROVAL_NODE.into(),
12736 "land".into(),
12737 "Repair?".into(),
12738 String::new(),
12739 vec![land::REPAIR.into()],
12740 );
12741 q.actions.insert(land::REPAIR.into(), resume_action(run));
12742 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12743 q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
12745 q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
12746 questions.put(&mut q).unwrap();
12747 task.hold_manual(Some("Keep this PR paused".into()));
12748 if legacy {
12749 task.hold_source = None;
12750 }
12751 queue.put(&mut task).unwrap();
12752
12753 apply_task_choice_actions(&queue, &questions, dir.path());
12754 let after = queue.get(&task.id).unwrap();
12755 assert!(after.operator_held());
12756 assert_eq!(after.hold_source, task.hold_source);
12757 assert_eq!(after.operator_decided_at, task.operator_decided_at);
12758 assert_eq!(after.runs, task.runs);
12759 assert_eq!(after.instruction, task.instruction);
12760 assert!(after.resume_override.is_none());
12761 assert!(after.action_applied(&q.id));
12762 let reason = after.hold_reason.as_deref().unwrap();
12763 assert!(reason.starts_with("Keep this PR paused"));
12764 assert!(reason.contains("later operator decision"));
12765 assert!(reason.contains(&format!("magi task release {}", task.id)));
12766
12767 for recovery in [
12768 crate::conduct::Recovery::Review,
12769 crate::conduct::Recovery::Requeue,
12770 ] {
12771 crate::conduct::apply(
12772 &queue,
12773 &questions,
12774 &crate::conduct::Verdict {
12775 decisions: vec![crate::conduct::Decision {
12776 id: task.id.clone(),
12777 recovery: Some(recovery),
12778 ..Default::default()
12779 }],
12780 },
12781 )
12782 .unwrap();
12783 }
12784 apply_task_choice_actions(&queue, &questions, dir.path());
12787 let still_held = queue.get(&task.id).unwrap();
12788 assert!(still_held.operator_held());
12789 assert_eq!(still_held.hold_reason, after.hold_reason);
12790 assert_eq!(still_held.runs, task.runs);
12791 assert!(still_held.review_branch.is_none());
12792 assert!(!still_held.fresh_start);
12793 assert!(queue.next_runnable().is_none());
12794 }
12795 }
12796
12797 #[test]
12798 fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
12799 for held in [false, true] {
12800 for retry in [false, true] {
12801 let dir = tempfile::tempdir().unwrap();
12802 let queue = Queue::at(dir.path().join("queue"));
12803 let questions = Questions::at(dir.path().join("questions"));
12804 let home = dir.path().join("home");
12805 let mut t = task();
12806 if held {
12807 t.hold_machine(Some("driver state unknown".into()));
12808 }
12809 queue.put(&mut t).unwrap();
12810 let verdict = serde_json::from_value(serde_json::json!({
12811 "decisions": [{
12812 "id": t.id,
12813 "question": "Driver state unknown; retry the checks or hold?",
12814 "choices": ["daemon: recheck and retry", "daemon: hold the task"],
12815 "actions": {
12816 "daemon: recheck and retry": {"do": "requeue"},
12817 "daemon: hold the task": {"do": "hold"}
12818 }
12819 }]
12820 }))
12821 .unwrap();
12822 crate::conduct::apply(&queue, &questions, &verdict).unwrap();
12823 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
12824 let mut q = questions.list().pop().unwrap();
12825 let choice = if retry {
12826 "daemon: recheck and retry"
12827 } else {
12828 "daemon: hold the task"
12829 };
12830 assert_eq!(q.actions.len(), 2);
12831 q.answer(ask::Answer::Choice(choice.into())).unwrap();
12832 questions.put(&mut q).unwrap();
12833
12834 questions.beat(&q.id, ask::WaiterKind::Deputy);
12836 for _ in 0..2 {
12837 resolve_blockers(&queue, &questions);
12838 apply_task_choice_actions(&queue, &questions, &home);
12839 let waiting = queue.get(&t.id).unwrap();
12840 assert_eq!(waiting.status, TaskStatus::Blocked);
12841 assert_eq!(waiting.blocked_by, [q.id.clone()]);
12842 assert!(waiting.answers.is_empty());
12843 assert!(!waiting.action_applied(&q.id));
12844 assert!(runnable(&queue).is_empty());
12845 let free = Arc::new(tokio::sync::Semaphore::new(1));
12846 assert!(claim_dispatch(&queue, &t, false, &free, &free).is_none());
12847 }
12848 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
12849
12850 resolve_blockers(&queue, &questions);
12852 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
12853 apply_task_choice_actions(&queue, &questions, &home);
12854 let after = queue.get(&t.id).unwrap();
12855 assert_eq!(
12856 after.status,
12857 if retry {
12858 TaskStatus::Queued
12859 } else {
12860 TaskStatus::Held
12861 }
12862 );
12863 assert!(after.action_applied(&q.id));
12864 assert_eq!(after.operator_held(), !retry);
12865 assert_eq!(after.answers.len(), 1);
12866
12867 let mut changed = after;
12869 if retry {
12870 changed.hold_manual(Some("later hold".into()));
12871 } else {
12872 changed.release_operator("test", None);
12873 }
12874 let expected = changed.status;
12875 queue.put(&mut changed).unwrap();
12876 apply_task_choice_actions(&queue, &questions, &home);
12877 assert_eq!(queue.get(&t.id).unwrap().status, expected);
12878 }
12879 }
12880 }
12881
12882 #[test]
12883 fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
12884 let dir = tempfile::tempdir().unwrap();
12885 let queue = Queue::at(dir.path().join("queue"));
12886 let questions = Questions::at(dir.path().join("questions"));
12887 let home = dir.path().join("home");
12888 let mut state = run_state(RunStatus::Blocked);
12889 state.id = "20260101-000000-act1".to_owned();
12890 state.save_under(&home).unwrap();
12891
12892 let mut t = held_task_with(&state.id);
12893 queue.put(&mut t).unwrap();
12894 let mut q = action_question(&state.id, resume_action(&state.id));
12895 questions.put(&mut q).unwrap();
12896
12897 apply_task_choice_actions(&queue, &questions, &home);
12898 let after = queue.get(&t.id).unwrap();
12899 assert_eq!(after.status, TaskStatus::Queued);
12900 assert!(!after.fresh_start);
12901 assert!(after.action_applied(&q.id));
12902 let pin = after.resume_override.clone().unwrap();
12903 assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
12904 assert!(pin.forced);
12905
12906 let mut again = queue.get(&t.id).unwrap();
12908 again.hold_machine(Some("later".into()));
12909 queue.put(&mut again).unwrap();
12910 apply_task_choice_actions(&queue, &questions, &home);
12911 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12912 }
12913
12914 #[test]
12915 fn a_delivered_answer_is_still_acted_on_exactly_once() {
12916 let dir = tempfile::tempdir().unwrap();
12917 let queue = Queue::at(dir.path().join("queue"));
12918 let questions = Questions::at(dir.path().join("questions"));
12919 let home = dir.path().join("home");
12920 let mut state = run_state(RunStatus::Blocked);
12921 state.id = "20260101-000000-act2".to_owned();
12922 state.save_under(&home).unwrap();
12923
12924 let mut t = held_task_with(&state.id);
12925 queue.put(&mut t).unwrap();
12926 let mut q = action_question(&state.id, resume_action(&state.id));
12927 q.answer_delivered = true;
12928 questions.put(&mut q).unwrap();
12929
12930 apply_task_choice_actions(&queue, &questions, &home);
12933 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
12934 assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
12935
12936 let mut again = queue.get(&t.id).unwrap();
12938 again.hold_machine(Some("later".into()));
12939 queue.put(&mut again).unwrap();
12940 apply_task_choice_actions(&queue, &questions, &home);
12941 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12942 }
12943
12944 #[test]
12945 fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
12946 let dir = tempfile::tempdir().unwrap();
12947 let queue = Queue::at(dir.path().join("queue"));
12948 let questions = Questions::at(dir.path().join("questions"));
12949 let home = dir.path().join("home");
12950 let mut state = run_state(RunStatus::Blocked);
12951 state.id = "20260101-000000-act3".to_owned();
12952 state.save_under(&home).unwrap();
12953 let mut t = held_task_with(&state.id);
12954 queue.put(&mut t).unwrap();
12955 let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
12956 questions.put(&mut q).unwrap();
12957
12958 questions.beat(&q.id, crate::ask::WaiterKind::Asker);
12959 apply_task_choice_actions(&queue, &questions, &home);
12960 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12961
12962 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
12963 apply_task_choice_actions(&queue, &questions, &home);
12964 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
12965 }
12966
12967 #[test]
12968 fn action_standing_tells_the_reasons_apart() {
12969 let mut t = held_task_with("r1");
12970 let q = action_question("r1", ask::ChoiceAction::Requeue);
12971 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
12972 let mut plain = q.clone();
12973 plain.actions.clear();
12974 assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
12975
12976 t.mark_action_applied(&q.id);
12978 assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
12979
12980 let mut t = held_task_with("r1");
12982 t.start("r2".to_owned());
12983 assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
12984 let q2 = action_question("r2", ask::ChoiceAction::Requeue);
12986 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
12987 t.status = TaskStatus::Blocked;
12988 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
12989
12990 let mut c = action_question("r0", ask::ChoiceAction::Requeue);
12992 c.node = crate::conduct::NODE.to_owned();
12993 assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
12994 assert!(!ActionStanding::Busy.daemon_owns());
12995 }
12996
12997 #[test]
12998 fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
12999 let dir = tempfile::tempdir().unwrap();
13000 let queue = Queue::at(dir.path().join("queue"));
13001 let questions = Questions::at(dir.path().join("questions"));
13002 let home = dir.path().join("home");
13003 let mut state = run_state(RunStatus::Blocked);
13004 state.id = "20260101-000000-act4".to_owned();
13005 state.save_under(&home).unwrap();
13006 let mut t = held_task_with(&state.id);
13007 t.status = TaskStatus::Running;
13008 queue.put(&mut t).unwrap();
13009 let mut q = action_question(&state.id, ask::ChoiceAction::Done);
13010 q.cwd = Some(dir.path().display().to_string());
13011 questions.put(&mut q).unwrap();
13012
13013 let running = queue.get(&t.id).unwrap();
13016 assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
13017 assert!(matches!(
13018 crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
13019 crate::waiter::Action::Deliver(_)
13020 ));
13021 apply_task_choice_actions(&queue, &questions, &home);
13023 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
13024 let mut back = queue.get(&t.id).unwrap();
13025 back.hold_machine(Some("later".into()));
13026 queue.put(&mut back).unwrap();
13027 apply_task_choice_actions(&queue, &questions, &home);
13028 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
13029 let mut again = queue.get(&t.id).unwrap();
13030 again.hold_machine(Some("again".into()));
13031 queue.put(&mut again).unwrap();
13032 apply_task_choice_actions(&queue, &questions, &home);
13033 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13034 }
13035}