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(last) = state.events.last() {
6079 let unanswered = state
6083 .reviews
6084 .last()
6085 .filter(|r| {
6086 state.status == RunStatus::Blocked
6087 && last.node == "review"
6088 && r.incomplete()
6089 && r.blocking == 0
6090 && r.round == state.config.graph.review_rounds
6091 && r.e2e.iter().all(crate::run::CommandOutcome::ok)
6092 })
6093 .map(|r| (r.expected - r.answered, r.round));
6094 match unanswered {
6095 Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
6096 detail.push_str(&format!(
6097 " ({}: {})",
6098 last.node,
6099 (p.reviewers_never_answered)(missing, rounds)
6100 ));
6101 }
6102 _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
6103 }
6104 }
6105 detail.push_str(&format!(" [run {}]", state.id));
6106 detail
6107}
6108
6109const DIAGNOSTIC_MAX: usize = 4_000;
6115
6116const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
6121
6122fn diagnostic(state: &RunState) -> Option<String> {
6136 let mut parts: Vec<String> = Vec::new();
6137
6138 for o in state.gate.iter().filter(|o| !o.ok()) {
6140 parts.push(format!(
6141 "gate `{}` failed ({}):\n{}",
6142 o.command,
6143 notices::exit_status(o.code),
6144 crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
6145 ));
6146 }
6147
6148 if let Some(last) = state
6151 .events
6152 .iter()
6153 .rev()
6154 .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
6155 {
6156 parts.push(last.message.clone());
6157 }
6158
6159 if state.viable().is_empty() {
6166 for c in &state.candidates {
6167 if let Some(evidence) = &c.verified_noop {
6168 parts.push(format!(
6169 "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
6170 c.label
6171 ));
6172 } else if !c.summary.trim().is_empty() {
6173 parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
6174 } else if let Some(why) = &c.failed {
6175 parts.push(format!("candidate {}: {why}", c.label));
6176 }
6177 }
6178 }
6179
6180 if parts.is_empty() {
6181 return None;
6182 }
6183 Some(crate::run::tail(
6188 &parts.join("\n\n"),
6189 DIAGNOSTIC_MAX.saturating_sub(100),
6190 ))
6191}
6192
6193fn label(status: RunStatus) -> &'static str {
6201 status.as_str()
6202}
6203
6204pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
6206 match mode {
6207 "none" => Ok(MergeMode::None),
6208 "local" => Ok(MergeMode::Local),
6209 "pr" => Ok(MergeMode::Pr),
6210 other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
6211 }
6212}
6213
6214fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
6219 mutex
6220 .lock()
6221 .unwrap_or_else(std::sync::PoisonError::into_inner)
6222}
6223
6224#[cfg(test)]
6225mod tests {
6226 use super::*;
6227 use crate::queue::{Source, TaskStatus};
6228 use crate::run::{Candidate, CommandOutcome};
6229 use pretty_assertions::assert_eq;
6230
6231 fn task() -> Task {
6232 Task::new(
6233 "add retries".to_owned(),
6234 "add retries".to_owned(),
6235 PathBuf::from("/repo"),
6236 Source::Human,
6237 )
6238 }
6239
6240 fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
6241 let job = crate::worker::Job {
6242 id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
6243 sequence: 1,
6244 kind: "task".into(),
6245 key: format!("task:{}", request.task),
6246 payload: serde_json::to_value(request).unwrap(),
6247 generation: "a".repeat(64),
6248 version: None,
6249 status: crate::worker::Status::Starting,
6250 result: None,
6251 pid: None,
6252 created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
6253 finished_at: None,
6254 };
6255 let dir = home.join("workers/jobs").join(&job.id);
6256 std::fs::create_dir_all(&dir).unwrap();
6257 std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
6258 job
6259 }
6260
6261 #[test]
6262 fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
6263 let home = tempfile::tempdir().unwrap();
6264 let request = TaskWorker {
6265 opts: Opts::default(),
6266 queue: home.path().join("queue"),
6267 task: "startup".into(),
6268 lane: PermitKind::Ordinary,
6269 standalone: false,
6270 };
6271 let job = starting_task_reservation(home.path(), &request);
6272 let error = task_worker_spawn_error(
6273 home.path(),
6274 &request,
6275 anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
6276 )
6277 .expect_err("our own reservation must not turn a failed spawn into a resync");
6278 let active = crate::worker::active(home.path()).unwrap();
6279 assert_eq!(active.len(), 1);
6280 assert_eq!(active[0].id, job.id);
6281 assert_eq!(active[0].status, crate::worker::Status::Starting);
6282 assert!(
6283 crate::worker::control(home.path(), &job.key)
6284 .unwrap()
6285 .is_none()
6286 );
6287 let notices = notices::Notices::at(home.path().join("notifications")).list();
6288 assert_eq!(notices.len(), 1);
6289 assert_eq!(notices[0].key, "loop:worker-startup");
6290 assert!(!notices[0].message.contains("private-error-detail"));
6291 assert!(notices[0].message.contains(&request.task));
6292 assert!(
6293 notices[0]
6294 .message
6295 .contains("could not be started or acknowledged")
6296 );
6297 assert!(notices[0].message.contains("worker.log"));
6298 assert_eq!(
6299 notices[0].link,
6300 Some(Link::Task {
6301 id: request.task.clone()
6302 })
6303 );
6304 assert!(format!("{error:#}").contains("private-error-detail"));
6305 }
6306
6307 #[test]
6308 fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
6309 let home = tempfile::tempdir().unwrap();
6310 let mut request = TaskWorker {
6311 opts: Opts::default(),
6312 queue: home.path().join("queue"),
6313 task: "handoff".into(),
6314 lane: PermitKind::Ordinary,
6315 standalone: true,
6316 };
6317 let job = starting_task_reservation(home.path(), &request);
6318 request.standalone = false;
6319 task_worker_spawn_error(
6320 home.path(),
6321 &request,
6322 anyhow::anyhow!("operation key is already reserved for a different request"),
6323 )
6324 .expect("a different standalone request is the handoff race, not our startup failure");
6325 let active = crate::worker::active(home.path()).unwrap();
6326 assert_eq!(active.len(), 1);
6327 assert_eq!(active[0].id, job.id);
6328 assert_eq!(active[0].payload, job.payload);
6329 assert!(
6330 notices::Notices::at(home.path().join("notifications"))
6331 .list()
6332 .is_empty()
6333 );
6334 }
6335
6336 #[test]
6337 fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
6338 let home = tempfile::tempdir().unwrap();
6339 let queue = Queue::at(home.path().join("queue"));
6340 let mut task = task();
6341 task.runs = vec!["previous".into()];
6342 queue.put(&mut task).unwrap();
6343 let request = TaskWorker {
6344 opts: Opts::default(),
6345 queue: home.path().join("queue"),
6346 task: task.id.clone(),
6347 lane: PermitKind::Ordinary,
6348 standalone: false,
6349 };
6350 let job = starting_task_reservation(home.path(), &request);
6351 let claims = current_work(home.path(), Timestamp::now());
6352 assert_eq!(claims.len(), 1);
6353 assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
6354 assert_eq!(claims[0].run, "previous");
6355 assert!(other_claims_run(&claims, "previous", None));
6356 assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
6359 assert!(is_working_on(home.path(), "previous", Timestamp::now()));
6360 }
6361
6362 #[test]
6363 fn admission_excludes_only_the_callers_exact_reservation() {
6364 let own = Current {
6365 worker: Some("own".into()),
6366 task: "same-task".into(),
6367 run: "previous".into(),
6368 };
6369 assert!(!other_claims_run(
6370 std::slice::from_ref(&own),
6371 "previous",
6372 Some("own")
6373 ));
6374 assert!(other_claims_run(
6375 std::slice::from_ref(&own),
6376 "previous",
6377 None
6378 ));
6379 for worker in [None, Some("other".into())] {
6380 let other = Current {
6381 worker,
6382 ..own.clone()
6383 };
6384 assert!(other_claims_run(
6385 &[own.clone(), other],
6386 "previous",
6387 Some("own")
6388 ));
6389 }
6390 let legacy: Current =
6391 serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
6392 assert!(other_claims_run(&[legacy], "previous", Some("own")));
6393 }
6394
6395 #[test]
6396 fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
6397 let mut task = task();
6398 let mut run = run_state(RunStatus::Reviewing);
6399 run.task_instruction = Some(task.instruction.clone());
6400 run.reviewed_commits = Some(vec!["committed-fix".into()]);
6401 let branch = "magi/test/B";
6402 run.candidates.push(crate::run::Candidate {
6403 branch: branch.into(),
6404 ..candidate('B', "preserved work", false, None)
6405 });
6406 task.runs = vec![run.id.clone()];
6407 let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
6408 assert_eq!(
6409 review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
6410 Starter::Resume(run.id.clone())
6411 );
6412 assert!(matches!(
6413 review_retry_starter(
6414 &task,
6415 Some(&run),
6416 Some("different"),
6417 true,
6418 unfinished.as_deref()
6419 ),
6420 Starter::Review(_)
6421 ));
6422 assert_eq!(
6423 review_retry_starter(
6424 &task,
6425 Some(&run),
6426 Some(branch),
6427 false,
6428 unfinished.as_deref()
6429 ),
6430 Starter::Start
6431 );
6432 task.instruction.push_str(" changed criteria");
6433 assert!(matches!(
6434 review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
6435 Starter::Review(_)
6436 ));
6437 assert!(matches!(
6438 review_retry_starter(&task, Some(&run), Some(branch), true, None),
6439 Starter::Review(_)
6440 ));
6441 }
6442
6443 #[test]
6444 fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
6445 let dir = tempfile::tempdir().unwrap();
6446 let queue = Queue::at(dir.path().join("queue"));
6447 let mut task = task();
6448 task.status = TaskStatus::Running;
6449 task.attempts = 1;
6450 queue.put(&mut task).unwrap();
6451 let live = std::collections::BTreeSet::from([task.id.clone()]);
6452 assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
6453 drop(queue.claim(&task.id).unwrap());
6454 let saved = queue.get(&task.id).unwrap();
6455 assert_eq!(saved.status, TaskStatus::Running);
6456 assert_eq!(saved.attempts, 1);
6457 assert!(saved.last_error.is_none());
6458 }
6459
6460 #[test]
6461 fn standalone_workers_do_not_consume_scheduler_lanes() {
6462 let request = |task: &str, lane, standalone| TaskWorker {
6463 opts: Opts::default(),
6464 queue: PathBuf::from("/queue"),
6465 task: task.to_owned(),
6466 lane,
6467 standalone,
6468 };
6469 let mut jobs = vec![
6470 request("ordinary", PermitKind::Ordinary, false),
6471 request("standalone-urgent", PermitKind::Urgent, true),
6472 request("standalone-ordinary", PermitKind::Ordinary, true),
6473 request("decision", PermitKind::None, false),
6474 ];
6475 assert_eq!(available_slots(&jobs, 2), (1, 1));
6476 jobs.push(request("urgent", PermitKind::Urgent, false));
6477 assert_eq!(available_slots(&jobs, 2), (1, 0));
6478 assert_eq!(available_slots(&jobs, 0), (0, 0));
6479 }
6480
6481 #[test]
6482 fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
6483 let now = Timestamp::now();
6484 let mut reading = Reading {
6485 pid: Some(std::process::id()),
6486 updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
6487 ..Reading::default()
6488 };
6489 assert!(!reading.running(now));
6490 assert!(legacy_scheduler_running(&reading, now, 0));
6491 reading.worker_protocol = Some(1);
6492 assert!(!legacy_scheduler_running(&reading, now, 0));
6493 }
6494
6495 #[test]
6496 fn selected_public_head_overrides_historical_resume_and_pin() {
6497 let mut t = task();
6498 let mut old = run_state(RunStatus::Blocked);
6499 let selection = crate::pr_recovery::Selection {
6500 url: "url".into(),
6501 branch: format!("magi/task-{}", t.id),
6502 head: "a".repeat(40),
6503 source_head: None,
6504 source_run: None,
6505 source_proof: None,
6506 disposition: Some(crate::pr_recovery::Disposition::Review),
6507 instruction: t.instruction.clone(),
6508 approved_at: Timestamp::now(),
6509 };
6510 t.resume_override = Some(crate::queue::OperatorResume {
6511 pinned_run: Some(old.id.clone()),
6512 question_id: "choice".into(),
6513 at: Timestamp::now(),
6514 conductor_rehold: None,
6515 forced: false,
6516 });
6517 assert_eq!(
6518 selected_starter(&selection, Some(&old), Some(&old.id)),
6519 Starter::Review(selection.branch.clone())
6520 );
6521 old.pr_recovery = Some(selection.clone());
6522 assert_eq!(
6523 selected_starter(&selection, Some(&old), Some(&old.id)),
6524 Starter::Review(selection.branch.clone())
6525 );
6526 old.reviewed_commits = Some(vec!["implementation".into()]);
6527 assert_eq!(
6528 selected_starter(&selection, Some(&old), Some(&old.id)),
6529 Starter::Resume(old.id.clone())
6530 );
6531 let mut changed = selection.clone();
6532 changed.head = "b".repeat(40);
6533 assert_eq!(
6534 selected_starter(&changed, Some(&old), Some(&old.id)),
6535 Starter::Review(changed.branch)
6536 );
6537 }
6538
6539 #[test]
6540 fn candidate_transplant_failure_is_one_actionable_hold() {
6541 let dir = tempfile::tempdir().unwrap();
6542 let q = Queue::at(dir.path().join("queue"));
6543 let mut t = task();
6544 let mut state = run_state(RunStatus::Blocked);
6545 state.event("prep", "cannot apply referenced commit: conflict");
6546 state.prep_failure = Some("conflict".into());
6547 t.start(state.id.clone());
6548 finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
6549 assert_eq!(t.attempts, 1);
6550 assert_eq!(t.status, TaskStatus::Held);
6551 assert!(t.operator_held());
6552 assert!(!t.status.runnable());
6553 assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
6554 let first = t.chat_notice_key().unwrap();
6555 t.chat_notices.push(first.clone());
6556 t.release_operator("test", None);
6557 state.id = "another-unprepared-run".into();
6558 t.start(state.id.clone());
6559 finish_attempt(
6560 3,
6561 &q,
6562 &mut t,
6563 &state,
6564 &[],
6565 Err(anyhow::anyhow!("still conflicts")),
6566 );
6567 assert_eq!(
6568 t.chat_notice_key().as_ref(),
6569 Some(&first),
6570 "no work happened"
6571 );
6572 t.release_operator("test", None);
6573 state.prep_failure = None;
6574 state.status = RunStatus::Failed;
6575 state.begin_pass();
6576 t.start(state.id.clone());
6577 finish_attempt(
6578 1,
6579 &q,
6580 &mut t,
6581 &state,
6582 &[],
6583 Err(anyhow::anyhow!("new gate failure")),
6584 );
6585 let failure = t.chat_notice_key().unwrap();
6586 assert_ne!(failure, first, "approved recovery reached a real failure");
6587 t.release_operator("test", None);
6588 state.begin_pass();
6589 t.start(state.id.clone());
6590 finish_attempt(
6591 1,
6592 &q,
6593 &mut t,
6594 &state,
6595 &[],
6596 Err(anyhow::anyhow!("new failure on resume")),
6597 );
6598 assert_ne!(
6599 t.chat_notice_key().as_ref(),
6600 Some(&failure),
6601 "a new settled pass"
6602 );
6603 }
6604
6605 #[test]
6606 fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
6607 for source in ["cli", "web"] {
6608 let mut t = task();
6609 let mut run = run_state(RunStatus::Blocked);
6610 run.instruction = "Run A original criteria".into();
6611 run.task_instruction = Some(run.instruction.clone());
6612 t.start(run.id.clone());
6613 t.release_operator("choice", Some("resume-question"));
6614 t.resume_override = Some(crate::queue::OperatorResume {
6615 question_id: "resume-question".into(),
6616 at: Timestamp::now(),
6617 conductor_rehold: None,
6618 forced: true,
6619 pinned_run: Some(run.id.clone()),
6620 });
6621 t.hold_machine(Some("not enough free space to start a run".into()));
6622 let mut unchanged = t.clone();
6623 unchanged
6624 .edit("title changed".into(), unchanged.instruction.clone())
6625 .unwrap();
6626 unchanged.release_operator(source, None);
6627 assert_eq!(
6628 unchanged
6629 .resume_override
6630 .as_ref()
6631 .unwrap()
6632 .pinned_run
6633 .as_deref(),
6634 Some(run.id.as_str())
6635 );
6636 assert!(!compatible_run_instruction(&run, &unchanged));
6637 assert!(may_resume_run(&run, &unchanged));
6638
6639 t.edit(
6640 "approved recovery".into(),
6641 "Reuse measured PR head B; fix Clippy; review".into(),
6642 )
6643 .unwrap();
6644 assert!(t.resume_override.is_none());
6645 t.release_operator(source, None);
6646 let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
6647 assert!(reloaded.resume_override.is_none());
6648 assert!(!may_resume_run(&run, &reloaded));
6649 let unfinished =
6650 unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
6651 .filter(|_| may_resume_run(&run, &reloaded));
6652 assert_eq!(
6653 choose_starter(None, false, unfinished.as_deref()),
6654 Starter::Start
6655 );
6656 assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
6657 assert_eq!(
6658 reloaded.resumption_history[0].question_id.as_deref(),
6659 Some("resume-question")
6660 );
6661
6662 unchanged.instruction = "Reuse measured PR head B".into();
6665 unchanged.hold_machine(Some("disk hold".into()));
6666 unchanged.release_operator(source, None);
6667 assert!(unchanged.resume_override.is_none());
6668 assert!(!may_resume_run(&run, &unchanged));
6669 }
6670 }
6671
6672 #[test]
6673 fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
6674 let mut t = task();
6675 let mut run = run_state(RunStatus::Blocked);
6676 t.review_of = Some("approved-head".into());
6677 t.instruction =
6678 "Review the branch `approved-head` (review-only: no implementation, no judging)."
6679 .into();
6680 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();
6681 run.reviewed_commits = Some(vec!["Commit log".into()]);
6682 t.start(run.id.clone());
6683 t.hold_machine(Some("interrupted review".into()));
6684 t.release_operator("cli", None);
6685 assert!(
6686 compatible_run_instruction(&run, &t),
6687 "legacy explicit review remains resumable"
6688 );
6689 let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
6690 .filter(|_| compatible_run_instruction(&run, &t));
6691 assert_eq!(
6692 choose_starter(None, false, unfinished.as_deref()),
6693 Starter::Resume(run.id.clone())
6694 );
6695 run.task_instruction = Some(t.instruction.clone());
6696 assert!(compatible_run_instruction(&run, &t));
6697 let reloaded: RunState =
6698 serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
6699 assert!(compatible_run_instruction(&reloaded, &t));
6700 t.edit(
6701 "new approved head".into(),
6702 "Reuse measured PR head B".into(),
6703 )
6704 .unwrap();
6705 assert!(!compatible_run_instruction(&run, &t));
6706
6707 t.review_of = None;
6709 t.instruction = "Fix Clippy on approved head".into();
6710 run.task_instruction = None;
6711 run.instruction = format!(
6712 "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
6713 t.instruction
6714 );
6715 assert!(compatible_run_instruction(&run, &t));
6716 t.instruction.push('\n');
6717 assert!(
6718 compatible_run_instruction(&run, &t),
6719 "legacy generated review trimmed the original criteria"
6720 );
6721 t.hold_for_handover(Some("approved-head".into()), "refused".into());
6722 let mut unchanged = t.clone();
6723 assert_eq!(
6724 take_review_branch(&mut unchanged, Some(&run)).as_deref(),
6725 Some("approved-head")
6726 );
6727 t.edit("new plan".into(), "Reuse measured PR head B".into())
6728 .unwrap();
6729 assert!(take_review_branch(&mut t, Some(&run)).is_none());
6730 assert!(!compatible_run_instruction(&run, &t));
6731 t.review_branch = Some("approved-head".into());
6732 t.review_instruction = None;
6733 assert!(
6734 take_review_branch(&mut t, Some(&run)).is_none(),
6735 "legacy retained candidate cannot replace a revised approved head"
6736 );
6737 }
6738
6739 #[test]
6740 fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
6741 crate::run::pin_test_home();
6742 let dir = tempfile::tempdir().unwrap();
6743 let queue = Queue::at(dir.path().join("queue"));
6744 for resume in [true, false] {
6745 let state = run_state(RunStatus::Blocked);
6746 let mut t = task();
6747 t.start(state.id.clone());
6748 let action = if resume {
6749 ask::ChoiceAction::Resume {
6750 run: state.id.clone(),
6751 }
6752 } else {
6753 ask::ChoiceAction::Requeue
6754 };
6755 let mut q = action_question(&state.id, action);
6756 q.status = ask::QuestionStatus::Open;
6757 q.answer = None;
6758 q.answered_at = None;
6759 t.fail("run stopped with a question", 3);
6760 hold_if_runnable(&queue, &mut t);
6761 assert!(t.operator_decided_at.is_none());
6762 assert!(t.operator_held());
6763 q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
6764 let expected = if resume {
6765 ActionDecision::Resume(state.id.clone())
6766 } else {
6767 ActionDecision::Requeue
6768 };
6769 assert_eq!(
6770 decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
6771 expected
6772 );
6773 t.hold_manual(Some("later explicit hold".into()));
6774 assert_eq!(
6775 decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
6776 ActionDecision::Stale
6777 );
6778 }
6779 }
6780
6781 #[test]
6782 fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
6783 let mut t = task();
6784 t.answers.push(crate::queue::AnsweredQuestion {
6785 question: "Inspect the remote?".into(),
6786 answer: "Inspect then wait".into(),
6787 });
6788 let old = instruction_for(&t);
6789 assert!(compatible_instruction(&old, &t));
6790 t.instruction = "Reuse approved PR head and review".into();
6791 t.release_operator("cli", None);
6792 assert!(!compatible_instruction(&old, &t));
6793 let approved = instruction_for(&t);
6794 assert!(approved.contains("waiting premises are superseded"));
6795 assert!(compatible_instruction(&approved, &t));
6796 assert_eq!(resumed_instruction(&approved, &t), approved);
6797 t.release_operator("web", None);
6798 assert!(compatible_instruction(&approved, &t));
6799 assert_eq!(t.resumption_history.len(), 1);
6800 t.start("run".into());
6801 assert!(instruction_for(&t).contains("Explicit operator resumption"));
6802 }
6803
6804 #[test]
6808 fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
6809 let mut state = RunState::new(
6810 PathBuf::from("/repo"),
6811 "main".into(),
6812 "base".into(),
6813 "task".into(),
6814 Config::default(),
6815 );
6816 state.status = RunStatus::Landing;
6817 state.parked = true;
6818 state.pr_pushed_head = Some("head".into());
6819 state.land_unrelated = Some(
6820 serde_json::from_value(serde_json::json!({
6821 "head": "head", "question": "ci-question",
6822 "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
6823 }))
6824 .unwrap(),
6825 );
6826 let mut t = task();
6827 t.start(state.id.clone());
6828 let verdict = Verdict {
6829 status: RunStatus::Landing,
6830 left_pr: true,
6831 quota_hit: false,
6832 parked: true,
6833 no_viable_candidates: false,
6834 };
6835 settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
6836 assert_eq!(t.attempts, 0);
6837 assert_eq!(t.status, TaskStatus::Held);
6838 assert!(!t.operator_held());
6839 assert!(
6840 t.hold_reason
6841 .as_deref()
6842 .unwrap()
6843 .starts_with("[ci-unrelated]")
6844 );
6845 t.attempts = 1;
6847 settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
6848 assert_eq!(t.attempts, 1);
6849 assert_eq!(t.passes.len(), 1);
6850 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
6851 state.pr_pushed_head = Some("new-head".into());
6852 state.parked = false;
6853 state.status = RunStatus::Blocked;
6854 let stale = Verdict {
6855 status: RunStatus::Blocked,
6856 parked: false,
6857 ..verdict
6858 };
6859 settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
6860 assert_eq!(t.attempts, 1);
6861 state.begin_pass();
6863 state.begin_pass();
6864 state.status = RunStatus::Landing;
6865 state.parked = true;
6866 state.pr_pushed_head = Some("head".into());
6867 settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
6868 assert_eq!(t.attempts, 0);
6869 assert_eq!(t.passes.len(), 2);
6870 }
6871
6872 #[test]
6873 fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
6874 let mut state = RunState::new(
6875 PathBuf::from("/repo"),
6876 "main".to_owned(),
6877 "abc1234".to_owned(),
6878 "task".to_owned(),
6879 Config::default(),
6880 );
6881 state.status = RunStatus::Blocked;
6882 state.resource_block = Some(crate::run::ResourceBlock {
6883 cause: crate::run::ResourceBlockCause::Other,
6884 node: "graft".to_owned(),
6885 kind: "shared build cache".to_owned(),
6886 detail: "timed out".to_owned(),
6887 at: jiff::Timestamp::now(),
6888 });
6889 let mut t = task();
6890 t.start("20260902-000000-aaaa".to_owned());
6891 assert_eq!(t.attempts, 1);
6892 let verdict = Verdict {
6893 status: RunStatus::Blocked,
6894 left_pr: false,
6895 quota_hit: false,
6896 parked: false,
6897 no_viable_candidates: false,
6898 };
6899 settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
6900 assert_eq!(t.status, TaskStatus::Held);
6901 assert_eq!(t.attempts, 0, "the attempt is refunded");
6902 assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
6903 assert!(
6904 !t.operator_held(),
6905 "a machine hold, released without a human"
6906 );
6907
6908 let mut selected = task();
6909 selected.start("20260902-000000-cccc".into());
6910 selected.replacement = Some(crate::merge_decision::Replacement {
6911 question: "fixture".into(),
6912 run: "earlier".into(),
6913 pr: "https://example.invalid/pr/1".into(),
6914 agent: "selected".into(),
6915 context: "fixture".into(),
6916 });
6917 state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
6918 settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
6919 assert_eq!(selected.attempts, 0);
6920 assert!(
6921 !selected.operator_held(),
6922 "a selected agent also retains a machine resource hold"
6923 );
6924 assert!(
6925 selected
6926 .hold_reason
6927 .as_deref()
6928 .unwrap()
6929 .starts_with("[resource] ")
6930 );
6931
6932 let mut p = task();
6934 p.start("20260902-000000-bbbb".to_owned());
6935 settle_and_diagnose(
6936 &mut p,
6937 Verdict {
6938 parked: true,
6939 ..verdict
6940 },
6941 "parked",
6942 2,
6943 &state,
6944 );
6945 assert_eq!(p.status, TaskStatus::Parked);
6946 assert_eq!(
6947 p.attempts, 0,
6948 "parking refunds once rather than also settling the resource hold"
6949 );
6950 }
6951
6952 #[test]
6953 fn record_failure_notice_links_the_task() {
6954 let dir = tempfile::tempdir().unwrap();
6955 std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
6958 let queue = Queue::at(dir.path().join("queue"));
6959 let mut t = interrupt_task("rec-fail-1");
6960 record(&queue, &mut t);
6961
6962 let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
6963 assert_eq!(found.len(), 1);
6964 assert_eq!(found[0].key, "loop:record");
6965 assert_eq!(
6966 found[0].link,
6967 Some(Link::Task {
6968 id: "rec-fail-1".to_owned()
6969 })
6970 );
6971 }
6972
6973 fn interrupt_task(id: &str) -> Task {
6976 let mut t = task();
6977 t.id = id.to_owned();
6978 t.interrupt = true;
6979 t
6980 }
6981
6982 fn task_with_id(id: &str) -> Task {
6984 let mut t = task();
6985 t.id = id.to_owned();
6986 t
6987 }
6988
6989 fn urgent_task(id: &str) -> Task {
6991 let mut t = task();
6992 t.id = id.to_owned();
6993 t.urgent = true;
6994 t
6995 }
6996
6997 #[test]
6998 fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
6999 let dir = tempfile::tempdir().unwrap();
7000 let queue = Queue::at(dir.path().join("queue"));
7001 let mut parked = task_with_id("parked");
7002 parked.start("run".into());
7003 parked.park("upgrade");
7004 parked.record_pass_at(
7005 "run",
7006 0,
7007 Some(Timestamp::now()),
7008 1,
7009 Some(crate::run::ParkCause::Upgrade {
7010 from: "old".into(),
7011 to: None,
7012 }),
7013 );
7014 let mut fresh = task_with_id("fresh");
7015 fresh.priority = 100;
7016 let mut urgent_task = urgent_task("urgent");
7017 for t in [&mut parked, &mut fresh, &mut urgent_task] {
7018 queue.put(t).unwrap();
7019 }
7020 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7021 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7022 let candidates = runnable(&queue);
7023 assert_eq!(candidates[0].id, parked.id);
7024 let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
7025 assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_none());
7026 assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_some());
7027 drop(first);
7028 let claimed_elsewhere = queue.claim(&parked.id).unwrap();
7029 let next = runnable(&queue)
7030 .into_iter()
7031 .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent))
7032 .unwrap();
7033 assert_eq!(next.task.id, fresh.id);
7034 assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
7035 drop(claimed_elsewhere);
7036 drop(next);
7037 assert!(claim_dispatch(&queue, &parked, true, &ordinary, &urgent).is_none());
7038 }
7039
7040 #[test]
7041 fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
7042 let dir = tempfile::tempdir().unwrap();
7043 let queue = Queue::at(dir.path().join("queue"));
7044 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7045 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7046 let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
7047 let mut first = task();
7048 queue.put(&mut first).unwrap();
7049 let stale_plain = queue.get(&first.id).unwrap();
7050 first.set_urgent(true).unwrap();
7051 queue.put(&mut first).unwrap();
7052 let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
7053 let mut second = urgent_task("second");
7054 queue.put(&mut second).unwrap();
7055 assert!(claim_dispatch(&queue, &second, false, &ordinary, &urgent).is_none());
7056 drop(queue.claim(&second.id).unwrap());
7057 assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
7058 drop(dispatched);
7059 let stale_urgent = queue.get(&first.id).unwrap();
7060 first.set_urgent(false).unwrap();
7061 queue.put(&mut first).unwrap();
7062 assert!(claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent).is_none());
7063 assert_eq!(urgent.available_permits(), 1);
7064 drop(queue.claim(&first.id).unwrap());
7065 drop(occupied);
7066 }
7067
7068 #[test]
7069 fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
7070 let dir = tempfile::tempdir().unwrap();
7071 let queue = Queue::at(dir.path().join("queue"));
7072 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7073 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7074 let mut t = task();
7075 queue.put(&mut t).unwrap();
7076 for enabled in [true, false] {
7077 let stale = queue.get(&t.id).unwrap();
7078 t.set_urgent(enabled).unwrap();
7079 queue.put(&mut t).unwrap();
7080 assert_ne!(stale.urgent, enabled);
7081 let DispatchClaim {
7082 task: fresh,
7083 claim,
7084 permit,
7085 } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
7086 assert_eq!(fresh.urgent, enabled);
7087 assert_eq!(ordinary.available_permits(), usize::from(enabled));
7088 assert_eq!(urgent.available_permits(), usize::from(!enabled));
7089 assert!(queue.claim(&t.id).is_err());
7090 assert_eq!(fresh.attempts, stale.attempts);
7091 drop((claim, permit));
7092 assert_eq!(ordinary.available_permits(), 1);
7093 assert_eq!(urgent.available_permits(), 1);
7094 }
7095 t.set_urgent(true).unwrap();
7096 queue.put(&mut t).unwrap();
7097 let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
7098 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7099 assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
7100 drop(queue.claim(&t.id).unwrap());
7101 assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
7102 drop(occupied);
7103 assert!(claim_dispatch(&queue, &t, true, &ordinary, &urgent).is_none());
7104 drop(queue.claim(&t.id).unwrap());
7105 let held = queue.claim(&t.id).unwrap();
7106 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7107 drop(held);
7108 t.status = TaskStatus::Held;
7109 queue.put(&mut t).unwrap();
7110 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7111 drop(queue.claim(&t.id).unwrap());
7112 std::fs::remove_file(queue.path_of(&t.id)).unwrap();
7113 assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7114 drop(queue.claim(&t.id).unwrap());
7115 assert_eq!(urgent.available_permits(), 1);
7116 }
7117
7118 #[test]
7123 fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
7124 assert_eq!(permit_kind(true, false), PermitKind::None);
7125 assert_eq!(permit_kind(true, true), PermitKind::None);
7126 }
7127
7128 #[test]
7133 fn permit_kind_separates_urgent_from_ordinary() {
7134 assert_eq!(permit_kind(false, true), PermitKind::Urgent);
7135 assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
7136 }
7137
7138 #[test]
7145 fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
7146 let cfg = Config::default();
7147 let repo = Path::new("/any/repo/path");
7148
7149 let reason =
7150 disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
7151 assert!(reason.contains("1024"), "{reason}");
7152 assert!(
7153 reason.contains(&cfg.disk.min_free_bytes.to_string()),
7154 "{reason}"
7155 );
7156
7157 assert_eq!(
7158 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
7159 None,
7160 "exactly at the floor is open"
7161 );
7162 assert_eq!(
7163 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
7164 None,
7165 "comfortably above the floor is open"
7166 );
7167 }
7168
7169 #[test]
7170 fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
7171 let mut cfg = Config::default();
7172 cfg.disk.min_free_bytes = 0;
7173 let repo = Path::new("/any/repo/path");
7174 assert_eq!(
7175 disk_gate_with(repo, &cfg, |_| Ok(0)),
7176 None,
7177 "a zero floor never measures at all"
7178 );
7179 }
7180
7181 #[test]
7182 fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
7183 let cfg = Config::default();
7184 let repo = Path::new("/any/repo/path");
7185 let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
7186 .expect("a measurement failure must close the gate, not open it");
7187 assert!(reason.contains("could not measure"), "{reason}");
7188 }
7189
7190 #[test]
7191 fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
7192 let ordinary = task();
7193 let next = advance_interrupt(
7194 Interrupt::Idle,
7195 std::slice::from_ref(&ordinary.id),
7196 std::slice::from_ref(&ordinary),
7197 );
7198 assert_eq!(next, Interrupt::Idle);
7199 }
7200
7201 #[test]
7202 fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
7203 let marked = interrupt_task("marked");
7206 let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7207 assert_eq!(next, Interrupt::Idle);
7208 }
7209
7210 #[test]
7211 fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
7212 let marked = interrupt_task("marked");
7213 let next = advance_interrupt(
7214 Interrupt::Idle,
7215 &["running".to_owned()],
7216 std::slice::from_ref(&marked),
7217 );
7218 assert_eq!(
7219 next,
7220 Interrupt::Parking {
7221 parked: vec!["running".to_owned()],
7222 interrupt_task: "marked".to_owned(),
7223 }
7224 );
7225 }
7226
7227 #[test]
7236 fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
7237 let marked = interrupt_task("marked");
7238
7239 let two = advance_interrupt(
7240 Interrupt::Idle,
7241 &["a".to_owned(), "b".to_owned()],
7242 std::slice::from_ref(&marked),
7243 );
7244 assert_eq!(two, Interrupt::Idle);
7245
7246 let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7247 assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
7248 }
7249
7250 #[test]
7251 fn parking_holds_until_every_parked_id_has_actually_left_flight() {
7252 let state = Interrupt::Parking {
7253 parked: vec!["running".to_owned()],
7254 interrupt_task: "marked".to_owned(),
7255 };
7256 let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
7258 assert_eq!(still_going, state);
7259
7260 let stopped_but_not_yet_dispatched =
7264 advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
7265 assert_eq!(stopped_but_not_yet_dispatched, state);
7266
7267 let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
7269 assert_eq!(
7270 dispatched,
7271 Interrupt::Running {
7272 parked: vec!["running".to_owned()],
7273 interrupt_task: "marked".to_owned(),
7274 }
7275 );
7276 }
7277
7278 #[test]
7279 fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
7280 let state = Interrupt::Running {
7281 parked: vec!["running".to_owned()],
7282 interrupt_task: "marked".to_owned(),
7283 };
7284 let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
7285 assert_eq!(still_running, state);
7286
7287 let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
7294 assert_eq!(
7295 ended,
7296 Interrupt::Resuming {
7297 parked: vec!["running".to_owned()]
7298 }
7299 );
7300 }
7301
7302 #[test]
7303 fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
7304 let state = Interrupt::Resuming {
7305 parked: vec!["running".to_owned()],
7306 };
7307 let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
7308 assert_eq!(still_waiting, state);
7309
7310 let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
7311 assert_eq!(dispatched, Interrupt::Idle);
7312 }
7313
7314 #[test]
7320 fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
7321 {
7322 let state = Interrupt::Parking {
7323 parked: vec!["running".to_owned()],
7324 interrupt_task: "marked".to_owned(),
7325 };
7326 let next = advance_interrupt(state, &[], &[]);
7329 assert_eq!(
7330 next,
7331 Interrupt::Resuming {
7332 parked: vec!["running".to_owned()]
7333 },
7334 "abandoning the interrupt must not abandon the resume it owes"
7335 );
7336 }
7337
7338 #[test]
7341 fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
7342 let state = Interrupt::Resuming {
7343 parked: vec!["running".to_owned()],
7344 };
7345 let next = advance_interrupt(state, &[], &[]);
7346 assert_eq!(
7347 next,
7348 Interrupt::Idle,
7349 "nothing is left to wait for; the loop must not stay wedged"
7350 );
7351 }
7352
7353 #[test]
7354 fn disabled_by_config_the_sequence_can_never_leave_idle() {
7355 let marked = interrupt_task("marked");
7356 let next = advance_interrupt_tick(
7357 false,
7358 Interrupt::Idle,
7359 &["running".to_owned()],
7360 std::slice::from_ref(&marked),
7361 );
7362 assert_eq!(
7363 next,
7364 Interrupt::Idle,
7365 "an unmarked, unconfigured daemon must behave exactly as before"
7366 );
7367 }
7368
7369 #[test]
7370 fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
7371 let state = Interrupt::Parking {
7372 parked: vec!["running".to_owned()],
7373 interrupt_task: "marked".to_owned(),
7374 };
7375 let candidates = vec![interrupt_task("marked"), task()];
7376 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
7377 assert!(
7378 allowed.is_empty(),
7379 "nothing may dispatch - not even the interrupt task itself - \
7380 until the parked run has actually stopped"
7381 );
7382 }
7383
7384 #[test]
7398 fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
7399 for state in [
7400 Interrupt::Parking {
7401 parked: vec!["running".to_owned()],
7402 interrupt_task: "marked".to_owned(),
7403 },
7404 Interrupt::Running {
7405 parked: vec!["running".to_owned()],
7406 interrupt_task: "marked".to_owned(),
7407 },
7408 Interrupt::Resuming {
7409 parked: vec!["running".to_owned()],
7410 },
7411 ] {
7412 let candidates = vec![
7413 interrupt_task("marked"),
7414 urgent_task("hot"),
7415 task_with_id("ordinary"),
7416 ];
7417 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
7418 assert!(
7419 !allowed.iter().any(|t| t.id == "hot"),
7420 "an urgent candidate must wait out the same gate as anything \
7421 else while the run it would run alongside has not actually \
7422 left flight, for state {state:?}: {allowed:?}"
7423 );
7424 }
7425 }
7426
7427 #[test]
7433 fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
7434 let state = Interrupt::Resuming {
7435 parked: vec!["hot".to_owned()],
7436 };
7437 let candidates = vec![urgent_task("hot"), task()];
7438 let allowed = interrupt_gate(&state, &[], candidates);
7439 assert_eq!(
7440 allowed.iter().filter(|t| t.id == "hot").count(),
7441 1,
7442 "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
7443 );
7444 }
7445
7446 #[test]
7447 fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
7448 let state = Interrupt::Parking {
7449 parked: vec!["running".to_owned()],
7450 interrupt_task: "marked".to_owned(),
7451 };
7452 let other = task();
7453 let candidates = vec![interrupt_task("marked"), other.clone()];
7454 let allowed = interrupt_gate(&state, &[], candidates);
7455 assert_eq!(allowed.len(), 1);
7456 assert_eq!(allowed[0].id, "marked");
7457 }
7458
7459 #[test]
7460 fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
7461 let state = Interrupt::Running {
7462 parked: vec!["running".to_owned()],
7463 interrupt_task: "marked".to_owned(),
7464 };
7465 let candidates = vec![task(), task()];
7466 let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
7467 assert!(allowed.is_empty());
7468 }
7469
7470 #[test]
7477 fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
7478 let state = Interrupt::Resuming {
7479 parked: vec!["a".to_owned(), "c".to_owned()],
7480 };
7481 let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
7482 let allowed = interrupt_gate(&state, &[], candidates);
7483 assert_eq!(
7484 allowed.len(),
7485 1,
7486 "at most one candidate may be offered while resuming: {allowed:?}"
7487 );
7488 assert_eq!(allowed[0].id, "a");
7489 }
7490
7491 #[test]
7492 fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
7493 let state = Interrupt::Resuming {
7494 parked: vec!["a".to_owned()],
7495 };
7496 let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
7497 assert!(allowed.is_empty());
7498 }
7499
7500 #[test]
7506 fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
7507 let running = task(); let marked = interrupt_task("marked");
7509
7510 let mut state = Interrupt::Idle;
7511 let in_flight = vec![running.id.clone()];
7513 state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
7514 let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
7515 assert!(gated.is_empty(), "still waiting on `running` to park");
7516
7517 state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
7519 let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
7520 assert_eq!(
7521 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7522 vec!["marked"],
7523 "only the interrupt task may be offered to the dispatcher now"
7524 );
7525
7526 state = advance_interrupt_tick(
7528 true,
7529 state,
7530 &["marked".to_owned()],
7531 std::slice::from_ref(&running),
7532 );
7533 let gated = interrupt_gate(
7534 &state,
7535 &["marked".to_owned()],
7536 vec![marked.clone(), running.clone()],
7537 );
7538 assert!(
7539 gated.is_empty(),
7540 "the parked run must not be offered back while the interrupt \
7541 task is still running"
7542 );
7543
7544 let other = task_with_id("other");
7548 state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
7549 assert_eq!(
7550 state,
7551 Interrupt::Resuming {
7552 parked: vec![running.id.clone()]
7553 }
7554 );
7555 let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
7556 assert_eq!(
7557 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7558 vec![running.id.as_str()],
7559 "exactly the parked run resumes - not the unrelated task, even \
7560 though it was offered first"
7561 );
7562
7563 state = advance_interrupt_tick(
7567 true,
7568 state,
7569 std::slice::from_ref(&running.id),
7570 std::slice::from_ref(&other),
7571 );
7572 assert_eq!(state, Interrupt::Idle);
7573 let gated = interrupt_gate(
7574 &state,
7575 std::slice::from_ref(&running.id),
7576 vec![other.clone()],
7577 );
7578 assert_eq!(
7579 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7580 vec![other.id.as_str()],
7581 "ordinary dispatch is unrestricted again"
7582 );
7583 }
7584
7585 #[test]
7586 fn every_run_status_settles_the_task_it_came_from() {
7587 let table = [
7589 (RunStatus::Merged, TaskStatus::Done, 1),
7590 (RunStatus::Ready, TaskStatus::Done, 1),
7591 (RunStatus::Stalled, TaskStatus::Failed, 0),
7592 (RunStatus::Blocked, TaskStatus::Failed, 1),
7593 (RunStatus::Failed, TaskStatus::Failed, 1),
7594 (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
7595 (RunStatus::Prep, TaskStatus::Failed, 1),
7596 (RunStatus::Implementing, TaskStatus::Failed, 1),
7597 (RunStatus::Judging, TaskStatus::Failed, 1),
7598 (RunStatus::Deliberating, TaskStatus::Failed, 1),
7599 (RunStatus::Voting, TaskStatus::Failed, 1),
7600 (RunStatus::Reviewing, TaskStatus::Failed, 1),
7601 (RunStatus::Gating, TaskStatus::Failed, 1),
7602 ];
7603 for (run, want, attempts) in table {
7604 let mut t = task();
7605 t.start("20260902-000000-aaaa".to_owned());
7606 settle(
7607 &mut t,
7608 Verdict {
7609 status: run,
7610 left_pr: false,
7611 parked: false,
7612 quota_hit: matches!(run, RunStatus::Stalled),
7613 no_viable_candidates: false,
7614 },
7615 "why",
7616 2,
7617 );
7618 assert_eq!(t.status, want, "task status after {}", label(run));
7619 assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
7620 }
7621 }
7622
7623 #[test]
7624 fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
7625 let mut stalled = task();
7626 stalled.start("20260902-000000-aaaa".to_owned());
7627 settle(
7628 &mut stalled,
7629 Verdict {
7630 status: RunStatus::Stalled,
7631 left_pr: false,
7632 parked: false,
7633 quota_hit: true,
7634 no_viable_candidates: false,
7635 },
7636 "quota",
7637 1,
7638 );
7639 assert_eq!(stalled.attempts, 0);
7640 assert!(
7641 stalled.status.runnable(),
7642 "a machine problem must leave the task in line"
7643 );
7644
7645 let mut blocked = task();
7646 blocked.start("20260902-000000-aaaa".to_owned());
7647 settle(
7648 &mut blocked,
7649 Verdict {
7650 status: RunStatus::Blocked,
7651 left_pr: false,
7652 parked: false,
7653 quota_hit: false,
7654 no_viable_candidates: false,
7655 },
7656 "findings open",
7657 1,
7658 );
7659 assert_eq!(blocked.attempts, 1);
7660 assert_eq!(
7661 blocked.status,
7662 TaskStatus::Held,
7663 "the last attempt hands the task to a human"
7664 );
7665 }
7666
7667 #[test]
7668 fn a_run_that_opened_a_pull_request_is_never_re_competed() {
7669 let mut delivered = task();
7672 delivered.start("20260903-080619-01c2".to_owned());
7673 settle(
7674 &mut delivered,
7675 Verdict {
7676 status: RunStatus::Blocked,
7677 left_pr: true,
7678 parked: false,
7679 quota_hit: false,
7680 no_viable_candidates: false,
7681 },
7682 "no check status",
7683 4,
7684 );
7685 assert_eq!(
7686 delivered.status,
7687 TaskStatus::Held,
7688 "a pull request waiting on CI or a person is not a retryable failure"
7689 );
7690 assert!(
7691 !delivered.status.runnable(),
7692 "the loop must not pick this task up again"
7693 );
7694 assert_eq!(
7695 delivered.last_error.as_deref(),
7696 Some("no check status"),
7697 "the operator needs to be told what the gate was waiting for"
7698 );
7699
7700 let mut empty_handed = task();
7703 empty_handed.start("20260903-080619-01c2".to_owned());
7704 settle(
7705 &mut empty_handed,
7706 Verdict {
7707 status: RunStatus::Blocked,
7708 left_pr: false,
7709 parked: false,
7710 quota_hit: false,
7711 no_viable_candidates: false,
7712 },
7713 "findings open",
7714 4,
7715 );
7716 assert_eq!(empty_handed.status, TaskStatus::Failed);
7717 assert!(empty_handed.status.runnable());
7718 }
7719
7720 #[test]
7721 fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
7722 let mut noop = task();
7728 noop.start("20260912-131304-391f".to_owned());
7729 settle(
7730 &mut noop,
7731 Verdict {
7732 status: RunStatus::VerifiedNoop,
7733 left_pr: false,
7734 parked: false,
7735 quota_hit: false,
7736 no_viable_candidates: true,
7737 },
7738 "candidate A: already fixed by b32cfc4, on main",
7739 4,
7740 );
7741 assert_eq!(
7742 noop.status,
7743 TaskStatus::Held,
7744 "an unverified claim is a request for a human, not a failure"
7745 );
7746 assert!(
7747 !noop.status.runnable(),
7748 "the loop must not requeue this on the same unverified claim"
7749 );
7750 assert_eq!(noop.attempts, 1);
7755 }
7756
7757 #[test]
7758 fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
7759 let mut parked = task();
7764 parked.start("20260903-183634-2d98".to_owned());
7765 settle(
7766 &mut parked,
7767 Verdict {
7768 status: RunStatus::Implementing,
7769 left_pr: false,
7770 quota_hit: false,
7771 parked: true,
7772 no_viable_candidates: false,
7773 },
7774 "parked after `implementing`",
7775 2,
7776 );
7777 assert_eq!(parked.attempts, 0, "a park is refunded");
7778 assert!(
7779 parked.status.runnable(),
7780 "and the task stays in line so the next loop resumes its run"
7781 );
7782 assert_eq!(parked.status, TaskStatus::Parked);
7783 assert_eq!(
7784 parked.park_reason.as_deref(),
7785 Some("parked after `implementing`"),
7786 "the card says where it stopped"
7787 );
7788 assert_eq!(parked.last_error, None, "nothing failed");
7789
7790 let mut broken = task();
7794 broken.start("20260903-183634-2d98".to_owned());
7795 settle(
7796 &mut broken,
7797 Verdict {
7798 status: RunStatus::Implementing,
7799 left_pr: false,
7800 quota_hit: false,
7801 parked: false,
7802 no_viable_candidates: false,
7803 },
7804 "returned mid-flight",
7805 2,
7806 );
7807 assert_eq!(broken.attempts, 1);
7808 }
7809
7810 #[test]
7811 fn only_a_rate_limit_buys_the_task_its_attempt_back() {
7812 let mut flaky = task();
7817 flaky.start("20260903-123023-e633".to_owned());
7818 settle(
7819 &mut flaky,
7820 Verdict {
7821 status: RunStatus::Stalled,
7822 left_pr: false,
7823 parked: false,
7824 quota_hit: false,
7825 no_viable_candidates: false,
7826 },
7827 "verdict rests on 1 of 3 judges",
7828 2,
7829 );
7830 assert_eq!(
7831 flaky.attempts, 1,
7832 "flakiness spends an attempt, so `max_attempts` still bounds it"
7833 );
7834 assert!(flaky.status.runnable(), "and it is still worth retrying");
7835
7836 let mut limited = task();
7838 limited.start("20260903-123023-e633".to_owned());
7839 settle(
7840 &mut limited,
7841 Verdict {
7842 status: RunStatus::Stalled,
7843 left_pr: false,
7844 parked: false,
7845 quota_hit: true,
7846 no_viable_candidates: false,
7847 },
7848 "judge-2, judge-3 out of quota",
7849 2,
7850 );
7851 assert_eq!(limited.attempts, 0, "a quota window is refunded");
7852 assert!(limited.status.runnable());
7853
7854 let mut worn = task();
7857 for _ in 0..2 {
7858 worn.release();
7859 }
7860 worn.start("20260903-123023-e633".to_owned());
7861 worn.attempts = 2;
7862 settle(
7863 &mut worn,
7864 Verdict {
7865 status: RunStatus::Stalled,
7866 left_pr: false,
7867 parked: false,
7868 quota_hit: false,
7869 no_viable_candidates: false,
7870 },
7871 "no quorum again",
7872 2,
7873 );
7874 assert_eq!(worn.status, TaskStatus::Held);
7875 assert!(!worn.status.runnable());
7876 }
7877
7878 #[test]
7879 fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
7880 let mut wiped_out = task();
7887 wiped_out.start("20260907-025000-a1b2".to_owned());
7888 settle(
7889 &mut wiped_out,
7890 Verdict {
7891 status: RunStatus::Failed,
7892 left_pr: false,
7893 parked: false,
7894 quota_hit: true,
7895 no_viable_candidates: true,
7896 },
7897 "no candidate produced a change; nothing to judge",
7898 2,
7899 );
7900 assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
7901 assert!(
7902 wiped_out.status.runnable(),
7903 "a machine problem must leave the task in line"
7904 );
7905
7906 let mut partial_progress = task();
7912 partial_progress.start("20260907-025500-c3d4".to_owned());
7913 settle(
7914 &mut partial_progress,
7915 Verdict {
7916 status: RunStatus::Failed,
7917 left_pr: false,
7918 parked: false,
7919 quota_hit: true,
7920 no_viable_candidates: false,
7921 },
7922 "gate failed on the winning candidate",
7923 2,
7924 );
7925 assert_eq!(
7926 partial_progress.attempts, 1,
7927 "a candidate that actually produced a change spends the attempt \
7928 even though some other seat hit its quota"
7929 );
7930 assert!(partial_progress.status.runnable());
7931 }
7932
7933 #[test]
7934 fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
7935 let mut t = task();
7941 t.start("20260907-025000-a1b2".to_owned());
7942 let mut state = run_state(RunStatus::Failed);
7943 state.quota.push(QuotaLoss {
7944 seat: "cand-a".to_owned(),
7945 node: "implement".to_owned(),
7946 at: Timestamp::now(),
7947 reset: None,
7948 });
7949 assert!(
7950 state.viable().is_empty(),
7951 "no candidate was added, so nothing is viable"
7952 );
7953 reclaim(&mut t, Some(state), 2, "en");
7954 assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
7955 assert!(t.status.runnable());
7956 }
7957
7958 #[test]
7959 fn a_held_task_is_never_offered_to_the_loop() {
7960 let dir = tempfile::tempdir().unwrap();
7961 let queue = Queue::at(dir.path().to_path_buf());
7962 for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
7963 let mut t = task();
7964 t.id = format!("2026090{n}-000000-000{n}");
7965 t.priority = priority;
7966 queue.put(&mut t).unwrap();
7967 }
7968 let mut held = task();
7969 held.id = "20260909-000000-9999".to_owned();
7970 held.priority = 99;
7971 held.hold_machine(None);
7972 queue.put(&mut held).unwrap();
7973
7974 let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
7975 assert_eq!(order.len(), 3);
7976 assert!(!order.contains(&held.id));
7977 assert_eq!(
7978 order.first().cloned(),
7979 queue.next_runnable().map(|t| t.id),
7980 "the loop's first candidate is exactly what the queue offers"
7981 );
7982 assert_eq!(
7983 order,
7984 vec![
7985 "20260902-000000-0002".to_owned(),
7986 "20260903-000000-0003".to_owned(),
7987 "20260901-000000-0001".to_owned(),
7988 ],
7989 "priority first, then oldest, so nothing starves"
7990 );
7991 }
7992
7993 #[test]
7994 fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
7995 let dir = tempfile::tempdir().unwrap();
7996 let queue = Queue::at(dir.path().to_path_buf());
7997 let mut old = task();
7998 old.id = "20260101-000000-old0".to_owned();
7999 queue.put(&mut old).unwrap();
8000 let mut fresh = task();
8001 fresh.id = "20260101-000000-new0".to_owned();
8002 queue.put(&mut fresh).unwrap();
8003
8004 std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
8008 std::thread::sleep(Duration::from_millis(60));
8009 let live = queue.claim(&fresh.id).unwrap();
8010
8011 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8012 assert_eq!(swept, vec![old.id.clone()]);
8013 assert!(
8014 queue.claim(&old.id).is_ok(),
8015 "an unparseable lock older than the threshold is swept"
8016 );
8017 assert!(
8018 queue.claim(&fresh.id).is_err(),
8019 "a live pid protects its lock regardless of age"
8020 );
8021 drop(live);
8022 }
8023
8024 #[test]
8025 fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
8026 let dir = tempfile::tempdir().unwrap();
8029 let queue = Queue::at(dir.path().to_path_buf());
8030 let mut t = task();
8031 t.id = "20260101-000000-live".to_owned();
8032 queue.put(&mut t).unwrap();
8033
8034 let claim = queue.claim(&t.id).unwrap();
8035 std::thread::sleep(Duration::from_millis(60));
8036
8037 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8038 assert!(
8039 swept.is_empty(),
8040 "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
8041 );
8042 assert!(
8043 queue.claim(&t.id).is_err(),
8044 "the lock still protects its task"
8045 );
8046 drop(claim);
8047 }
8048
8049 fn injected_dead_pid() -> u32 {
8052 std::process::id().checked_add(1).unwrap_or(1)
8053 }
8054
8055 #[test]
8056 fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
8057 let dir = tempfile::tempdir().unwrap();
8058 let queue = Queue::at(dir.path().to_path_buf());
8059 let mut t = task();
8060 t.id = "20260101-000000-dead".to_owned();
8061 queue.put(&mut t).unwrap();
8062 let dead_pid = injected_dead_pid();
8063
8064 std::fs::write(
8069 dir.path().join(format!("{}.lock", t.id)),
8070 dead_pid.to_string(),
8071 )
8072 .unwrap();
8073
8074 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8075 pid != dead_pid
8076 });
8077 assert_eq!(
8078 swept,
8079 vec![t.id.clone()],
8080 "a dead owner is reclaimed immediately, not after STALE_CLAIM"
8081 );
8082 assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
8083 }
8084
8085 #[test]
8086 fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
8087 let dir = tempfile::tempdir().unwrap();
8088 let queue = Queue::at(dir.path().to_path_buf());
8089 let mut t = task();
8090 t.id = "20260101-000000-late".to_owned();
8091 queue.put(&mut t).unwrap();
8092 let dead_pid = injected_dead_pid();
8093
8094 assert!(
8097 sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
8098 "nothing has claimed the task yet"
8099 );
8100
8101 std::fs::write(
8104 dir.path().join(format!("{}.lock", t.id)),
8105 dead_pid.to_string(),
8106 )
8107 .unwrap();
8108
8109 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8113 pid != dead_pid
8114 });
8115 assert_eq!(swept, vec![t.id.clone()]);
8116 }
8117
8118 #[test]
8119 fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
8120 crate::run::pin_test_home();
8125 let dir = tempfile::tempdir().unwrap();
8126 let queue = Queue::at(dir.path().to_path_buf());
8127 let mut t = task();
8128 t.id = "20260101-000000-crsh".to_owned();
8129 t.status = TaskStatus::Running;
8130 t.attempts = 1;
8131 t.runs.push("20260904-000000-4043".to_owned());
8135 queue.put(&mut t).unwrap();
8136 let dead_pid = injected_dead_pid();
8137
8138 std::fs::write(
8141 dir.path().join(format!("{}.lock", t.id)),
8142 dead_pid.to_string(),
8143 )
8144 .unwrap();
8145
8146 assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
8152 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
8153
8154 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8155 pid != dead_pid
8156 });
8157 assert_eq!(swept, vec![t.id.clone()]);
8158
8159 let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
8160 assert_eq!(reclaimed, vec![t.id.clone()]);
8161 let after = queue.get(&t.id).unwrap();
8162 assert_eq!(
8163 after.status,
8164 TaskStatus::Held,
8165 "no run.json to recover from, so a human is asked"
8166 );
8167 assert_eq!(
8168 after.runs,
8169 vec!["20260904-000000-4043".to_owned()],
8170 "the crashed run's id is kept as evidence, not discarded"
8171 );
8172 }
8173
8174 #[test]
8175 fn a_lock_is_kept_when_the_process_query_is_unavailable() {
8176 let dir = tempfile::tempdir().unwrap();
8177 let queue = Queue::at(dir.path().to_path_buf());
8178 let mut t = task();
8179 t.id = "20260101-000000-unknown".to_owned();
8180 queue.put(&mut t).unwrap();
8181 let dead_pid = injected_dead_pid();
8182 std::fs::write(
8183 dir.path().join(format!("{}.lock", t.id)),
8184 dead_pid.to_string(),
8185 )
8186 .unwrap();
8187
8188 let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
8189 assert!(swept.is_empty(), "an unknown pid must keep its lock");
8190 assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
8191 }
8192
8193 fn run_state_in(status: RunStatus, language: &str) -> RunState {
8194 let mut s = run_state(status);
8195 s.config.graph.language = language.to_owned();
8196 s
8197 }
8198
8199 fn unstarted_verdict(status: RunStatus) -> Verdict {
8200 Verdict {
8201 status,
8202 left_pr: false,
8203 quota_hit: false,
8204 parked: false,
8205 no_viable_candidates: false,
8206 }
8207 }
8208
8209 #[test]
8210 fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
8211 let mut t = task();
8212 t.attempts = 1;
8213 settle_in(
8214 &mut t,
8215 unstarted_verdict(RunStatus::AlreadyInBase),
8216 "already in main",
8217 1,
8218 phrases("en"),
8219 );
8220 assert_eq!(t.status, TaskStatus::Done);
8221 assert_eq!(t.attempts, 0);
8222 }
8223
8224 #[test]
8225 fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
8226 let reason = |language: &str| {
8227 let mut t = task();
8228 settle_in(
8229 &mut t,
8230 unstarted_verdict(RunStatus::Judging),
8231 "boom",
8232 1,
8233 phrases(language),
8234 );
8235 t.last_error.or(t.hold_reason).unwrap_or_default()
8236 };
8237 assert!(
8238 reason("en").starts_with("the graph stopped at `"),
8239 "{}",
8240 reason("en")
8241 );
8242 assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
8243 assert!(reason("日本語").contains("boom"));
8244 assert_eq!(reason("fr"), reason("en"));
8245 }
8246
8247 #[test]
8248 fn describe_follows_the_run_language_and_keeps_the_run_id() {
8249 let en = describe(&run_state_in(RunStatus::Stalled, "en"));
8250 assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
8251 let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
8252 assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
8253 assert!(ja.contains("[run "), "{ja}");
8254 let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
8255 assert!(ended.starts_with("run 終了: "), "{ended}");
8256 let mut de = run_state_in(RunStatus::Failed, "de");
8257 let mut en = run_state_in(RunStatus::Failed, "en");
8258 de.id = "same".to_owned();
8259 en.id = "same".to_owned();
8260 assert_eq!(describe(&de), describe(&en));
8261 }
8262
8263 #[test]
8264 fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
8265 use crate::handover::Refused;
8266 let cases = [
8267 Refused::Foreign {
8268 branch: "b".into(),
8269 path: "/w/x".into(),
8270 why: "made by hand".into(),
8271 },
8272 Refused::Unsafe {
8273 branch: "b".into(),
8274 path: "/w/x".into(),
8275 why: "its worktree has uncommitted changes (a.rs)".into(),
8276 },
8277 Refused::ReleaseFailed {
8278 branch: "b".into(),
8279 path: "/w/x".into(),
8280 run: "ab12".into(),
8281 },
8282 ];
8283 for r in &cases {
8284 let en = (phrases("en").handover_refused)(r);
8285 assert_eq!(en, r.to_string());
8286 let ja = (phrases("ja").handover_refused)(r);
8287 assert!(
8288 !ja.contains("is checked out") && !ja.contains("try again"),
8289 "{ja}"
8290 );
8291 assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
8292 if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
8293 assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
8294 }
8295 }
8296 assert!(phrases("en").handover_hint.contains("release the task"));
8297 assert!(phrases("ja").handover_hint.contains("解放"));
8298 }
8299
8300 #[test]
8301 fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
8302 let build = |lang: &str| {
8303 let mut s = run_state_in(RunStatus::Blocked, lang);
8304 s.id = "same".to_owned();
8305 s.config.graph.review_rounds = 3;
8306 let mut r = review_round(3);
8307 r.expected = 3;
8308 r.answered = 1;
8309 s.reviews.push(r);
8310 s.event(
8311 "review",
8312 "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
8313 );
8314 s
8315 };
8316 let en = describe(&build("en"));
8317 assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
8318 let ja = describe(&build("ja"));
8319 assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
8320 assert!(!ja.contains("never answered"), "{ja}");
8321 assert!(ja.contains("[run "), "{ja}");
8322
8323 let mut failed = build("ja");
8326 failed.reviews[0].e2e.push(crate::run::CommandOutcome {
8327 command: "cargo test".to_owned(),
8328 code: Some(1),
8329 output_tail: String::new(),
8330 duration_ms: 0,
8331 resource_blocked: false,
8332 });
8333 failed.event("review", "stopped; e2e failed: cargo test");
8334 let ja = describe(&failed);
8335 assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
8336 assert!(!ja.contains("席のレビュアー"), "{ja}");
8337 }
8338
8339 #[test]
8340 fn refusals_and_recovery_prose_follow_the_language() {
8341 let t = held_task_with("r1");
8342 let q = action_question(
8343 "r1",
8344 ask::ChoiceAction::Resume {
8345 run: "r1".to_owned(),
8346 },
8347 );
8348 let refuse = |p: &Phrases| match decide_action(&t, &q, p, |_: &str| bail!("gone")) {
8349 ActionDecision::Refuse(s) => s,
8350 other => panic!("{other:?}"),
8351 };
8352 assert!(refuse(phrases("en")).contains("could not be read: gone"));
8353 assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
8354 assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
8355
8356 let mut held = task();
8357 reclaim(&mut held, None, 2, "ja");
8358 assert!(held.hold_reason.unwrap().contains("保留にしました"));
8359 let mut held = task();
8360 reclaim(&mut held, None, 2, "xx");
8361 assert!(held.hold_reason.unwrap().contains("held for a human"));
8362 }
8363
8364 fn run_state(status: RunStatus) -> RunState {
8365 let mut state = RunState::new(
8366 PathBuf::from("/repo"),
8367 "main".to_owned(),
8368 "abc1234def".to_owned(),
8369 "add retries".to_owned(),
8370 Config::default(),
8371 );
8372 state.status = status;
8373 state
8374 }
8375
8376 fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
8377 Candidate {
8378 index: 0,
8379 label,
8380 agent: "claude".to_owned(),
8381 branch: format!("magi/x/{label}"),
8382 worktree: PathBuf::from("/repo"),
8383 summary: summary.to_owned(),
8384 stat: String::new(),
8385 files: 0,
8386 commits: usize::from(!empty),
8387 empty,
8388 failed: failed.map(str::to_owned),
8389 verified_noop: None,
8390 duration_ms: 0,
8391 folded: false,
8392 }
8393 }
8394
8395 #[test]
8396 fn diagnostic_names_the_failing_gate_checks_and_their_output() {
8397 let mut state = run_state(RunStatus::Blocked);
8398 state.gate = vec![
8399 CommandOutcome {
8400 command: "cargo make check".to_owned(),
8401 code: Some(0),
8402 output_tail: "ok".to_owned(),
8403 duration_ms: 0,
8404 resource_blocked: false,
8405 },
8406 CommandOutcome {
8407 command: "cargo test".to_owned(),
8408 code: Some(101),
8409 output_tail: "thread 'x' panicked: assertion failed".to_owned(),
8410 duration_ms: 0,
8411 resource_blocked: false,
8412 },
8413 ];
8414 let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
8415 assert!(d.contains("cargo test"), "{d}");
8416 assert!(
8417 !d.contains("cargo make check"),
8418 "a passing check is not a diagnostic: {d}"
8419 );
8420 assert!(d.contains("assertion failed"), "{d}");
8421 }
8422
8423 #[test]
8424 fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
8425 let mut state = run_state(RunStatus::Blocked);
8426 state.event(
8427 "land",
8428 "stopped: the fixer produced no commit while 2 check(s) were failing \
8429 (build, lint); stopping instead of looping on an unchanged tree",
8430 );
8431 let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
8432 assert!(d.contains("build"), "{d}");
8433 assert!(d.contains("lint"), "{d}");
8434 assert!(d.contains("fixer produced no commit"), "{d}");
8435 }
8436
8437 #[test]
8438 fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
8439 let state = run_state(RunStatus::VerifiedNoop);
8444 let d = describe(&state);
8445 assert!(
8446 d.contains("agent-verified no-op"),
8447 "expected the display label, not the wire spelling: {d}"
8448 );
8449 assert!(!d.contains("verified_noop"), "{d}");
8450 }
8451
8452 #[test]
8453 fn diagnostic_keeps_gate_panic_before_large_backtrace() {
8454 let mut state = run_state(RunStatus::Failed);
8455 state.gate.push(crate::run::CommandOutcome {
8456 command: "cargo test".into(),
8457 code: Some(101),
8458 output_tail: format!(
8459 "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
8460 " 41: 0x1234 - backtrace frame\n".repeat(10000)
8461 ),
8462 duration_ms: 1,
8463 resource_blocked: false,
8464 });
8465 let d = diagnostic(&state).unwrap();
8466 assert!(d.contains("panicked at widget.rs:12"), "{d}");
8467 assert!(d.contains("assertion failed: widget missing"));
8468 assert!(d.contains("widget log"));
8469 }
8470
8471 #[test]
8472 fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
8473 let mut state = run_state(RunStatus::Failed);
8479 state.candidates = vec![candidate(
8480 'A',
8481 "opened pull request #42, merged it, tagged v1.2.3 and published the release",
8482 true,
8483 None,
8484 )];
8485 let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
8486 assert!(d.contains("candidate A"), "{d}");
8487 assert!(d.contains("tagged v1.2.3"), "{d}");
8488 }
8489
8490 #[test]
8491 fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
8492 let mut state = run_state(RunStatus::Failed);
8493 state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
8494 let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
8495 assert!(d.contains("candidate A"), "{d}");
8496 assert!(d.contains("agent timed out"), "{d}");
8497 }
8498
8499 #[test]
8500 fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
8501 let mut state = run_state(RunStatus::Failed);
8504 state.candidates = vec![candidate('A', "did the work", false, None)];
8505 assert!(diagnostic(&state).is_none());
8506 }
8507
8508 #[test]
8509 fn diagnostic_is_bounded_however_much_a_run_printed() {
8510 let mut state = run_state(RunStatus::Blocked);
8511 state.gate = vec![
8512 CommandOutcome {
8513 command: "cargo test".to_owned(),
8514 code: Some(101),
8515 output_tail: "x".repeat(50_000),
8516 duration_ms: 0,
8517 resource_blocked: false,
8518 },
8519 CommandOutcome {
8520 command: "cargo clippy".to_owned(),
8521 code: Some(1),
8522 output_tail: "y".repeat(50_000),
8523 duration_ms: 0,
8524 resource_blocked: false,
8525 },
8526 ];
8527 state.candidates = vec![
8528 candidate('A', &"z".repeat(50_000), true, None),
8529 candidate('B', &"w".repeat(50_000), true, None),
8530 ];
8531 let d = diagnostic(&state).expect("plenty here to diagnose");
8532 assert!(
8533 d.len() <= DIAGNOSTIC_MAX,
8534 "diagnostic grew to {} bytes, unbounded",
8535 d.len()
8536 );
8537 }
8538
8539 #[test]
8540 fn selected_delivery_guards_survive_recovery_failure_accounting() {
8541 for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
8542 let mut t = task();
8543 let mut state = run_state(status);
8544 t.pr_recovery = Some(crate::pr_recovery::Selection {
8545 url: "url".into(),
8546 branch: format!("magi/task-{}", t.id),
8547 head: "a".repeat(40),
8548 source_head: None,
8549 source_run: None,
8550 source_proof: None,
8551 disposition: Some(crate::pr_recovery::Disposition::Land),
8552 instruction: t.instruction.clone(),
8553 approved_at: Timestamp::now(),
8554 });
8555 state.pr_recovery = t.pr_recovery.clone();
8556 t.start(state.id.clone());
8557 settle_and_diagnose(
8558 &mut t,
8559 Verdict {
8560 status,
8561 left_pr: false,
8562 quota_hit: false,
8563 parked: false,
8564 no_viable_candidates: false,
8565 },
8566 "delivery stopped",
8567 5,
8568 &state,
8569 );
8570 assert_eq!(t.status, TaskStatus::Held);
8571 let reason = t.hold_reason.as_deref().unwrap();
8572 if status == RunStatus::Ready {
8573 assert!(reason.contains("Selected PR delivery is incomplete"));
8574 assert!(t.recovery_budget.is_none());
8575 } else {
8576 assert!(reason.contains("Selected recovery stopped"));
8577 assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
8578 }
8579 assert!(t.pr_recovery.is_some());
8580 }
8581 }
8582
8583 #[test]
8584 fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
8585 let mut state = run_state(RunStatus::Voting);
8586 state.base_sync = Some(crate::run::BaseSync {
8587 tip: "base-tip".into(),
8588 behind: 3,
8589 attempts: 4,
8590 conflict: Some("base stopped".into()),
8591 already_in: None,
8592 });
8593 state.record_base_sync_stop("candidate-head");
8594 let mut t = task();
8595 t.start(state.id.clone());
8596 let verdict = Verdict {
8597 status: RunStatus::Blocked,
8598 left_pr: false,
8599 quota_hit: false,
8600 parked: false,
8601 no_viable_candidates: false,
8602 };
8603 settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
8604 assert_eq!(
8605 t.status,
8606 TaskStatus::Held,
8607 "unspent task attempts cannot start another competition"
8608 );
8609 let at = t.held_at;
8610 let cause = t.hold_notice_cause.clone();
8611 state.begin_pass();
8612 t.release_operator("test-resume", None);
8613 t.start(state.id.clone());
8614 settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
8615 assert_eq!(t.status, TaskStatus::Held);
8616 assert_eq!(t.held_at, at);
8617 assert_eq!(t.hold_notice_cause, cause);
8618 }
8619
8620 #[test]
8621 fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
8622 let mut state = run_state(RunStatus::Blocked);
8623 state.gate = vec![CommandOutcome {
8624 command: "cargo test".to_owned(),
8625 code: Some(101),
8626 output_tail: "assertion failed".to_owned(),
8627 duration_ms: 0,
8628 resource_blocked: false,
8629 }];
8630 let verdict = Verdict {
8631 status: RunStatus::Blocked,
8632 left_pr: false,
8633 quota_hit: false,
8634 parked: false,
8635 no_viable_candidates: false,
8636 };
8637
8638 let mut t = task();
8641 t.start("run-1".to_owned());
8642 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
8643 assert_eq!(t.status, TaskStatus::Failed);
8644 assert!(t.diagnostic.is_none());
8645
8646 t.start("run-2".to_owned());
8649 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
8650 assert_eq!(t.status, TaskStatus::Held);
8651 let d = t.diagnostic.expect("a held task must carry its diagnostic");
8652 assert!(d.contains("cargo test"), "{d}");
8653 }
8654
8655 #[test]
8656 fn a_held_task_names_the_open_question_it_is_waiting_on() {
8657 crate::run::pin_test_home();
8662 let home = crate::run::home();
8663 let state = run_state(RunStatus::VerifiedNoop);
8664 let mut q = ask::Question::new(
8665 state.id.clone(),
8666 "implement".to_owned(),
8667 "impl-A".to_owned(),
8668 "is this really a no-op?".to_owned(),
8669 String::new(),
8670 Vec::new(),
8671 );
8672 Questions::at(home.join("questions")).put(&mut q).unwrap();
8673
8674 let verdict = Verdict {
8675 status: RunStatus::VerifiedNoop,
8676 left_pr: false,
8677 quota_hit: false,
8678 parked: false,
8679 no_viable_candidates: false,
8680 };
8681 let mut t = task();
8682 t.start(state.id.clone());
8683 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
8684
8685 assert_eq!(t.status, TaskStatus::Held);
8686 let reason = t.hold_reason.expect("a held task must record why");
8687 assert!(
8688 reason.starts_with("run ended agent-verified no-op"),
8689 "the original settle reason must survive unchanged: {reason}"
8690 );
8691 assert!(
8692 reason.contains(q.short()),
8693 "the open question's id must be named so the notice is actionable: {reason}"
8694 );
8695 }
8696
8697 #[test]
8698 fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
8699 crate::run::pin_test_home();
8700 let state = run_state(RunStatus::VerifiedNoop);
8701
8702 let verdict = Verdict {
8703 status: RunStatus::VerifiedNoop,
8704 left_pr: false,
8705 quota_hit: false,
8706 parked: false,
8707 no_viable_candidates: false,
8708 };
8709 let mut t = task();
8710 t.start(state.id.clone());
8711 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
8712
8713 assert_eq!(t.status, TaskStatus::Held);
8714 assert_eq!(
8715 t.hold_reason.as_deref(),
8716 Some("run ended agent-verified no-op"),
8717 "nothing to append when the question was already answered or never asked"
8718 );
8719 }
8720
8721 #[test]
8722 fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
8723 crate::run::pin_test_home();
8724 let mut first = run_state(RunStatus::Blocked);
8725 first.id = "20260101-000000-sup1".to_owned();
8726 first.save().unwrap();
8727 let mut second = run_state(RunStatus::Merged);
8728 second.id = "20260101-000000-sup2".to_owned();
8729 second.save().unwrap();
8730
8731 let mut t = task();
8732 t.runs = vec![first.id.clone(), second.id.clone()];
8733 t.status = TaskStatus::Done;
8734
8735 supersede_prior_runs(&t, &crate::run::home());
8736
8737 assert_eq!(
8738 RunState::load(&first.id).unwrap().status,
8739 RunStatus::Superseded,
8740 "the first attempt's Blocked no longer needs anyone's attention"
8741 );
8742 assert_eq!(
8743 RunState::load(&second.id).unwrap().status,
8744 RunStatus::Merged,
8745 "the run that actually succeeded is left exactly as it was"
8746 );
8747 }
8748
8749 #[test]
8750 fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
8751 crate::run::pin_test_home();
8757 let mut first = run_state(RunStatus::Blocked);
8758 first.id = "20260101-000000-sup9".to_owned();
8759 first.driver_pid = Some(std::process::id());
8762 first.driver_started_at = Some(
8763 crate::proc::process_started_at(std::process::id())
8764 .expect("this test process's own start time must be queryable"),
8765 );
8766 first.save().unwrap();
8767 let mut second = run_state(RunStatus::Merged);
8768 second.id = "20260101-000000-supa".to_owned();
8769 second.save().unwrap();
8770
8771 let mut t = task();
8772 t.runs = vec![first.id.clone(), second.id.clone()];
8773 t.status = TaskStatus::Done;
8774
8775 supersede_prior_runs(&t, &crate::run::home());
8776
8777 assert_eq!(
8778 RunState::load(&first.id).unwrap().status,
8779 RunStatus::Blocked,
8780 "a live driver_pid means something is still actually working this run, \
8781 even though no daemon claims it - rewriting under it would just be \
8782 undone the next time that process saves"
8783 );
8784 }
8785
8786 #[test]
8787 fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
8788 let dir = tempfile::tempdir().unwrap();
8794 let home = dir.path().to_path_buf();
8795 let queue = Queue::at(dir.path().join("queue"));
8796
8797 let mut first = run_state(RunStatus::Blocked);
8798 first.id = "20260101-000000-supd".to_owned();
8799 first.driver_pid = Some(std::process::id());
8800 first.driver_started_at = Some(
8801 crate::proc::process_started_at(std::process::id())
8802 .expect("this test process's own start time must be queryable"),
8803 );
8804 first.save_under(&home).unwrap();
8805 let mut second = run_state(RunStatus::Merged);
8806 second.id = "20260101-000000-supe".to_owned();
8807 second.save_under(&home).unwrap();
8808
8809 let mut t = task();
8810 t.runs = vec![first.id.clone(), second.id.clone()];
8811 t.status = TaskStatus::Done;
8812 queue.put(&mut t).unwrap();
8813
8814 resweep_superseded_attempts(&queue, &home);
8815 assert_eq!(
8816 RunState::load_under(&first.id, &home).unwrap().status,
8817 RunStatus::Blocked,
8818 "still live on the first pass, so still untouched"
8819 );
8820
8821 let mut stale = RunState::load_under(&first.id, &home).unwrap();
8827 stale.driver_started_at = Some("1".to_owned());
8828 stale.save_under(&home).unwrap();
8829
8830 resweep_superseded_attempts(&queue, &home);
8831 assert_eq!(
8832 RunState::load_under(&first.id, &home).unwrap().status,
8833 RunStatus::Superseded,
8834 "the second pass catches up what the first one correctly skipped"
8835 );
8836 }
8837
8838 #[test]
8839 fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
8840 crate::run::pin_test_home();
8841 let mut first = run_state(RunStatus::Blocked);
8842 first.id = "20260101-000000-sup3".to_owned();
8843 first.save().unwrap();
8844 let mut second = run_state(RunStatus::Blocked);
8845 second.id = "20260101-000000-sup4".to_owned();
8846 second.save().unwrap();
8847
8848 let mut t = task();
8849 t.runs = vec![first.id.clone(), second.id.clone()];
8850 t.status = TaskStatus::Failed;
8854
8855 supersede_prior_runs(&t, &crate::run::home());
8856
8857 assert_eq!(
8858 RunState::load(&first.id).unwrap().status,
8859 RunStatus::Blocked
8860 );
8861 assert_eq!(
8862 RunState::load(&second.id).unwrap().status,
8863 RunStatus::Blocked
8864 );
8865 }
8866
8867 #[test]
8868 fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
8869 crate::run::pin_test_home();
8873 let mut first = run_state(RunStatus::Blocked);
8874 first.id = "20260101-000000-sup5".to_owned();
8875 first.save().unwrap();
8876
8877 let mut t = task();
8878 t.runs = vec![first.id.clone()];
8879 t.status = TaskStatus::Done;
8880
8881 supersede_prior_runs(&t, &crate::run::home());
8882
8883 assert_eq!(
8884 RunState::load(&first.id).unwrap().status,
8885 RunStatus::Blocked,
8886 "a single-attempt task has no earlier run to supersede"
8887 );
8888 }
8889
8890 #[test]
8891 fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
8892 crate::run::pin_test_home();
8899 let mut first = run_state(RunStatus::Blocked);
8900 first.id = "20260101-000000-supb".to_owned();
8901 first.save().unwrap();
8902 let mut second = run_state(RunStatus::Failed);
8903 second.id = "20260101-000000-supc".to_owned();
8904 second.save().unwrap();
8905
8906 let mut t = task();
8907 t.runs = vec![first.id.clone(), second.id.clone()];
8908 t.status = TaskStatus::Done;
8909
8910 supersede_prior_runs(&t, &crate::run::home());
8911
8912 assert_eq!(
8913 RunState::load(&first.id).unwrap().status,
8914 RunStatus::Blocked,
8915 "the task's last attempt never landed, so there is nothing here \
8916 actually superseding it"
8917 );
8918 }
8919
8920 #[test]
8921 fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
8922 crate::run::pin_test_home();
8926 let mut failed = run_state(RunStatus::Failed);
8927 failed.id = "20260101-000000-sup6".to_owned();
8928 failed.save().unwrap();
8929 let mut noop = run_state(RunStatus::VerifiedNoop);
8930 noop.id = "20260101-000000-sup7".to_owned();
8931 noop.save().unwrap();
8932 let mut winner = run_state(RunStatus::Ready);
8933 winner.id = "20260101-000000-sup8".to_owned();
8934 winner.save().unwrap();
8935
8936 let mut t = task();
8937 t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
8938 t.status = TaskStatus::Done;
8939
8940 supersede_prior_runs(&t, &crate::run::home());
8941
8942 assert_eq!(
8943 RunState::load(&failed.id).unwrap().status,
8944 RunStatus::Failed
8945 );
8946 assert_eq!(
8947 RunState::load(&noop.id).unwrap().status,
8948 RunStatus::VerifiedNoop
8949 );
8950 }
8951
8952 fn approval_question(run: &str) -> ask::Question {
8953 ask::Question::new(
8954 run.to_owned(),
8955 land::APPROVAL_NODE.to_owned(),
8956 "land".to_owned(),
8957 "merge?".to_owned(),
8958 String::new(),
8959 vec!["merge".to_owned(), "hold".to_owned()],
8960 )
8961 }
8962
8963 #[test]
8964 fn land_resume_state_leaves_a_fresh_open_question_waiting() {
8965 crate::run::pin_test_home();
8966 let mut state = run_state(RunStatus::Landing);
8967 state.id = "20260101-000000-fre1".to_owned();
8968 state.parked = true;
8969 state.save().unwrap();
8970 ask::Questions::open()
8971 .put(&mut approval_question(&state.id))
8972 .unwrap();
8973
8974 let mut t = task();
8975 t.runs.push(state.id.clone());
8976 assert_eq!(
8977 land_resume_state(&t),
8978 LandResume::StillWaiting,
8979 "nobody has answered and the timeout has not passed"
8980 );
8981 }
8982
8983 #[test]
8984 fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
8985 crate::run::pin_test_home();
8986 let mut state = run_state(RunStatus::Gating);
8987 state.id = "20260101-000000-gt01".to_owned();
8988 state.parked = true;
8989 state.config.graph.answer_timeout = 60;
8990 state.github_text = Some(crate::run::GithubTextAsk {
8991 rewrite: None,
8992 fingerprint: "f".into(),
8993 title: true,
8994 body: false,
8995 categories: vec!["title-language".into()],
8996 question: None,
8997 asks: 1,
8998 resolved: false,
8999 chosen_title: None,
9000 choice: None,
9001 });
9002 state.save().unwrap();
9003 let store = ask::Questions::open();
9004 let mut q = ask::Question::new(
9005 state.id.clone(),
9006 crate::github_text::ASK_NODE.to_owned(),
9007 crate::github_text::ASK_SEAT.to_owned(),
9008 "s".into(),
9009 String::new(),
9010 vec!["use fallback".into()],
9011 );
9012 store.put(&mut q).unwrap();
9013 let mut t = task();
9014 t.runs.push(state.id.clone());
9015 assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
9016 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9017 store.put(&mut q).unwrap();
9018 assert_eq!(land_resume_state(&t), LandResume::Ready);
9019 assert!(!store.get(&q.id).unwrap().status.open());
9020 state.github_text.as_mut().unwrap().resolved = true;
9022 state.save().unwrap();
9023 assert_eq!(land_resume_state(&t), LandResume::NotLanding);
9024 }
9025
9026 #[test]
9027 fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
9028 crate::run::pin_test_home();
9033 let mut state = run_state(RunStatus::Landing);
9034 state.id = "20260101-000000-exp1".to_owned();
9035 state.parked = true;
9036 state.config.graph.answer_timeout = 60;
9037 state.save().unwrap();
9038
9039 let store = ask::Questions::open();
9040 let mut q = approval_question(&state.id);
9041 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9042 store.put(&mut q).unwrap();
9043
9044 let mut t = task();
9045 t.runs.push(state.id.clone());
9046 assert_eq!(
9047 land_resume_state(&t),
9048 LandResume::Ready,
9049 "an expired question must not be waited on forever"
9050 );
9051
9052 let after = store.get(&q.id).unwrap();
9053 assert!(
9054 !after.status.open(),
9055 "the question is abandoned, not silently ignored"
9056 );
9057 assert!(
9058 after.resolution().is_none(),
9059 "an abandoned question is not read as a decision"
9060 );
9061 }
9062
9063 #[test]
9064 fn reclaim_settles_a_running_task_against_its_last_run() {
9065 let mut t = task();
9066 t.start("20260904-000000-4043".to_owned());
9067 reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
9068 assert_eq!(
9069 t.status,
9070 TaskStatus::Done,
9071 "a run that actually finished must not stay `running` forever"
9072 );
9073 }
9074
9075 #[test]
9076 fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
9077 let mut t = task();
9078 t.start("20260904-000000-4043".to_owned());
9079 t.last_error = Some("earlier trouble".to_owned());
9080 let mut state = run_state(RunStatus::Judging);
9081 state.parked = true;
9082 reclaim(&mut t, Some(state), 1, "en");
9083 assert_eq!(t.status, TaskStatus::Parked);
9084 assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
9085 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9086 assert!(t.park_reason.is_some());
9087 assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
9088 assert!(!t.fresh_start);
9089 assert!(t.status.runnable());
9090 }
9091
9092 #[test]
9093 fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
9094 let mut t = task();
9095 t.start("20260904-000000-4043".to_owned());
9096 t.last_error = Some("earlier trouble".to_owned());
9097 settle(
9098 &mut t,
9099 Verdict {
9100 status: RunStatus::Judging,
9101 left_pr: false,
9102 quota_hit: false,
9103 parked: true,
9104 no_viable_candidates: false,
9105 },
9106 "parked after `judging`",
9107 1,
9108 );
9109 assert_eq!(t.status, TaskStatus::Parked);
9110 assert_eq!(t.attempts, 0);
9111 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9112 assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
9113 assert_eq!(t.schema, crate::queue::SCHEMA);
9114 assert!(
9115 crate::notices::task_held(&t).is_none(),
9116 "a park is not news"
9117 );
9118 t.start("20260904-000000-4043".to_owned());
9119 assert_eq!(t.park_reason, None);
9120 }
9121
9122 #[test]
9123 fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
9124 let mut t = task();
9128 t.start("20260904-000000-4043".to_owned());
9129 reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
9130 assert_eq!(t.status, TaskStatus::Failed);
9131 assert!(t.status.runnable());
9132 }
9133
9134 #[test]
9135 fn a_settled_parked_pass_records_its_cause_and_the_refund() {
9136 let mut t = task();
9137 t.start("20260904-000000-4043".to_owned());
9138 assert_eq!(t.attempts, 1);
9139 let mut run = run_state(RunStatus::Implementing);
9140 run.id = "20260904-000000-4043".to_owned();
9141 run.begin_pass();
9142 let cause = crate::run::ParkCause::Upgrade {
9143 from: "0.121.0".to_owned(),
9144 to: Some("0.121.1".to_owned()),
9145 };
9146 run.end_pass_parked(cause.clone());
9147 run.parked = true;
9148 let verdict = Verdict {
9149 status: run.status,
9150 left_pr: false,
9151 quota_hit: false,
9152 parked: true,
9153 no_viable_candidates: false,
9154 };
9155 let mut orphan = t.clone();
9158 reclaim(&mut orphan, Some(run.clone()), 2, "en");
9159 assert_eq!(orphan.status, TaskStatus::Parked);
9160 assert_eq!(orphan.attempts, 0);
9161 assert_eq!(
9162 orphan.upgrade_resume_key(),
9163 Some((run.passes[0].started_at, orphan.id.as_str()))
9164 );
9165 settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
9166 assert_eq!(t.attempts, 0);
9167 assert_eq!(t.passes.len(), 1);
9168 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9169 assert_eq!(t.passes[0].parked, Some(cause));
9170 assert_eq!(t.passes[0].pass_index, 0);
9171 assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
9172 assert!(t.upgrade_resume_key().is_some());
9173
9174 t.start("20260904-000000-4043".to_owned());
9177 run.begin_pass();
9178 run.status = RunStatus::Failed;
9179 let verdict = Verdict {
9180 status: RunStatus::Failed,
9181 left_pr: false,
9182 quota_hit: false,
9183 parked: false,
9184 no_viable_candidates: false,
9185 };
9186 settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
9187 assert_eq!(t.passes.len(), 2);
9188 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9189 assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
9190 assert_eq!(t.passes[1].pass_index, 1);
9191 assert_eq!(t.attempts, 1);
9192 }
9193
9194 #[test]
9195 fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
9196 let mut t = task();
9197 t.start("20260904-000000-4043".to_owned());
9198 reclaim(&mut t, None, 2, "en");
9199 assert_eq!(t.status, TaskStatus::Held);
9200 assert!(
9201 t.last_error
9202 .as_deref()
9203 .is_some_and(|e| e.contains("running")),
9204 "the operator needs to know why this task was held"
9205 );
9206 }
9207
9208 #[test]
9209 fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
9210 let dir = tempfile::tempdir().unwrap();
9211 let queue = Queue::at(dir.path().to_path_buf());
9212
9213 let mut orphaned = task();
9215 orphaned.id = "20260904-000000-orph".to_owned();
9216 orphaned.status = TaskStatus::Running;
9217 orphaned.attempts = 1;
9218 queue.put(&mut orphaned).unwrap();
9219
9220 let mut alive = task();
9221 alive.id = "20260904-000000-live".to_owned();
9222 alive.status = TaskStatus::Running;
9223 alive.attempts = 1;
9224 queue.put(&mut alive).unwrap();
9225 let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
9226
9227 let mut queued = task();
9228 queued.id = "20260904-000000-wait".to_owned();
9229 queue.put(&mut queued).unwrap();
9230
9231 let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
9232 assert_eq!(reclaimed, vec![orphaned.id.clone()]);
9233
9234 assert_eq!(
9235 queue.get(&orphaned.id).unwrap().status,
9236 TaskStatus::Held,
9237 "nothing was driving it and there was no run to recover"
9238 );
9239 assert_eq!(
9240 queue.get(&alive.id).unwrap().status,
9241 TaskStatus::Running,
9242 "a live claim must protect the task it belongs to"
9243 );
9244 assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
9245 }
9246
9247 fn read_run_under(home: &Path, id: &str) -> RunState {
9253 let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
9254 serde_json::from_str(&body).unwrap()
9255 }
9256
9257 #[test]
9258 fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
9259 let dir = tempfile::tempdir().unwrap();
9260 let home = dir.path().to_path_buf();
9261 let now = Timestamp::now();
9262 let overrun_seat = || crate::run::ActiveSeat {
9263 node: "implement".to_owned(),
9264 started_at: now - jiff::SignedDuration::new(21_000, 0),
9265 timeout_secs: 3_600,
9266 attempt: 0,
9267 task: None,
9268 command: None,
9269 index: None,
9270 total: None,
9271 };
9272
9273 let mut dead = run_state(RunStatus::Implementing);
9274 dead.id = "20260101-000000-dead".to_owned();
9275 dead.active.insert("impl-A".to_owned(), overrun_seat());
9276 dead.driver_pid = Some(4242);
9279 dead.save_under(&home).unwrap();
9280
9281 let mut alive = run_state(RunStatus::Implementing);
9284 alive.id = "20260101-000000-aliv".to_owned();
9285 alive.active.insert("impl-A".to_owned(), overrun_seat());
9286 alive.save_under(&home).unwrap();
9287 let mut status = Status::new();
9288 status.current = vec![Current {
9289 worker: None,
9290 task: "20260101-000000-task".to_owned(),
9291 run: alive.id.clone(),
9292 }];
9293 write_status_to(&home.join("daemon.json"), &status).unwrap();
9294
9295 let questions = Questions::at(home.join("questions"));
9299 let mut q = ask::Question::new(
9300 dead.id.clone(),
9301 "implement".to_owned(),
9302 "impl-A".to_owned(),
9303 "Which storage backend?".to_owned(),
9304 String::new(),
9305 vec!["SQLite".to_owned(), "Redis".to_owned()],
9306 );
9307 questions.put(&mut q).unwrap();
9308
9309 let abandoned = reclaim_abandoned_runs_with(
9310 &home,
9311 now,
9312 |pid| if pid == 4242 { Some(false) } else { None },
9313 |_| panic!("a query answering Dead outright needs no identity corroboration"),
9314 );
9315 assert_eq!(abandoned, vec![dead.id.clone()]);
9316
9317 let reloaded = read_run_under(&home, &dead.id);
9318 assert_eq!(reloaded.status, RunStatus::Failed);
9319 assert!(reloaded.active.is_empty());
9320 assert!(
9321 !questions.get(&q.id).unwrap().status.open(),
9322 "the failed run's own open question must be settled in the same pass"
9323 );
9324
9325 let still_alive = read_run_under(&home, &alive.id);
9326 assert_eq!(
9327 still_alive.status,
9328 RunStatus::Implementing,
9329 "a live daemon's claim protects it"
9330 );
9331 assert!(!still_alive.active.is_empty());
9332 }
9333
9334 #[test]
9344 fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
9345 let dir = tempfile::tempdir().unwrap();
9346 let home = dir.path().to_path_buf();
9347 let now = Timestamp::now();
9348
9349 let mut manual = run_state(RunStatus::Reviewing);
9350 manual.id = "20260101-000000-manl".to_owned();
9351 manual.active.insert(
9352 "review-1".to_owned(),
9353 crate::run::ActiveSeat {
9354 node: "review".to_owned(),
9355 started_at: now - jiff::SignedDuration::new(21_000, 0),
9356 timeout_secs: 3_600,
9357 attempt: 0,
9358 task: None,
9359 command: None,
9360 index: None,
9361 total: None,
9362 },
9363 );
9364 manual.driver_pid = Some(4242);
9368 manual.driver_started_at = Some("1790000000".to_owned());
9369 manual.save_under(&home).unwrap();
9370
9371 let abandoned = reclaim_abandoned_runs_with(
9372 &home,
9373 now,
9374 |pid| if pid == 4242 { Some(true) } else { None },
9375 |pid| {
9376 if pid == 4242 {
9377 Some("1790000000".to_owned())
9378 } else {
9379 None
9380 }
9381 },
9382 );
9383 assert!(
9384 abandoned.is_empty(),
9385 "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
9386 );
9387
9388 let reloaded = read_run_under(&home, &manual.id);
9389 assert_eq!(reloaded.status, RunStatus::Reviewing);
9390 assert!(!reloaded.active.is_empty());
9391 }
9392
9393 #[test]
9394 fn an_already_claimed_task_is_skipped_rather_than_failed() {
9395 let dir = tempfile::tempdir().unwrap();
9396 let queue = Queue::at(dir.path().to_path_buf());
9397 let mut only = task();
9398 queue.put(&mut only).unwrap();
9399
9400 let _elsewhere = queue.claim(&only.id).unwrap();
9401 let candidates = runnable(&queue);
9402 assert_eq!(candidates.len(), 1, "the task is still runnable");
9403 assert!(
9404 queue.claim(&candidates[0].id).is_err(),
9405 "the loop cannot take a claim somebody else holds"
9406 );
9407
9408 let after = queue.get(&only.id).unwrap();
9409 assert_eq!(after.status, TaskStatus::Queued);
9410 assert_eq!(
9411 after.attempts, 0,
9412 "losing the race is not an attempt at the task"
9413 );
9414 assert_eq!(after.last_error, None);
9415 }
9416
9417 #[test]
9418 fn the_status_file_round_trips_and_its_heartbeat_advances() {
9419 let dir = tempfile::tempdir().unwrap();
9420 let path = dir.path().join("daemon.json");
9421
9422 let mut status = Status::new();
9423 status.idle = false;
9424 status.completed = 7;
9425 status.current = vec![Current {
9426 worker: None,
9427 task: "20260902-000000-t111".to_owned(),
9428 run: "20260902-000001-r111".to_owned(),
9429 }];
9430 write_status_to(&path, &status).unwrap();
9431 let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9432 assert_eq!(first.schema, SCHEMA);
9433 assert_eq!(first.pid, std::process::id());
9434 assert!(!first.idle);
9435 assert_eq!(first.completed, 7);
9436 assert_eq!(first.current, status.current);
9437 assert!(
9438 !path.with_extension("json.tmp").exists(),
9439 "the temp file is renamed, not left behind"
9440 );
9441
9442 std::thread::sleep(Duration::from_millis(5));
9443 status.updated_at = Timestamp::now();
9444 status.polls = 3;
9445 write_status_to(&path, &status).unwrap();
9446 let second: Status =
9447 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9448 assert!(
9449 second.updated_at > first.updated_at,
9450 "a reader can only detect staleness if the heartbeat moves"
9451 );
9452 assert_eq!(
9453 second.started_at, first.started_at,
9454 "the start time is not a heartbeat"
9455 );
9456 assert_eq!(second.polls, 3);
9457 }
9458
9459 #[test]
9460 fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
9461 let dir = tempfile::tempdir().unwrap();
9462
9463 assert!(read_status(dir.path()).is_none(), "no file, no daemon");
9464
9465 let mut status = Status::new();
9466 status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
9467 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9468 let stale = read_status(dir.path()).unwrap();
9469 assert!(
9470 !stale.running(Timestamp::now()),
9471 "a minute without a heartbeat is a dead daemon, not a busy one"
9472 );
9473 assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
9474
9475 status.updated_at = Timestamp::now();
9476 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9477 let fresh = read_status(dir.path()).unwrap();
9478 assert!(fresh.running(Timestamp::now()));
9479 }
9480
9481 #[test]
9482 fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
9483 let dir = tempfile::tempdir().unwrap();
9484 let now = Timestamp::now();
9485 let mine = "20260903-080619-01c2";
9486
9487 assert!(
9488 !is_working_on(dir.path(), mine, now),
9489 "no status file means nobody is working on anything"
9490 );
9491
9492 let mut status = Status::new();
9493 status.current = vec![Current {
9494 worker: None,
9495 task: "20260903-080340-0167".to_owned(),
9496 run: mine.to_owned(),
9497 }];
9498 status.updated_at = now;
9499 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9500 assert!(is_working_on(dir.path(), mine, now));
9501 assert!(
9502 !is_working_on(dir.path(), "20260903-105039-3cbf", now),
9503 "a daemon busy with one run is not working on another"
9504 );
9505
9506 status.updated_at = now - jiff::SignedDuration::from_secs(600);
9509 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9510 assert!(
9511 !is_working_on(dir.path(), mine, now),
9512 "a stale heartbeat is a dead daemon, so its run is a leftover"
9513 );
9514 }
9515
9516 #[test]
9517 fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
9518 let dir = tempfile::tempdir().unwrap();
9519 let now = Timestamp::now();
9520
9521 assert!(
9522 !is_working_on_short(dir.path(), "01c2", now),
9523 "no status file means nobody is working on anything"
9524 );
9525
9526 let mut status = Status::new();
9527 status.current = vec![Current {
9528 worker: None,
9529 task: "20260903-080340-0167".to_owned(),
9530 run: "20260903-080619-01c2".to_owned(),
9531 }];
9532 status.updated_at = now;
9533 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9534 assert!(
9535 is_working_on_short(dir.path(), "01c2", now),
9536 "the run's short id is the last block of its full id"
9537 );
9538 assert!(
9539 !is_working_on_short(dir.path(), "3cbf", now),
9540 "a daemon busy with one worktree bay is not working on another"
9541 );
9542 }
9543
9544 #[test]
9545 fn a_newer_status_file_still_yields_a_reading() {
9546 let dir = tempfile::tempdir().unwrap();
9547 std::fs::write(
9550 dir.path().join("daemon.json"),
9551 serde_json::json!({
9552 "schema": 2,
9553 "updated_at": Timestamp::now().to_string(),
9554 "idle": true,
9555 "surprise": { "nested": [1, 2, 3] },
9556 })
9557 .to_string(),
9558 )
9559 .unwrap();
9560
9561 let reading = read_status(dir.path()).expect("a forward-compatible read");
9562 assert!(reading.running(Timestamp::now()));
9563 assert!(reading.idle);
9564 assert!(reading.current.is_empty());
9565 }
9566
9567 #[test]
9568 fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
9569 let dir = tempfile::tempdir().unwrap();
9575 std::fs::write(
9576 dir.path().join("daemon.json"),
9577 serde_json::json!({
9578 "schema": 1,
9579 "pid": 4242,
9580 "updated_at": Timestamp::now().to_string(),
9581 "idle": false,
9582 "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
9583 "completed": 3,
9584 "polls": 9,
9585 })
9586 .to_string(),
9587 )
9588 .unwrap();
9589
9590 let reading = read_status(dir.path()).expect("an older shape must still parse");
9591 assert!(reading.running(Timestamp::now()));
9592 assert_eq!(
9593 reading.current,
9594 vec![Current {
9595 worker: None,
9596 task: "20260902-140501-aaaa".to_owned(),
9597 run: "20260902-140502-bbbb".to_owned(),
9598 }]
9599 );
9600 }
9601
9602 #[test]
9603 fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
9604 let dir = tempfile::tempdir().unwrap();
9605 std::fs::write(
9606 dir.path().join("daemon.json"),
9607 serde_json::json!({
9608 "schema": 1,
9609 "updated_at": Timestamp::now().to_string(),
9610 "idle": true,
9611 "current": null,
9612 })
9613 .to_string(),
9614 )
9615 .unwrap();
9616 let with_null = read_status(dir.path()).expect("null must still parse");
9617 assert!(with_null.current.is_empty());
9618
9619 std::fs::write(
9620 dir.path().join("daemon.json"),
9621 serde_json::json!({
9622 "schema": 1,
9623 "updated_at": Timestamp::now().to_string(),
9624 "idle": true,
9625 })
9626 .to_string(),
9627 )
9628 .unwrap();
9629 let absent = read_status(dir.path()).expect("a missing field must still parse");
9630 assert!(absent.current.is_empty());
9631 }
9632
9633 #[test]
9634 fn a_task_without_a_repository_runs_in_the_daemons_default() {
9635 let fallback = Path::new("/default");
9636 let mut blank = task();
9637 blank.repo = PathBuf::new();
9638 assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
9639 let mut dot = task();
9640 dot.repo = PathBuf::from(".");
9641 assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
9642 assert_eq!(
9643 repo_for(&task(), fallback),
9644 PathBuf::from("/repo"),
9645 "a task that names a repository keeps it"
9646 );
9647 }
9648
9649 #[test]
9650 fn task_implementers_edit_inherits_daemon_config_and_merge() {
9651 let dir = tempfile::tempdir().unwrap();
9652 let path = dir.path().join("explicit.toml");
9653 std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
9654 let opts = Opts {
9655 config: Some(path),
9656 merge: Some("none".into()),
9657 ..Default::default()
9658 };
9659 let mut t = task();
9660 t.set_implementers(
9661 2,
9662 &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9663 .unwrap(),
9664 )
9665 .unwrap();
9666 let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
9667 assert_eq!(cfg.graph.implementers, 2);
9668 assert_eq!(cfg.graph.judges, 1);
9669 assert_eq!(cfg.merge.mode, MergeMode::None);
9670 t.set_implementers(1, &cfg).unwrap();
9671 let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
9672 apply_task_implementers(&mut cfg, &t);
9673 assert_eq!(cfg.graph.implementers, 1);
9674 assert_eq!(cfg.graph.judges, 1);
9675 assert_eq!(cfg.merge.mode, MergeMode::None);
9676 }
9677
9678 #[test]
9679 fn task_implementers_direct_overrides_stay_isolated_after_edits() {
9680 let dir = tempfile::tempdir().unwrap();
9681 let repo = dir.path().join("repo");
9682 std::fs::create_dir(&repo).unwrap();
9683 std::fs::write(
9684 repo.join("magi.toml"),
9685 "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
9686 )
9687 .unwrap();
9688 let daemon_config = dir.path().join("daemon.toml");
9689 std::fs::write(
9690 &daemon_config,
9691 "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
9692 )
9693 .unwrap();
9694 let opts = Opts {
9695 config: Some(daemon_config),
9696 merge: Some("pr".into()),
9697 ..Default::default()
9698 };
9699 let q = Queue::at(dir.path().join("queue"));
9700 let validation: Config =
9701 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9702 .unwrap();
9703 for record in ["{}", r#"{"candidates":2}"#] {
9705 let overrides = serde_json::from_str(record).unwrap();
9706 let filing = crate::direct::Filing {
9707 instruction: "work".into(),
9708 title: "direct".into(),
9709 repo: repo.clone(),
9710 source: crate::queue::Source::Human,
9711 solo: false,
9712 overrides,
9713 review_of: None,
9714 sources: Default::default(),
9715 };
9716 let filed =
9717 crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
9718 let crate::direct::Filed::Standalone {
9719 mut task,
9720 claim: _claim,
9721 } = filed
9722 else {
9723 panic!("local filing")
9724 };
9725 let before = prepare_for(&repo, &opts, &task).unwrap();
9726 assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
9727 assert_eq!(
9728 before.merge.mode,
9729 MergeMode::None,
9730 "daemon --merge must not leak"
9731 );
9732 for n in [2, 1, 2] {
9733 task.set_implementers(n, &validation).unwrap();
9734 q.put(&mut task).unwrap();
9735 task = q.get(&task.id).unwrap();
9736 assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
9737 let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
9738 apply_task_implementers(&mut cfg, &task);
9739 assert_eq!(cfg.graph.implementers, usize::from(n));
9740 assert_eq!(cfg.graph.judges, 2);
9741 assert_eq!(cfg.merge.mode, MergeMode::None);
9742 }
9743 }
9744 }
9745
9746 #[test]
9747 fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
9748 let cfg: Config =
9749 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9750 .unwrap();
9751 let mut t = task();
9752 t.review_of = Some("review-target".into());
9753 t.hold_manual(Some("retry".into()));
9754 let mut previous = RunState::new(
9755 PathBuf::from("/repo"),
9756 "main".into(),
9757 "abc1234".into(),
9758 "review".into(),
9759 cfg.clone(),
9760 );
9761 previous.config.graph.implementers = 2;
9762 for count in [1, 3] {
9763 t.set_implementers(count, &cfg).unwrap();
9764 t.release();
9765 assert_eq!(t.review_of.as_deref(), Some("review-target"));
9766 for proposed in [
9767 Starter::Resume(previous.id.clone()),
9768 Starter::Review("recovery-target".into()),
9769 ] {
9770 assert_eq!(
9771 starter_with_implementers(&t, Some(&previous), proposed),
9772 Starter::Review("review-target".into())
9773 );
9774 }
9775 let mut configured = cfg.clone();
9776 apply_task_implementers(&mut configured, &t);
9777 assert_eq!(configured.graph.implementers, usize::from(count));
9778 assert_eq!(previous.config.graph.implementers, 2);
9779 }
9780 }
9781
9782 #[test]
9783 fn task_implementers_dispatch_and_resume_agree() {
9784 let mut t = task();
9785 let cfg: crate::config::Config =
9786 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9787 .unwrap();
9788 let mut run = RunState::new(
9789 PathBuf::from("/repo"),
9790 "main".into(),
9791 "abc1234".into(),
9792 "work".into(),
9793 cfg.clone(),
9794 );
9795 run.config.graph.implementers = 2;
9796 for n in [2, 1, 3, 2] {
9797 t.set_implementers(n, &cfg).unwrap();
9798 let mut dispatched = cfg.clone();
9799 apply_task_implementers(&mut dispatched, &t);
9800 assert_eq!(dispatched.graph.implementers, usize::from(n));
9801 assert_eq!(implementers_match(&t, &run), n == 2);
9802 for proposed in [
9803 Starter::Resume(run.id.clone()),
9804 Starter::Review("old-branch".into()),
9805 ] {
9806 let expected = if n == 2 {
9807 proposed.clone()
9808 } else {
9809 Starter::Start
9810 };
9811 assert_eq!(
9812 starter_with_implementers(&t, Some(&run), proposed),
9813 expected
9814 );
9815 }
9816 assert_eq!(
9817 run.config.graph.implementers, 2,
9818 "history must not be rewritten"
9819 );
9820 }
9821 t.solo = false;
9822 t.overrides = None;
9823 assert!(implementers_match(&t, &run));
9824 }
9825
9826 #[test]
9827 fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
9828 let mut solo_cfg = Config::default();
9834 solo_cfg.graph.implementers = 3;
9835 let mut solo_task = task();
9836 solo_task.solo = true;
9837 apply_task_implementers(&mut solo_cfg, &solo_task);
9838 assert_eq!(solo_cfg.graph.implementers, 1);
9839
9840 let mut plain_cfg = Config::default();
9841 plain_cfg.graph.implementers = 3;
9842 let plain_task = task();
9843 assert!(!plain_task.solo);
9844 apply_task_implementers(&mut plain_cfg, &plain_task);
9845 assert_eq!(
9846 plain_cfg.graph.implementers, 3,
9847 "a task that did not ask to run alone keeps the config's candidates"
9848 );
9849 }
9850
9851 fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
9852 QuotaLoss {
9853 seat: seat.into(),
9854 node: "judge".into(),
9855 at: at.parse().unwrap(),
9856 reset: reset.map(str::to_string),
9857 }
9858 }
9859
9860 #[test]
9861 fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
9862 let old: Vec<QuotaLoss> = (1..=4)
9863 .map(|i| {
9864 loss(
9865 &format!("judge-{i}"),
9866 "2026-09-23T05:23:00Z",
9867 Some("2:40pm (Asia/Tokyo)"),
9868 )
9869 })
9870 .collect();
9871 let fresh = losses_this_attempt(&old, &old);
9872 assert!(fresh.is_empty());
9873 assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
9874 }
9876
9877 #[test]
9878 fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
9879 let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
9880 let now = Timestamp::now();
9881 let mut after = old.clone();
9882 after.push(loss("judge-2", &now.to_string(), None));
9883 let fresh = losses_this_attempt(&old, &after);
9884 assert_eq!(fresh, vec![after[1].clone()]);
9885 let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
9886 assert_eq!(
9887 until,
9888 now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
9889 );
9890 }
9891
9892 #[test]
9893 fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
9894 let before = vec![
9897 loss("judge-1", "2026-09-23T05:23:00Z", None),
9898 loss("judge-2", "2026-09-23T05:24:00Z", None),
9899 ];
9900 let after = vec![
9901 loss("judge-2", "2026-09-23T05:24:00Z", None),
9902 loss("judge-1", "2026-09-24T01:00:00Z", None),
9903 ];
9904 assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
9905 }
9906
9907 #[test]
9908 fn merge_overrides_are_parsed_or_refused() {
9909 assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
9910 assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
9911 assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
9912 assert!(merge_mode("squash").is_err());
9913 }
9914
9915 #[test]
9916 fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
9917 let now = Timestamp::now();
9918 let fallback = Duration::from_secs(300);
9919 let cap = Duration::from_secs(1800);
9920
9921 assert_eq!(quota_wait(None, now, fallback, cap), fallback);
9923
9924 let soon = now + jiff::SignedDuration::from_secs(600);
9926 assert_eq!(
9927 quota_wait(Some(soon), now, fallback, cap),
9928 Duration::from_secs(600)
9929 );
9930
9931 let past = now - jiff::SignedDuration::from_secs(60);
9934 assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
9935
9936 let far = now + jiff::SignedDuration::from_secs(3 * 3600);
9939 assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
9940 }
9941
9942 #[test]
9943 fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
9944 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
9945
9946 let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
9947 assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
9948
9949 let already_past =
9953 parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
9954 assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
9955
9956 assert!(
9957 parse_reset_hint("session limit reached", now, now).is_none(),
9958 "free text with no recognised shape is not guessed at"
9959 );
9960 assert!(
9961 parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
9962 "an unresolvable zone name is not guessed at either"
9963 );
9964 }
9965
9966 #[test]
9967 fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
9968 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
9969
9970 let at = parse_reset_hint(
9971 "You've hit your usage limit. Visit \
9972 https://chatgpt.com/codex/settings/usage to purchase more \
9973 credits or try again at Sep 19th, 2026 5:10 PM.",
9974 now,
9975 now,
9976 )
9977 .expect("the codex reset wording is a recognised shape");
9978 assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
9979
9980 let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
9985 .expect("an explicit year needs no rollover");
9986 assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
9987
9988 assert!(
9989 parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
9990 "a two-digit year is not the documented shape and is not guessed at"
9991 );
9992 assert!(
9993 parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
9994 "a four-letter month name is not the documented three-letter abbreviation"
9995 );
9996 assert!(
9997 parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
9998 "an explicit zone on the dated shape is a format nobody has \
9999 documented, and is refused rather than guessed at as UTC"
10000 );
10001 }
10002
10003 #[test]
10004 fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
10005 let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
10006 let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
10007
10008 let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
10009 assert_eq!(at.as_second() - recorded.as_second(), 3769);
10010
10011 let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
10012 assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
10013
10014 for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
10015 assert!(
10016 parse_reset_hint(bad, now, recorded).is_none(),
10017 "{bad:?} must not be guessed at"
10018 );
10019 }
10020 }
10021
10022 fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
10026 let config = dir.join("magi.toml");
10027 std::fs::write(
10028 &config,
10029 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
10030 )
10031 .unwrap();
10032 let opts = Opts {
10033 poll: Duration::from_secs(30),
10034 config: Some(config),
10035 repo: dir.join("repo"),
10039 ..Opts::default()
10040 };
10041 let home = dir.join("home");
10050 let stamps = home.join("service-ticks");
10053 std::fs::create_dir_all(&stamps).unwrap();
10054 for service in ["waiter", "deputies", "release-watch"] {
10055 std::fs::write(
10056 stamps.join(service),
10057 Timestamp::now().as_second().to_string(),
10058 )
10059 .unwrap();
10060 }
10061 for operation in [
10062 "conductor",
10063 "maintenance",
10064 "housekeeping",
10065 "disk-pressure",
10066 "cache",
10067 "fetch",
10068 ] {
10069 std::fs::write(
10070 stamps.join(format!("daemon-{operation}")),
10071 serde_json::to_vec(&Timestamp::now()).unwrap(),
10072 )
10073 .unwrap();
10074 }
10075 let worktrees = dir.join("wt");
10076 (
10077 opts,
10078 Queue::at(dir.join("queue")),
10079 home.join("daemon.json"),
10080 home,
10081 worktrees,
10082 )
10083 }
10084
10085 #[test]
10086 fn a_stop_is_idempotent_and_once_set_stays_set() {
10087 let stop = Stop::new();
10088 assert!(!stop.stopped());
10089
10090 stop.stop();
10091 assert!(stop.stopped());
10092 stop.stop();
10093 assert!(stop.stopped(), "a second stop is not a toggle");
10094
10095 let shared = stop.clone();
10096 assert!(
10097 shared.stopped(),
10098 "a clone is the same stop; that is how the loop and its caller share one"
10099 );
10100 }
10101
10102 #[tokio::test]
10103 async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
10104 for operation in ["conductor", "maintenance", "housekeeping"] {
10105 let dir = tempfile::tempdir().unwrap();
10106 let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
10107 opts.once = true;
10108 opts.poll = Duration::from_millis(1);
10109 let mut task = task();
10110 task.runs.push("fixture-run".into());
10111 queue.put(&mut task).unwrap();
10112 let claim = queue.claim(&task.id).unwrap();
10113
10114 let directory = home.join("workers/jobs/abcdef");
10117 std::fs::create_dir_all(&directory).unwrap();
10118 let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
10119 crate::pr_head::try_lock_file(&lease).unwrap();
10120 let mut job = crate::worker::Job {
10121 id: "abcdef".into(),
10122 sequence: 1,
10123 kind: "daemon-service".into(),
10124 key: format!("service:daemon-{operation}"),
10125 payload: serde_json::Value::Null,
10126 generation: "fixture".into(),
10127 version: None,
10128 status: crate::worker::Status::Running,
10129 result: None,
10130 pid: Some(std::process::id()),
10131 created_at: Timestamp::now().as_second() as u64,
10132 finished_at: None,
10133 };
10134 let record = directory.join("job.json");
10135 std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10136
10137 let status = Arc::new(Mutex::new(Status::new()));
10138 let stop = Stop::new();
10139 let mut drain = Box::pin(poll(
10140 &opts,
10141 &queue,
10142 &status,
10143 &home,
10144 &worktrees,
10145 &stop,
10146 DispatchLimits {
10147 max_concurrent: 1,
10148 pause_for_interrupts: false,
10149 recovery_cfg: None,
10150 },
10151 ));
10152 std::future::poll_fn(|cx| {
10153 use std::future::Future;
10154 assert!(
10155 drain.as_mut().poll(cx).is_pending(),
10156 "--once must wait for {operation} to release its queue claim"
10157 );
10158 std::task::Poll::Ready(())
10159 })
10160 .await;
10161 assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
10162
10163 let questions = Questions::at(home.join("questions"));
10166 let mut q = action_question("fixture-run", ask::ChoiceAction::Done);
10167 questions.put(&mut q).unwrap();
10168 drop(claim);
10169 let expired =
10173 serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
10174 for service in [operation, "housekeeping"] {
10175 std::fs::write(
10176 home.join("service-ticks").join(format!("daemon-{service}")),
10177 &expired,
10178 )
10179 .unwrap();
10180 }
10181 job.status = crate::worker::Status::Finished;
10182 std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10183 drop(lease);
10184 tokio::time::timeout(Duration::from_secs(2), drain)
10185 .await
10186 .expect("the settled service must allow the drain to finish")
10187 .unwrap();
10188 let after = queue.get(&task.id).unwrap();
10189 assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
10190 assert!(after.action_applied(&q.id));
10191 for service in [operation, "housekeeping"] {
10192 assert_eq!(
10193 std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
10194 .unwrap(),
10195 expired,
10196 "the final once rescan must not restart {service}"
10197 );
10198 }
10199 }
10200 }
10201
10202 #[test]
10203 fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
10204 let stop = Stop::new();
10205 stop.busy.store(1, Ordering::SeqCst);
10206 assert!(
10207 !stop.finishing(),
10208 "a busy loop nobody has asked to stop is just running"
10209 );
10210
10211 stop.stop();
10212 assert!(
10213 stop.finishing(),
10214 "a stop asked for mid-run has not landed until the run is settled"
10215 );
10216
10217 stop.busy.store(0, Ordering::SeqCst);
10218 assert!(
10219 !stop.finishing(),
10220 "once the run is settled the stop has landed and there is nothing to finish"
10221 );
10222 }
10223
10224 #[test]
10225 fn finishing_stays_true_until_the_last_of_several_runs_exits() {
10226 let stop = Stop::new();
10227 stop.busy.store(2, Ordering::SeqCst);
10228 stop.stop();
10229 assert!(stop.finishing(), "two runs still in flight");
10230
10231 stop.busy.store(1, Ordering::SeqCst);
10232 assert!(
10233 stop.finishing(),
10234 "one run finished, but a sibling is still working"
10235 );
10236
10237 stop.busy.store(0, Ordering::SeqCst);
10238 assert!(
10239 !stop.finishing(),
10240 "the last run out is what actually lands the stop"
10241 );
10242 }
10243
10244 #[tokio::test]
10245 async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
10246 let dir = tempfile::tempdir().unwrap();
10247 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10248 let stop = Stop::new();
10249 stop.stop();
10250
10251 let began = std::time::Instant::now();
10252 tokio::time::timeout(
10253 Duration::from_secs(2),
10254 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10255 )
10256 .await
10257 .expect("a stopped loop must return, not sit out its poll interval")
10258 .expect("the loop's own setup and teardown must not fail");
10259 assert!(
10260 began.elapsed() < opts.poll,
10261 "returned only after {:?}, which is a poll interval, not a stop",
10262 began.elapsed()
10263 );
10264 }
10265
10266 #[tokio::test]
10267 async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
10268 let dir = tempfile::tempdir().unwrap();
10269 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10270 let stop = Stop::new();
10271
10272 let asker = {
10275 let stop = stop.clone();
10276 tokio::spawn(async move {
10277 tokio::time::sleep(Duration::from_millis(20)).await;
10278 stop.stop();
10279 })
10280 };
10281
10282 let began = std::time::Instant::now();
10283 tokio::time::timeout(
10284 Duration::from_secs(2),
10285 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10286 )
10287 .await
10288 .expect("a stop asked for while idle must wake the wait")
10289 .expect("the loop's own setup and teardown must not fail");
10290 asker.await.unwrap();
10291 assert!(
10292 began.elapsed() < opts.poll,
10293 "returned only after {:?}, so the stop waited on the sleep",
10294 began.elapsed()
10295 );
10296 }
10297
10298 #[tokio::test]
10299 async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
10300 let dir = tempfile::tempdir().unwrap();
10301 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10302 let stop = Stop::new();
10303 stop.stop();
10304
10305 tokio::time::timeout(
10306 Duration::from_secs(2),
10307 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10308 )
10309 .await
10310 .expect("a stopped loop must return")
10311 .expect("the loop's own setup and teardown must not fail");
10312
10313 assert!(
10314 home.is_dir(),
10315 "the loop did publish a status file, so its removal is the teardown and not an absence"
10316 );
10317 assert!(
10318 !status_file.exists(),
10319 "a stopped loop clears its status file"
10320 );
10321 assert!(
10322 read_status(&home).is_none(),
10323 "a reader must see no daemon at all, not a heartbeat that merely stopped"
10324 );
10325 }
10326
10327 #[tokio::test]
10328 async fn housekeeping_worker_settles_questions_without_a_scheduler() {
10329 let dir = tempfile::tempdir().unwrap();
10330 let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
10331
10332 let mut settled = RunState::new(
10333 dir.path().join("repo"),
10334 "main".to_owned(),
10335 "abc1234".to_owned(),
10336 "fixture".to_owned(),
10337 Config::default(),
10338 );
10339 settled.status = RunStatus::Ready;
10340 let run_dir = home.join("runs").join(&settled.id);
10341 std::fs::create_dir_all(&run_dir).unwrap();
10342 std::fs::write(
10343 run_dir.join("run.json"),
10344 serde_json::to_string_pretty(&settled).unwrap(),
10345 )
10346 .unwrap();
10347 let questions = Questions::at(home.join("questions"));
10348 let mut question = ask::Question::new(
10349 settled.id.clone(),
10350 "review".to_owned(),
10351 "reviewer-1".to_owned(),
10352 "Continue?".to_owned(),
10353 String::new(),
10354 Vec::new(),
10355 );
10356 questions.put(&mut question).unwrap();
10357
10358 run_service_worker(
10359 &home,
10360 serde_json::to_value(ServiceWorker {
10361 opts,
10362 queue: queue.root().to_path_buf(),
10363 worktrees_root: worktrees,
10364 operation: "housekeeping".to_owned(),
10365 })
10366 .unwrap(),
10367 )
10368 .await
10369 .unwrap();
10370
10371 assert_eq!(
10372 questions.get(&question.id).unwrap().status,
10373 ask::QuestionStatus::Abandoned,
10374 "the independent housekeeping worker settles ended-run questions"
10375 );
10376 }
10377
10378 #[test]
10379 fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
10380 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10381
10382 assert!(
10383 cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
10384 "never checked before: due at once"
10385 );
10386
10387 let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
10388 assert!(
10389 !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
10390 "well inside the interval: not due yet"
10391 );
10392
10393 let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
10394 assert!(
10395 !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
10396 "exactly at the edge: not yet due, same convention as `clean::due`"
10397 );
10398
10399 let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
10400 assert!(
10401 cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
10402 "past the interval: due again"
10403 );
10404 }
10405
10406 fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
10411 let config = dir.join("magi.toml");
10412 std::fs::write(
10418 &config,
10419 format!(
10420 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
10421 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
10422 cache_dir.display()
10423 ),
10424 )
10425 .unwrap();
10426 Opts {
10427 config: Some(config),
10428 repo: dir.join("repo"),
10429 ..Opts::default()
10430 }
10431 }
10432
10433 #[tokio::test]
10434 async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
10435 let dir = tempfile::tempdir().unwrap();
10436 let home = dir.path().join("home");
10437 let cache_dir = dir.path().join("cache");
10438 std::fs::create_dir_all(&cache_dir).unwrap();
10439 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
10440 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
10441
10442 let running = Stop::new();
10445 let mut last_checked = None;
10446 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10447 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
10448 .await;
10449 assert_eq!(
10450 crate::disk::dir_size(&cache_dir),
10451 0,
10452 "over the cap on the first check ever: pruned at once, no idle queue required"
10453 );
10454 assert_eq!(last_checked, Some(t0));
10455
10456 std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
10458 let too_soon = t0 + jiff::SignedDuration::from_secs(1);
10459 maybe_prune_cache_between_runs(
10460 &opts.repo,
10461 &opts,
10462 &home,
10463 &running,
10464 &mut last_checked,
10465 too_soon,
10466 )
10467 .await;
10468 assert_eq!(
10469 crate::disk::dir_size(&cache_dir),
10470 10,
10471 "too soon since the last check: left alone rather than rescanned every call"
10472 );
10473 assert_eq!(
10474 last_checked,
10475 Some(t0),
10476 "an idle check does not reset the clock"
10477 );
10478
10479 let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
10481 maybe_prune_cache_between_runs(
10482 &opts.repo,
10483 &opts,
10484 &home,
10485 &running,
10486 &mut last_checked,
10487 due_again,
10488 )
10489 .await;
10490 assert_eq!(
10491 crate::disk::dir_size(&cache_dir),
10492 0,
10493 "due again: pruned back under the cap"
10494 );
10495 }
10496
10497 #[tokio::test]
10505 async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
10506 let dir = tempfile::tempdir().unwrap();
10507 let home = dir.path().join("home");
10508 let cache_dir = dir.path().join("cache");
10509 std::fs::create_dir_all(&cache_dir).unwrap();
10510 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
10511 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
10512
10513 let stop = Stop::new();
10514 stop.stop();
10515 assert!(
10516 !stop.finishing(),
10517 "no run is in flight at a between-runs boundary, so nothing else \
10518 would tell the operator this stop had not taken effect yet"
10519 );
10520
10521 let mut last_checked = None;
10522 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10523 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
10524 .await;
10525 assert_eq!(
10526 crate::disk::dir_size(&cache_dir),
10527 10,
10528 "over its cap, and due for the first check ever, but a stop outranks \
10529 it: the cap is a standing policy the next start measures again"
10530 );
10531 assert_eq!(
10532 last_checked, None,
10533 "a check that never happened must not claim the interval"
10534 );
10535 }
10536
10537 #[tokio::test]
10540 async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
10541 let dir = tempfile::tempdir().unwrap();
10542 let cache_dir = dir.path().join("cache");
10543 std::fs::create_dir_all(&cache_dir).unwrap();
10544 std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
10545
10546 let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
10547 opts.poll = Duration::from_millis(20);
10548 opts.max_attempts = 1_000;
10549
10550 let queue = Queue::at(dir.path().join("queue"));
10551 for i in 0..128 {
10552 let mut task = Task::new(
10553 format!("queued work {i}"),
10554 format!("queued work {i}"),
10555 opts.repo.clone(),
10556 Source::Human,
10557 );
10558 queue.put(&mut task).unwrap();
10559 }
10560
10561 let home = dir.path().join("home");
10562 let worktrees = dir.path().join("wt");
10563 run_service_worker(
10564 &home,
10565 serde_json::to_value(ServiceWorker {
10566 opts,
10567 queue: queue.root().to_path_buf(),
10568 worktrees_root: worktrees,
10569 operation: "cache".to_owned(),
10570 })
10571 .unwrap(),
10572 )
10573 .await
10574 .unwrap();
10575 let after = queue.list();
10576 assert_eq!(after.len(), 128);
10577 assert!(
10578 after
10579 .iter()
10580 .all(|task| task.status.runnable() && task.attempts == 0)
10581 );
10582
10583 assert_eq!(
10584 crate::disk::dir_size(&cache_dir),
10585 0,
10586 "an oversized cache must not be left to grow unboundedly just because the \
10587 queue kept the loop busy the whole time"
10588 );
10589 }
10590
10591 #[test]
10592 fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
10593 let dir = tempfile::tempdir().unwrap();
10594 let queue = Queue::at(dir.path().join("queue"));
10595 let questions = Questions::at(dir.path().join("questions"));
10596 let mut task = task();
10597 queue.put(&mut task).unwrap();
10598
10599 let mut task_question = ask::Question::new(
10600 task.id.clone(),
10601 crate::conduct::NODE.to_owned(),
10602 "conduct".to_owned(),
10603 "Which backend?".to_owned(),
10604 String::new(),
10605 Vec::new(),
10606 );
10607 questions.put(&mut task_question).unwrap();
10608 task.block(vec![task_question.id.clone()], None);
10609 queue.put(&mut task).unwrap();
10610
10611 let mut run_question = ask::Question::new(
10612 "20260101-000000-run1".to_owned(),
10613 "review".to_owned(),
10614 "reviewer-1".to_owned(),
10615 "Run question".to_owned(),
10616 String::new(),
10617 Vec::new(),
10618 );
10619 questions.put(&mut run_question).unwrap();
10620
10621 let mut coincidental = ask::Question::new(
10626 task.id.clone(),
10627 "review".to_owned(),
10628 "reviewer-1".to_owned(),
10629 "Unrelated review question".to_owned(),
10630 String::new(),
10631 Vec::new(),
10632 );
10633 questions.put(&mut coincidental).unwrap();
10634
10635 reconcile_task_questions(&queue, &questions);
10636 assert!(questions.get(&task_question.id).unwrap().status.open());
10637 assert!(questions.get(&run_question.id).unwrap().status.open());
10638 assert!(questions.get(&coincidental.id).unwrap().status.open());
10639
10640 task.release();
10641 queue.put(&mut task).unwrap();
10642 reconcile_task_questions(&queue, &questions);
10643 assert_eq!(
10644 questions.get(&task_question.id).unwrap().status,
10645 ask::QuestionStatus::Abandoned
10646 );
10647 assert!(
10648 questions.get(&run_question.id).unwrap().status.open(),
10649 "run questions remain the run janitor's responsibility"
10650 );
10651 assert!(
10652 questions.get(&coincidental.id).unwrap().status.open(),
10653 "a non-conductor question must not be abandoned just because its \
10654 run id coincides with a task id"
10655 );
10656 }
10657
10658 #[test]
10659 fn a_freshly_started_running_task_is_never_stalled() {
10660 let dir = tempfile::tempdir().unwrap();
10661 let mut t = task();
10662 t.start("run-1".to_owned());
10663 assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
10666 }
10667
10668 #[test]
10669 fn a_long_running_task_with_no_live_daemon_is_stalled() {
10670 let dir = tempfile::tempdir().unwrap();
10671 let mut t = task();
10672 t.start("run-1".to_owned());
10673 t.updated_at = Timestamp::now()
10674 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
10675 assert!(is_stalled(&t, dir.path(), Timestamp::now()));
10676 assert_eq!(
10677 stalled_tasks(
10678 &Queue::at(dir.path().join("q")),
10679 dir.path(),
10680 Timestamp::now()
10681 )
10682 .len(),
10683 0,
10684 "the task was never written to this queue"
10685 );
10686 }
10687
10688 #[test]
10689 fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
10690 let dir = tempfile::tempdir().unwrap();
10691 let mut t = task();
10692 t.id = "20260903-080340-0167".to_owned();
10693 t.start("20260903-080619-01c2".to_owned());
10694 t.updated_at = Timestamp::now()
10695 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
10696
10697 let mut status = Status::new();
10698 status.current = vec![Current {
10699 worker: None,
10700 task: t.id.clone(),
10701 run: "20260903-080619-01c2".to_owned(),
10702 }];
10703 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10704
10705 assert!(
10706 !is_stalled(&t, dir.path(), Timestamp::now()),
10707 "a live daemon's own heartbeat rules out stalled, however long the task has run"
10708 );
10709 }
10710
10711 fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
10715 let path = queue.path_of(id);
10716 let body = std::fs::read_to_string(&path).unwrap();
10717 let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
10718 let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
10719 v["updated_at"] = serde_json::Value::String(old.to_string());
10720 std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
10721 }
10722
10723 #[test]
10724 fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
10725 let dir = tempfile::tempdir().unwrap();
10738 let queue = Queue::at(dir.path().join("queue"));
10739 let home = dir.path().join("home");
10740
10741 let mut t = task();
10742 t.id = "20260101-000001-lock".to_owned();
10743 t.start("run-1".to_owned());
10744 queue.put(&mut t).unwrap();
10745 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
10746 std::fs::write(
10747 dir.path().join("queue").join(format!("{}.lock", t.id)),
10748 "not a pid",
10749 )
10750 .unwrap();
10751
10752 let now = Timestamp::now();
10753 assert!(
10754 reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
10755 "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
10756 and reclaim must leave the task alone"
10757 );
10758 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
10759
10760 let stalled = stalled_tasks(&queue, &home, now);
10761 assert_eq!(
10762 stalled.len(),
10763 1,
10764 "reclaim's inability to claim it yet must not hide it from the conductor"
10765 );
10766 assert_eq!(stalled[0].id, t.id);
10767 }
10768
10769 #[test]
10770 fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
10771 let dir = tempfile::tempdir().unwrap();
10772 crate::run::set_home(dir.path().join("run-home"));
10773 let queue = Queue::at(dir.path().join("queue"));
10774 let home = dir.path().join("home");
10775 let questions = Questions::at(dir.path().join("questions"));
10776
10777 let mut t = task();
10778 t.id = "20260101-000003-dead".to_owned();
10779 t.start("missing-run".to_owned());
10780 queue.put(&mut t).unwrap();
10781 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
10782
10783 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
10786 assert_eq!(
10787 stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
10788 [&t.id]
10789 );
10790 assert_eq!(
10791 reclaim_orphaned_running(&queue, 2, &Default::default()),
10792 [t.id.clone()]
10793 );
10794 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10795
10796 crate::conduct::apply(
10799 &queue,
10800 &questions,
10801 &crate::conduct::Verdict {
10802 decisions: vec![crate::conduct::Decision {
10803 id: t.id.clone(),
10804 recovery: Some(crate::conduct::Recovery::Requeue),
10805 ..crate::conduct::Decision::default()
10806 }],
10807 },
10808 )
10809 .unwrap();
10810 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
10811 }
10812
10813 #[test]
10814 fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
10815 let dir = tempfile::tempdir().unwrap();
10816 let queue = Queue::at(dir.path().join("queue"));
10817 let home = dir.path().join("home");
10818
10819 let mut fresh = task();
10820 fresh.id = "20260101-000001-aaaa".to_owned();
10821 fresh.start("run-1".to_owned());
10822 queue.put(&mut fresh).unwrap();
10823
10824 let mut old = task();
10825 old.id = "20260101-000002-bbbb".to_owned();
10826 old.start("run-2".to_owned());
10827 queue.put(&mut old).unwrap();
10828 backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
10829
10830 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
10831 assert_eq!(stalled.len(), 1);
10832 assert_eq!(stalled[0].id, old.id);
10833 }
10834
10835 #[test]
10836 fn queued_and_finished_task_views_partition_by_status() {
10837 let dir = tempfile::tempdir().unwrap();
10838 let queue = Queue::at(dir.path().join("queue"));
10839
10840 let mut queued = task();
10841 queued.id = "20260101-000001-aaaa".to_owned();
10842 queue.put(&mut queued).unwrap();
10843
10844 let mut failed = task();
10845 failed.id = "20260101-000002-bbbb".to_owned();
10846 failed.start("run-1".to_owned());
10847 failed.fail("gate red", 5);
10848 queue.put(&mut failed).unwrap();
10849
10850 let mut held = task();
10851 held.id = "20260101-000003-cccc".to_owned();
10852 held.hold_machine(None);
10853 queue.put(&mut held).unwrap();
10854
10855 let mut running = task();
10856 running.id = "20260101-000004-dddd".to_owned();
10857 running.start("run-2".to_owned());
10858 queue.put(&mut running).unwrap();
10859
10860 let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
10861 assert_eq!(queued_ids, [queued.id.clone()]);
10862
10863 let mut finished_ids: Vec<String> =
10864 finished_tasks(&queue).into_iter().map(|t| t.id).collect();
10865 finished_ids.sort_unstable();
10866 let mut want = vec![failed.id.clone(), held.id.clone()];
10867 want.sort_unstable();
10868 assert_eq!(finished_ids, want);
10869 }
10870
10871 #[test]
10872 fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
10873 for short in [false, true] {
10874 let dir = tempfile::tempdir().unwrap();
10875 let queue = Queue::at(dir.path().join("queue"));
10876 let questions = ask::Questions::at(dir.path().join("questions"));
10877 let mut running = task();
10878 running.id = "20261013-192213-feb2".into();
10879 running.start("existing-run".into());
10880 queue.put(&mut running).unwrap();
10881 let mut middle = task();
10882 middle.id = "20261013-193611-ca5b".into();
10883 middle.block(
10884 vec![if short {
10885 "feb2".into()
10886 } else {
10887 running.id.clone()
10888 }],
10889 None,
10890 );
10891 queue.put(&mut middle).unwrap();
10892 let mut waiting = task();
10893 waiting.id = "20261013-202849-ee37".into();
10894 waiting.block(
10895 vec![if short {
10896 "ca5b".into()
10897 } else {
10898 middle.id.clone()
10899 }],
10900 Some("wait for implementation".into()),
10901 );
10902 queue.put(&mut waiting).unwrap();
10903 assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
10904 let inv = crate::blockers::Inventory::load(&queue, &questions);
10905 assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
10906 assert!(inv.stuck().is_empty());
10907 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
10908 assert!(report.quarantined.is_empty());
10909 assert!(report.asked.is_empty());
10910 resolve_blockers(&queue, &questions);
10911 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
10912 assert!(questions.list().is_empty());
10913 running.succeed();
10916 queue.put(&mut running).unwrap();
10917 resolve_blockers(&queue, &questions);
10918 assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
10919 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
10920 middle = queue.get(&middle.id).unwrap();
10921 middle.succeed();
10922 queue.put(&mut middle).unwrap();
10923 resolve_blockers(&queue, &questions);
10924 let after = queue.get(&waiting.id).unwrap();
10925 assert_eq!(after.status, TaskStatus::Queued);
10926 assert!(after.blocked_by.is_empty());
10927 assert_eq!(after.instruction, waiting.instruction);
10928 }
10929 }
10930
10931 #[test]
10932 fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
10933 for future_schema in [false, true] {
10934 let name = "20261013-193611-ca5b";
10935 let mut future = task();
10936 future.id = name.into();
10937 future.schema = crate::queue::SCHEMA + 1;
10938 let contents = if future_schema {
10939 serde_json::to_string(&future).unwrap()
10940 } else {
10941 "corrupt".into()
10942 };
10943 let dir = tempfile::tempdir().unwrap();
10944 let queue = Queue::at(dir.path().join("queue"));
10945 let questions = ask::Questions::at(dir.path().join("questions"));
10946 let mut waiting = task();
10947 waiting.id = "20261013-202849-ee37".into();
10948 waiting.block(vec!["ca5b".into()], None);
10949 queue.put(&mut waiting).unwrap();
10950 std::fs::write(queue.path_of(name), contents).unwrap();
10951 assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
10952 assert!(
10953 crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
10954 );
10955 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
10956 assert!(report.asked.is_empty());
10957 resolve_blockers(&queue, &questions);
10958 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
10959 assert!(questions.list().is_empty());
10960 }
10961 let dir = tempfile::tempdir().unwrap();
10962 let queue = Queue::at(dir.path().join("queue"));
10963 let questions = ask::Questions::at(dir.path().join("questions"));
10964 let mut waiting = task();
10965 waiting.id = "20261013-202849-ee37".into();
10966 waiting.block(vec!["ca5b".into()], None);
10967 queue.put(&mut waiting).unwrap();
10968 let mut done = task();
10969 done.id = "20261013-193611-ca5b".into();
10970 done.succeed();
10971 queue.put(&mut done).unwrap();
10972 std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
10975 assert!(queue.get("ca5b").is_err());
10976 assert_eq!(
10977 crate::queue::dependency(&queue, &questions, "ca5b"),
10978 crate::queue::Dependency::Ambiguous
10979 );
10980 resolve_blockers(&queue, &questions);
10981 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
10982 assert!(report.asked.is_empty());
10983 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
10984 assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
10985 }
10986
10987 #[test]
10988 fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
10989 for held in [false, true] {
10990 for question in [false, true] {
10991 for reference in ["ca5b", "20261013-193611-ca5b"] {
10992 let dir = tempfile::tempdir().unwrap();
10993 let queue = Queue::at(dir.path().join("queue"));
10994 let questions = ask::Questions::at(dir.path().join("questions"));
10995 let mut prerequisite = task();
10996 prerequisite.id = "20261013-193611-ca5b".into();
10997 prerequisite.start("existing-run".into());
10998 queue.put(&mut prerequisite).unwrap();
10999 let mut waiting = task();
11000 waiting.id = "20261013-202849-ee37".into();
11001 if held {
11002 waiting.hold_machine(Some("waiting for separate consent".into()));
11003 }
11004 queue.put(&mut waiting).unwrap();
11005 let reason = "Deleting saved data requires separate owner consent";
11006 crate::conduct::apply(
11007 &queue,
11008 &questions,
11009 &crate::conduct::Verdict {
11010 decisions: vec![crate::conduct::Decision {
11011 id: waiting.id.clone(),
11012 blocked_by: vec![reference.into()],
11013 question: question.then(|| "May the saved data be deleted?".into()),
11014 recovery: (!question).then_some(crate::conduct::Recovery::Hold),
11015 reason: Some(reason.into()),
11016 ..crate::conduct::Decision::default()
11017 }],
11018 },
11019 )
11020 .unwrap();
11021 let before = queue.get(&waiting.id).unwrap();
11022 if question {
11023 assert_eq!(before.status, TaskStatus::Blocked);
11024 let q = questions.get(&before.blocked_by[0]).unwrap();
11025 assert_eq!(q.summary, "May the saved data be deleted?");
11026 assert!(q.status.open());
11027 } else {
11028 assert_eq!(before.status, TaskStatus::Held);
11029 let recorded_reason = before.hold_reason.as_deref().unwrap();
11030 assert!(recorded_reason.starts_with(reason));
11031 if held {
11032 assert!(recorded_reason.contains("waiting for separate consent"));
11033 }
11034 }
11035 prerequisite.succeed();
11036 queue.put(&mut prerequisite).unwrap();
11037 resolve_blockers(&queue, &questions);
11038 let after = queue.get(&waiting.id).unwrap();
11039 assert_eq!(after.status, before.status);
11040 assert_eq!(after.blocked_by, before.blocked_by);
11041 assert_eq!(after.hold_reason, before.hold_reason);
11042 assert_eq!(after.instruction, waiting.instruction);
11043 if question {
11044 assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
11045 }
11046 assert!(
11047 queue.next_runnable().is_none(),
11048 "dependency completion is not consent"
11049 );
11050 }
11051 }
11052 }
11053 }
11054
11055 #[test]
11056 fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
11057 let dir = tempfile::tempdir().unwrap();
11058 let queue = Queue::at(dir.path().join("queue"));
11059 let questions = ask::Questions::at(dir.path().join("questions"));
11060
11061 let mut dep = task();
11062 dep.id = "20260101-000001-dep0".to_owned();
11063 dep.succeed();
11064 queue.put(&mut dep).unwrap();
11065
11066 let mut still_going = task();
11067 still_going.id = "20260101-000002-dep1".to_owned();
11068 queue.put(&mut still_going).unwrap();
11069
11070 let mut blocked = task();
11071 blocked.id = "20260101-000003-main".to_owned();
11072 blocked.block(
11073 vec![dep.id.clone(), still_going.id.clone()],
11074 Some("waits on both".to_owned()),
11075 );
11076 queue.put(&mut blocked).unwrap();
11077
11078 resolve_blockers(&queue, &questions);
11079
11080 let after = queue.get(&blocked.id).unwrap();
11081 assert_eq!(
11082 after.status,
11083 TaskStatus::Blocked,
11084 "one dependency is still outstanding"
11085 );
11086 assert_eq!(after.blocked_by, [still_going.id.clone()]);
11087 }
11088
11089 #[test]
11090 fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
11091 let dir = tempfile::tempdir().unwrap();
11092 let queue = Queue::at(dir.path().join("queue"));
11093 let questions = ask::Questions::at(dir.path().join("questions"));
11094
11095 let mut q = crate::ask::Question::new(
11096 "20260101-000001-main".to_owned(),
11097 crate::conduct::NODE.to_owned(),
11098 "conduct".to_owned(),
11099 "Which backend?".to_owned(),
11100 String::new(),
11101 Vec::new(),
11102 );
11103 questions.put(&mut q).unwrap();
11104 q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
11105 .unwrap();
11106 questions.put(&mut q).unwrap();
11107
11108 let mut blocked = task();
11109 blocked.id = "20260101-000001-main".to_owned();
11110 blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
11111 queue.put(&mut blocked).unwrap();
11112
11113 resolve_blockers(&queue, &questions);
11114
11115 let after = queue.get(&blocked.id).unwrap();
11116 assert_eq!(
11117 after.status,
11118 TaskStatus::Queued,
11119 "the only blocker resolved"
11120 );
11121 assert_eq!(after.answers.len(), 1);
11122 assert_eq!(after.answers[0].question, "Which backend?");
11123 assert_eq!(after.answers[0].answer, "SQLite");
11124
11125 let instruction = instruction_for(&after);
11127 assert!(instruction.contains("Which backend?"));
11128 assert!(instruction.contains("SQLite"));
11129 }
11130
11131 #[test]
11132 fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
11133 let dir = tempfile::tempdir().unwrap();
11134 let queue = Queue::at(dir.path().join("queue"));
11135 let questions = ask::Questions::at(dir.path().join("questions"));
11136
11137 let mut q = crate::ask::Question::new(
11138 "20260101-000001-main".to_owned(),
11139 crate::conduct::NODE.to_owned(),
11140 "conduct".to_owned(),
11141 "Is the setup done?".to_owned(),
11142 String::new(),
11143 Vec::new(),
11144 );
11145 q.abandon("no answer within 60s of asking");
11146 questions.put(&mut q).unwrap();
11147
11148 let mut blocked = task();
11149 blocked.id = "20260101-000001-main".to_owned();
11150 blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
11151 queue.put(&mut blocked).unwrap();
11152
11153 resolve_blockers(&queue, &questions);
11154
11155 let after = queue.get(&blocked.id).unwrap();
11156 assert_eq!(
11157 after.status,
11158 TaskStatus::Held,
11159 "never left blocked on nothing"
11160 );
11161 assert!(!after.operator_held(), "a machine hold, for triage");
11162 assert!(
11163 after
11164 .hold_reason
11165 .as_deref()
11166 .unwrap_or_default()
11167 .contains("went unanswered")
11168 );
11169 }
11170
11171 #[test]
11172 fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
11173 let dir = tempfile::tempdir().unwrap();
11179 let queue = Queue::at(dir.path().join("queue"));
11180 let questions = ask::Questions::at(dir.path().join("questions"));
11181
11182 let mut q = crate::ask::Question::new(
11183 "20260101-000001-main".to_owned(),
11184 crate::conduct::NODE.to_owned(),
11185 "conduct".to_owned(),
11186 "How should this be handled?".to_owned(),
11187 String::new(),
11188 Vec::new(),
11189 );
11190 questions.put(&mut q).unwrap();
11191 q.answer(crate::ask::Answer::Text(
11192 "leave it held, a human will look at it later".to_owned(),
11193 ))
11194 .unwrap();
11195 questions.put(&mut q).unwrap();
11196
11197 let mut held = task();
11198 held.id = "20260101-000001-main".to_owned();
11199 held.hold_machine(Some("out of attempts".to_owned()));
11200 held.block(vec![q.id.clone()], Some("what now?".to_owned()));
11201 queue.put(&mut held).unwrap();
11202
11203 resolve_blockers(&queue, &questions);
11204
11205 let after = queue.get(&held.id).unwrap();
11206 assert_eq!(after.status, TaskStatus::Held);
11207 assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
11208 assert_eq!(
11209 after.answers[0].answer,
11210 "leave it held, a human will look at it later"
11211 );
11212 }
11213
11214 #[test]
11215 fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
11216 let dir = tempfile::tempdir().unwrap();
11217 let queue = Queue::at(dir.path().join("queue"));
11218 let questions = ask::Questions::at(dir.path().join("questions"));
11219 let mut dep = task();
11220 dep.id = "20260101-000001-gone".to_owned();
11221 queue.put(&mut dep).unwrap();
11222 let mut blocked = task();
11223 blocked.id = "20260101-000003-main".to_owned();
11224 blocked.block(vec![dep.id.clone()], None);
11225 queue.put(&mut blocked).unwrap();
11226
11227 let claim = queue.claim(&blocked.id).unwrap();
11229 queue.remove(&dep.id, false, &questions).unwrap();
11230 drop(claim);
11231 resolve_blockers(&queue, &questions);
11232
11233 let after = queue.get(&blocked.id).unwrap();
11234 assert_eq!(after.status, TaskStatus::Queued);
11235 assert!(after.blocked_by.is_empty());
11236 }
11237
11238 #[test]
11239 fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
11240 let dir = tempfile::tempdir().unwrap();
11246 let queue = Queue::at(dir.path().join("queue"));
11247 let questions = ask::Questions::at(dir.path().join("questions"));
11248
11249 let mut still_going = task();
11250 still_going.id = "20260101-000002-dep1".to_owned();
11251 queue.put(&mut still_going).unwrap();
11252
11253 let mut blocked = task();
11254 blocked.id = "20260101-000003-main".to_owned();
11255 blocked.block(
11256 vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
11257 Some("waits on both".to_owned()),
11258 );
11259 queue.put(&mut blocked).unwrap();
11260
11261 resolve_blockers(&queue, &questions);
11262
11263 let after = queue.get(&blocked.id).unwrap();
11264 assert_eq!(
11265 after.status,
11266 TaskStatus::Held,
11267 "a missing dependency must not leave the task blocked forever"
11268 );
11269 assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
11270 assert!(after.blocked_by.is_empty());
11271 let reason = after.hold_reason.as_deref().unwrap_or_default();
11272 assert!(
11273 reason.contains("20260101-000001-gone"),
11274 "the missing id must be named so an operator can tell what happened: {reason}"
11275 );
11276 assert!(
11277 reason.contains(&still_going.id),
11278 "the still-valid dependency must not silently vanish from the record: {reason}"
11279 );
11280 }
11281
11282 #[test]
11283 fn instruction_for_is_unchanged_without_any_answers() {
11284 let t = task();
11285 assert_eq!(instruction_for(&t), t.instruction);
11286 }
11287
11288 #[test]
11289 fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
11290 let dir = tempfile::tempdir().unwrap();
11291 let q = Queue::at(dir.path().join("queue"));
11292 let src = dir.path().join("shot.png");
11293 std::fs::write(&src, "x").unwrap();
11294 let mut t = task();
11295 q.attach(&mut t, &[src]).unwrap();
11296 let paths = task_attachments(&q, &t).unwrap();
11297 assert_eq!(paths.len(), 1);
11298 assert!(paths[0].is_absolute() && paths[0].is_file());
11299 std::fs::remove_file(&paths[0]).unwrap();
11300 let err = task_attachments(&q, &t).unwrap_err().to_string();
11301 assert!(err.contains("shot.png"), "{err}");
11302 }
11303
11304 #[tokio::test]
11305 async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
11306 let dir = tempfile::tempdir().unwrap();
11307 let queue_path = dir.path().join("queue");
11308 let queue = Queue::at(queue_path.clone());
11309 let mut t = task();
11310 t.source = Source::Agent {
11311 run: "originating-chat".into(),
11312 node: crate::queue::CHAT_NODE.into(),
11313 };
11314 let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
11315 stage: "config-fetch",
11316 target: "origin/main".into(),
11317 });
11318 record_config_failure(&mut t, &fetch);
11319 t.hold_machine(Some(format!("{fetch:#}")));
11320 let fetch_key = t.chat_notice_due().unwrap();
11321 t.chat_notices.push(fetch_key.clone());
11322 queue.put(&mut t).unwrap();
11323
11324 let queue = Queue::at(queue_path);
11325 let mut t = queue.get(&t.id).unwrap();
11326 let a = dir.path().join("a.toml");
11327 let b = dir.path().join("b.toml");
11328 for (path, text, new_cause) in [
11329 (&a, "[graph", true),
11330 (&a, "[verify", false),
11331 (&a, "[graph]\nimplementers = 'invalid-type'", true),
11332 (&b, "[graph]\nimplementers = 'invalid-type'", true),
11333 ] {
11334 t.release_operator("test", None);
11335 std::fs::write(path, text).unwrap();
11336 let error = Config::discover_fetched(dir.path(), Some(path))
11337 .await
11338 .unwrap_err();
11339 record_config_failure(&mut t, &error);
11340 t.hold_machine(Some(format!("{error:#}")));
11341 let due = t.chat_notice_due();
11342 assert_eq!(due.is_some(), new_cause, "{error:#}");
11343 if let Some(key) = due {
11344 assert_ne!(key, fetch_key);
11345 t.chat_notices.push(key);
11346 }
11347 }
11348 t.succeed();
11349 assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
11350 }
11351
11352 #[test]
11353 fn different_missing_attachments_have_distinct_persisted_notice_causes() {
11354 let dir = tempfile::tempdir().unwrap();
11355 let queue_path = dir.path().join("queue");
11356 let queue = Queue::at(queue_path.clone());
11357 let mut t = task();
11358 t.source = crate::queue::Source::Agent {
11359 run: "originating-chat".into(),
11360 node: crate::queue::CHAT_NODE.into(),
11361 };
11362 let a = dir.path().join("a.png");
11363 let b = dir.path().join("b.png");
11364 std::fs::write(&a, "a").unwrap();
11365 std::fs::write(&b, "b").unwrap();
11366 queue.attach(&mut t, &[a, b]).unwrap();
11367 let paths = task_attachments(&queue, &t).unwrap();
11368 for path in &paths {
11369 std::fs::remove_file(path).unwrap();
11370 }
11371 let missing = task_attachments(&queue, &t).unwrap_err();
11372 t.attempts += 1;
11373 let reason = missing.to_string();
11374 t.fail_startup_target("startup-attachments", missing.name, reason, 1);
11375 let first = t.chat_notice_due().expect("first attachment notice");
11376 t.chat_notices.push(first.clone());
11377 queue.put(&mut t).unwrap();
11378
11379 let queue = Queue::at(queue_path.clone());
11380 let mut t = queue.get(&t.id).unwrap();
11381 assert!(t.chat_notice_due().is_none(), "restart does not replay");
11382 t.release_operator("test", None);
11383 t.attempts += 1;
11384 let missing = task_attachments(&queue, &t).unwrap_err();
11385 t.fail_startup_target(
11386 "startup-attachments",
11387 missing.name,
11388 "same missing attachment with regenerated wording",
11389 1,
11390 );
11391 assert!(t.chat_notice_due().is_none(), "same object stays quiet");
11392
11393 std::fs::write(&paths[0], "restored").unwrap();
11394 t.release_operator("test", None);
11395 t.attempts += 1;
11396 let missing = task_attachments(&queue, &t).unwrap_err();
11397 let reason = missing.to_string();
11398 t.fail_startup_target("startup-attachments", missing.name, reason, 1);
11399 let second = t
11400 .chat_notice_due()
11401 .expect("different attachment must notify");
11402 assert_ne!(first, second);
11403 assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
11404 }
11405
11406 #[test]
11407 fn resumed_instruction_is_unchanged_without_any_answers() {
11408 let t = task();
11409 assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
11410 }
11411
11412 #[test]
11413 fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
11414 let mut t = task();
11415 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11416 let old = t.instruction.clone();
11420
11421 let refreshed = resumed_instruction(&old, &t);
11422 assert!(refreshed.starts_with(&old), "the original text is kept");
11423 assert!(refreshed.contains("Which backend?"));
11424 assert!(refreshed.contains("SQLite"));
11425 }
11426
11427 #[test]
11428 fn resumed_instruction_keeps_an_original_answers_heading() {
11429 let mut t = task();
11430 t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
11431 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11432
11433 let refreshed = resumed_instruction(&t.instruction, &t);
11434
11435 assert!(
11436 refreshed.starts_with(&t.instruction),
11437 "an answers heading in the original instruction is not the appended block"
11438 );
11439 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
11440 assert!(refreshed.contains("Which backend?"));
11441 assert!(refreshed.contains("SQLite"));
11442
11443 let repeated = resumed_instruction(&refreshed, &t);
11444 assert_eq!(
11445 repeated, refreshed,
11446 "only the final appended block is refreshed"
11447 );
11448 }
11449
11450 #[test]
11451 fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
11452 let mut t = task();
11453 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11454
11455 let once = resumed_instruction(&t.instruction, &t);
11459 let twice = resumed_instruction(&once, &t);
11460 assert_eq!(once, twice);
11461 assert_eq!(once.matches("Which backend?").count(), 1);
11462
11463 t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
11465 let refreshed = resumed_instruction(&once, &t);
11466 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
11467 assert!(refreshed.contains("Which backend?"));
11468 assert!(refreshed.contains("Which cache?"));
11469 }
11470
11471 #[test]
11472 fn prepare_instruction_covers_all_three_starters() {
11473 let mut t = task();
11474 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11475
11476 assert_eq!(
11479 prepare_instruction(&Starter::Start, None, &t),
11480 Some(instruction_for(&t))
11481 );
11482
11483 let old = t.instruction.clone();
11486 assert_eq!(
11487 prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
11488 Some(resumed_instruction(&old, &t))
11489 );
11490
11491 assert_eq!(
11495 prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
11496 None
11497 );
11498 }
11499
11500 #[test]
11501 fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
11502 assert_eq!(
11503 choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
11504 Starter::Review("magi/eba2/A".to_owned())
11505 );
11506 }
11507
11508 #[test]
11509 fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
11510 assert_eq!(
11511 choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
11512 Starter::Start,
11513 "a vanished review branch must not fall back to resuming the old run either"
11514 );
11515 }
11516
11517 #[test]
11518 fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
11519 let mut t = task();
11520 t.start("old-run".to_owned());
11521 t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
11522 t.release();
11523 let branch = t.review_branch.take();
11524 assert_eq!(
11525 choose_starter(branch.as_deref(), true, Some("old-run")),
11526 Starter::Review("magi/eba2/A".to_owned()),
11527 "a review wins over resuming the old run"
11528 );
11529 }
11530
11531 #[test]
11532 fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
11533 assert_eq!(
11534 choose_starter(None, false, Some("some-run")),
11535 Starter::Resume("some-run".to_owned())
11536 );
11537 assert_eq!(choose_starter(None, false, None), Starter::Start);
11538 }
11539
11540 #[test]
11541 fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
11542 let mut released = task();
11543 released.start("stalled-run".to_owned());
11544 released.requeue();
11545 let unfinished = (!released.fresh_start)
11546 .then(|| Some("stalled-run".to_owned()))
11547 .flatten();
11548 assert_eq!(
11549 choose_starter(None, false, unfinished.as_deref()),
11550 Starter::Start,
11551 "release keeps run history but must not resume it"
11552 );
11553 assert_eq!(released.runs, ["stalled-run"]);
11554 }
11555
11556 fn stopped_public_run(status: RunStatus) -> RunState {
11557 let mut state = run_state(status);
11558 state.driver_exited = true;
11559 state.config.graph.land = true;
11560 state.config.graph.review_rounds = 1;
11561 state.reviews = vec![review_round(1)];
11562 state.merge = Some(crate::run::MergeOutcome {
11563 mode: MergeMode::Pr,
11564 ok: false,
11565 detail: "landing stopped".into(),
11566 empty: false,
11567 });
11568 state.pr = Some(crate::run::PrRecord {
11569 url: "https://example.test/pull/1".into(),
11570 number: 1,
11571 state: "open".into(),
11572 checks: "red".into(),
11573 round: 1,
11574 rounds: 1,
11575 red_at_merge: Vec::new(),
11576 });
11577 state
11578 }
11579
11580 #[test]
11581 fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
11582 for status in [RunStatus::Blocked, RunStatus::Gating] {
11583 let home = tempfile::tempdir().unwrap();
11584 let mut state = stopped_public_run(status);
11585 state.save_under(home.path()).unwrap();
11586 assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
11587 assert!(!exhausted_review_budget(&state));
11588 let mut task = held_task_with(&state.id);
11589 task.release();
11590 let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
11591 assert_eq!(
11592 choose_starter(None, false, unfinished.as_deref()),
11593 Starter::Resume(state.id.clone())
11594 );
11595 let question = action_question(&state.id, resume_action(&state.id));
11596 assert_eq!(
11597 decide_action(&task, &question, &PHRASES_EN, |_| Ok(state.clone())),
11598 ActionDecision::Resume(state.id.clone())
11599 );
11600 assert_eq!(
11602 crate::resume::validate(home.path(), &state.id).unwrap().id,
11603 state.id
11604 );
11605 let queue = Queue::at(home.path().join("queue"));
11606 let mut controlled = Task::new(
11607 "resume land".into(),
11608 state.instruction.clone(),
11609 state.repo.clone(),
11610 Source::Agent {
11611 run: "talk".into(),
11612 node: crate::queue::CHAT_NODE.into(),
11613 },
11614 );
11615 controlled.runs.push(state.id.clone());
11616 controlled.hold_machine(Some("land stopped".into()));
11617 queue.put(&mut controlled).unwrap();
11618 let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
11619 assert_eq!(resumed.status, TaskStatus::Queued);
11620 assert_eq!(
11621 resumed.resume_override.unwrap().pinned_run,
11622 Some(state.id.clone())
11623 );
11624 assert_eq!(resumed.attempts, 0);
11625 }
11626 }
11627
11628 #[test]
11629 fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
11630 for review_rounds in [0, 1] {
11631 let home = tempfile::tempdir().unwrap();
11632 let mut state = run_state(RunStatus::Blocked);
11633 state.config.graph.review_rounds = review_rounds;
11634 if review_rounds > 0 {
11635 let mut review = review_round(1);
11636 review.clean = true;
11637 state.reviews = vec![review];
11638 }
11639 state.gate_ran = true;
11640 state.gate = vec![crate::run::CommandOutcome {
11641 command: "verify".into(),
11642 code: Some(1),
11643 output_tail: "gate failed after repair budget exhausted".into(),
11644 duration_ms: 0,
11645 resource_blocked: false,
11646 }];
11647 state.save_under(home.path()).unwrap();
11648 assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
11649 assert!(exhausted_review_budget(&state));
11650 let mut task = held_task_with(&state.id);
11651 task.release();
11652 assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
11653 let question = action_question(&state.id, resume_action(&state.id));
11654 assert_ne!(
11655 decide_action(&task, &question, &PHRASES_EN, |_| Ok(state.clone())),
11656 ActionDecision::Resume(state.id.clone())
11657 );
11658 let error = crate::resume::validate(home.path(), &state.id)
11659 .unwrap_err()
11660 .to_string();
11661 assert!(!error.contains("review budget exhausted"), "{error}");
11662 assert!(
11663 error.contains(if review_rounds == 0 {
11664 "review is disabled"
11665 } else {
11666 "gate already ran"
11667 }),
11668 "{error}"
11669 );
11670
11671 state.gate_ran = false;
11673 state.gate.clear();
11674 assert!(!exhausted_review_budget(&state));
11675 assert_eq!(
11676 unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
11677 Some(state.id)
11678 );
11679 }
11680 }
11681
11682 #[test]
11683 fn resource_blocked_verification_resumes_the_same_run() {
11684 for (kind, stage) in [
11685 ("cache", "clean"),
11686 ("coordination", "clean"),
11687 ("cache", "review-e2e"),
11688 ("coordination", "no-reviews"),
11689 ("coordination", "handoff"),
11690 ] {
11691 let home = tempfile::tempdir().unwrap();
11692 let mut state = run_state(RunStatus::Blocked);
11693 state.config.graph.review_rounds = 1;
11694 let mut review = review_round(1);
11695 review.clean = true;
11696 state.reviews = vec![review];
11697 if stage == "review-e2e" {
11698 let review = &mut state.reviews[0];
11699 review.clean = false;
11700 review.blocking = 1;
11701 review.e2e = vec![crate::run::CommandOutcome {
11702 command: "verify".into(),
11703 code: None,
11704 output_tail: "resource wait expired".into(),
11705 duration_ms: 0,
11706 resource_blocked: true,
11707 }];
11708 } else if stage == "no-reviews" {
11709 state.config.graph.review_rounds = 0;
11710 state.reviews.clear();
11711 } else if stage == "handoff" {
11712 let review = &mut state.reviews[0];
11715 review.clean = false;
11716 review.blocking = 1;
11717 review.e2e = vec![crate::run::CommandOutcome {
11718 command: "verify".into(),
11719 code: Some(0),
11720 output_tail: String::new(),
11721 duration_ms: 0,
11722 resource_blocked: false,
11723 }];
11724 }
11725 state.gate_ran = false;
11726 state.resource_block = Some(crate::run::ResourceBlock {
11727 cause: crate::run::ResourceBlockCause::Other,
11728 node: if stage == "review-e2e" {
11729 "review"
11730 } else {
11731 "gate"
11732 }
11733 .into(),
11734 kind: kind.into(),
11735 detail: "resource wait expired".into(),
11736 at: jiff::Timestamp::now(),
11737 });
11738 state.save_under(home.path()).unwrap();
11739 assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
11740 assert!(!exhausted_review_budget(&state));
11741 let mut task = held_task_with(&state.id);
11742 task.release();
11743 let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
11744 assert_eq!(
11745 choose_starter(None, false, unfinished.as_deref()),
11746 Starter::Resume(state.id.clone())
11747 );
11748 let question = action_question(&state.id, resume_action(&state.id));
11749 assert_eq!(
11750 decide_action(&task, &question, &PHRASES_EN, |_| Ok(state.clone())),
11751 ActionDecision::Resume(state.id.clone())
11752 );
11753 assert_eq!(
11754 crate::resume::validate(home.path(), &state.id).unwrap().id,
11755 state.id
11756 );
11757 let queue = Queue::at(home.path().join("queue"));
11758 let mut controlled = Task::new(
11759 "resume verification".into(),
11760 state.instruction.clone(),
11761 state.repo.clone(),
11762 Source::Agent {
11763 run: "talk".into(),
11764 node: crate::queue::CHAT_NODE.into(),
11765 },
11766 );
11767 controlled.runs.push(state.id.clone());
11768 controlled.hold_machine(Some("verification resource unavailable".into()));
11769 queue.put(&mut controlled).unwrap();
11770 let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
11771 assert_eq!(resumed.status, TaskStatus::Queued);
11772 assert_eq!(
11773 resumed.resume_override.unwrap().pinned_run,
11774 Some(state.id.clone())
11775 );
11776 assert_eq!(resumed.attempts, 0);
11777
11778 state.config.graph.review_rounds = 1;
11780 let mut unresolved = review_round(1);
11781 unresolved.blocking = 1;
11782 state.reviews = vec![unresolved];
11783 state.resource_block = None;
11784 state.save_under(home.path()).unwrap();
11785 assert!(exhausted_review_budget(&state));
11786 assert!(crate::resume::validate(home.path(), &state.id).is_err());
11787 }
11788 }
11789
11790 #[tokio::test]
11791 async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
11792 if !crate::standalone_test(
11793 "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
11794 ) {
11795 return;
11796 }
11797 let home = tempfile::tempdir().unwrap();
11798 let mut owner = stopped_public_run(RunStatus::Blocked);
11799 owner.save_under(home.path()).unwrap();
11800 let history = vec![owner.id.clone()];
11801 let repo = owner.repo.clone();
11802 let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
11803 let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
11804 let initial =
11805 std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
11806 assert!(
11807 initial.is_pending(),
11808 "a busy record must not hold or resume the task"
11809 );
11810 owner.retired_to = Some("20260101-000001-bbbb".into());
11811 owner.save_under(home.path()).unwrap();
11812 drop(lock);
11813 let result = tokio::time::timeout(Duration::from_secs(10), lookup)
11814 .await
11815 .expect("ownership lock released")
11816 .expect("read settled owner");
11817 assert!(
11818 result.is_none(),
11819 "the retired owner must not be resumed from a stale read"
11820 );
11821 }
11822
11823 #[tokio::test]
11824 async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
11825 if !crate::standalone_test(
11826 "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
11827 ) {
11828 return;
11829 }
11830 let home = tempfile::tempdir().unwrap();
11831 let mut owner = stopped_public_run(RunStatus::Blocked);
11832 let repo = tempfile::tempdir().unwrap();
11833 crate::git::git(repo.path(), &["init"]).await.unwrap();
11834 owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
11835 owner.id = "20260101-000000-aaaa".into();
11836 owner.save_under(home.path()).unwrap();
11837 let mut successor = run_state(RunStatus::Blocked);
11838 successor.id = "20260101-000001-bbbb".into();
11839 successor.save_under(home.path()).unwrap();
11840 let runs = vec![owner.id.clone(), successor.id.clone()];
11841 assert_eq!(
11842 public_resume_owner(home.path(), &runs, &owner.repo)
11843 .await
11844 .unwrap()
11845 .unwrap()
11846 .id,
11847 owner.id
11848 );
11849 let subdir = owner.repo.join("nested");
11850 std::fs::create_dir(&subdir).unwrap();
11851 assert_eq!(
11852 public_resume_owner(home.path(), &runs, &subdir)
11853 .await
11854 .unwrap()
11855 .unwrap()
11856 .id,
11857 owner.id
11858 );
11859 #[cfg(unix)]
11860 {
11861 let alias = home.path().join("repo-alias");
11862 std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
11863 assert_eq!(
11864 public_resume_owner(home.path(), &runs, &alias.join("nested"))
11865 .await
11866 .unwrap()
11867 .unwrap()
11868 .id,
11869 owner.id
11870 );
11871 }
11872 let different = tempfile::tempdir().unwrap();
11873 crate::git::git(different.path(), &["init"]).await.unwrap();
11874 assert!(
11875 public_resume_owner(home.path(), &runs, different.path())
11876 .await
11877 .is_err()
11878 );
11879 std::fs::remove_file(
11880 home.path()
11881 .join("runs")
11882 .join(&successor.id)
11883 .join("run.json"),
11884 )
11885 .unwrap();
11886 assert!(
11887 public_resume_owner(home.path(), &runs, &owner.repo)
11888 .await
11889 .is_err()
11890 );
11891 }
11892
11893 #[test]
11894 fn an_ordinary_release_keeps_a_resumable_run_available() {
11895 let mut released = task();
11896 released.start("stalled-run".to_owned());
11897 released.release();
11898 let unfinished = (!released.fresh_start)
11899 .then(|| Some("stalled-run".to_owned()))
11900 .flatten();
11901 assert_eq!(
11902 choose_starter(None, false, unfinished.as_deref()),
11903 Starter::Resume("stalled-run".to_owned()),
11904 "manual release must preserve the normal resume path"
11905 );
11906 }
11907
11908 #[test]
11909 fn resume_refusals_explain_admission_without_changing_task_or_run() {
11910 crate::run::pin_test_home();
11911 use crate::handover::{ResumeRefusal, resume_refusal_under};
11912 let home = tempfile::tempdir().unwrap();
11913 let mut exhausted = run_state(RunStatus::Blocked);
11914 exhausted.driver_exited = true;
11915 exhausted.config.graph.review_rounds = 3;
11916 exhausted.reviews = (1..=3).map(review_round).collect();
11917 for refusal in [
11918 ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
11919 ResumeRefusal::Status(RunStatus::Ready),
11920 ResumeRefusal::Released("20261022-000000-aaaa".into()),
11921 ResumeRefusal::Retired("retirement-successor".into()),
11922 ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
11923 ] {
11924 let mut state = exhausted.clone();
11925 let expected = match refusal {
11926 ResumeRefusal::Status(_) => {
11927 state.status = RunStatus::Ready;
11928 "status `ready`"
11929 }
11930 ResumeRefusal::Released(ref target) => {
11931 state.released_to = Some(target.clone());
11932 "execution was released"
11933 }
11934 ResumeRefusal::Retired(ref target) => {
11935 state.retired_to = Some(target.clone());
11936 "execution was retired"
11937 }
11938 ResumeRefusal::OwnershipTransferred(ref target) => {
11939 state.pr_taken_over_by = Some(target.clone());
11940 "PR ownership was transferred"
11941 }
11942 _ => "review budget exhausted (3/3 rounds used)",
11943 };
11944 assert_eq!(
11945 resume_refusal_under(&state, Some(home.path())),
11946 Some(refusal.clone())
11947 );
11948 assert_eq!(
11949 refusal.successor(),
11950 state
11951 .released_to
11952 .as_deref()
11953 .or(state.retired_to.as_deref())
11954 .or(state.pr_taken_over_by.as_deref())
11955 );
11956 state.save_under(home.path()).unwrap();
11957 let queue = Queue::at(home.path().join("queue"));
11958 let mut task = Task::new(
11959 "retained implementation".into(),
11960 state.instruction.clone(),
11961 state.repo.clone(),
11962 Source::Agent {
11963 run: "talk".into(),
11964 node: crate::queue::CHAT_NODE.into(),
11965 },
11966 );
11967 task.runs.push(state.id.clone());
11968 task.hold_machine(Some("stopped".into()));
11969 queue.put(&mut task).unwrap();
11970 let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
11971 let before_run = serde_json::to_value(&state).unwrap();
11972 let error = crate::chat_control::resume(&queue, home.path(), &state.id)
11973 .unwrap_err()
11974 .to_string();
11975 assert!(error.contains(expected), "{error}");
11976 assert!(!error.contains("only a stalled or blocked"), "{error}");
11977 if matches!(refusal, ResumeRefusal::Status(_)) {
11978 assert!(
11979 error.contains("is final; there is nothing left to resume"),
11980 "{error}"
11981 );
11982 }
11983 if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
11984 assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
11985 assert!(error.contains("review-only successor with a new review budget"));
11986 assert!(error.contains("does not resume this run"));
11987 }
11988 for target in [
11989 &state.released_to,
11990 &state.retired_to,
11991 &state.pr_taken_over_by,
11992 ]
11993 .into_iter()
11994 .flatten()
11995 {
11996 let short = if state.retired_to.as_ref() == Some(target) {
11997 target.as_str()
11998 } else {
11999 crate::run::short_of(target)
12000 };
12001 assert!(
12002 error.contains(&format!("run {short}; inspect `magi show {short}`")),
12003 "{error}"
12004 );
12005 if short != target {
12006 assert!(!error.contains(target), "full successor id leaked: {error}");
12007 }
12008 }
12009 assert_eq!(
12010 serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
12011 before_task
12012 );
12013 assert_eq!(
12014 serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
12015 .unwrap(),
12016 before_run
12017 );
12018 let question = action_question(&state.id, resume_action(&state.id));
12019 for phrases in [&PHRASES_EN, &PHRASES_JA] {
12020 let ActionDecision::Refuse(detail) =
12021 decide_action(&task, &question, phrases, |_| Ok(state.clone()))
12022 else {
12023 panic!("refusal expected");
12024 };
12025 assert!(detail.contains(expected), "{detail}");
12026 }
12027 }
12028 exhausted.status = RunStatus::Ready;
12030 exhausted.released_to = Some("released".into());
12031 exhausted.retired_to = Some("retired".into());
12032 exhausted.pr_taken_over_by = Some("owner".into());
12033 let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
12034 assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
12035 let detail = reason.diagnostic(&exhausted);
12036 for target in ["released", "retired", "owner"] {
12037 assert!(detail.contains(&format!("magi show {target}")));
12038 }
12039 }
12040
12041 #[test]
12042 fn resume_checkpoint_admission_uses_the_supplied_question_store() {
12043 let home = tempfile::tempdir().unwrap();
12044 let mut state = run_state(RunStatus::Blocked);
12045 state.driver_exited = true;
12046 state.config.graph.review_rounds = 1;
12047 state.reviews = vec![review_round(1)];
12048 assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
12049 for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
12050 let mut saved = state.clone();
12051 match checkpoint {
12052 "publication" => saved.pr_publication_pending = true,
12053 "approval" => {
12054 saved.land_approval = Some(crate::run::LandApproval {
12055 question: "approval".into(),
12056 head: "head".into(),
12057 })
12058 }
12059 "armed" => saved.land_armed_head = Some("head".into()),
12060 "landing" => saved.status = RunStatus::Landing,
12061 _ => {
12062 let mut question = ask::Question::new(
12063 saved.id.clone(),
12064 "review".into(),
12065 "review-1".into(),
12066 "continue?".into(),
12067 String::new(),
12068 vec!["continue".into()],
12069 );
12070 ask::Questions::at(home.path().join("questions"))
12071 .put(&mut question)
12072 .unwrap();
12073 }
12074 }
12075 saved.save_under(home.path()).unwrap();
12076 assert!(
12077 crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
12078 "{checkpoint}"
12079 );
12080 assert!(
12081 crate::resume::validate(home.path(), &saved.id).is_ok(),
12082 "{checkpoint}"
12083 );
12084 }
12085 }
12086
12087 #[test]
12088 fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
12089 let mut state = run_state(RunStatus::Blocked);
12090 state.config.graph.review_rounds = 3;
12091 state.reviews = vec![review_round(1), review_round(2), review_round(3)];
12092 assert!(exhausted_review_budget(&state));
12093
12094 state.reviews.pop();
12096 assert!(!exhausted_review_budget(&state));
12097
12098 let mut stalled = run_state(RunStatus::Stalled);
12101 stalled.config.graph.review_rounds = 1;
12102 stalled.reviews = vec![review_round(1)];
12103 assert!(!exhausted_review_budget(&stalled));
12104 }
12105
12106 fn review_round(round: usize) -> crate::run::ReviewRound {
12107 crate::run::ReviewRound {
12108 round,
12109 head: "deadbeef".to_owned(),
12110 verified_head: None,
12111 verified_at: None,
12112 reviews: Vec::new(),
12113 e2e: Vec::new(),
12114 verify_retried: false,
12115 e2e_deferred: false,
12116 e2e_defer_reason: None,
12117 fix: None,
12118 blocking: 0,
12119 answered: 1,
12120 expected: 1,
12121 clean: false,
12122 progressed: true,
12123 vote_split: false,
12124 reconsideration: Vec::new(),
12125 verdict: None,
12126 }
12127 }
12128
12129 #[test]
12130 fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
12131 let mut run = RunState::new(
12132 PathBuf::from("/repo"),
12133 "main".to_owned(),
12134 "abc1234def".to_owned(),
12135 "add retries".to_owned(),
12136 Config::default(),
12137 );
12138 run.status = RunStatus::Judging;
12139 run.parked = true;
12140 let mut task = Task::new(
12141 "add retries".to_owned(),
12142 "add retries".to_owned(),
12143 PathBuf::from("/repo"),
12144 crate::queue::Source::Human,
12145 );
12146 task.status = TaskStatus::Failed;
12147 task.runs = vec![run.id.clone()];
12148 let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
12149 assert!(with(&task, &run), "parked after judging is the case");
12150 let mut parked_task = task.clone();
12151 parked_task.status = TaskStatus::Parked;
12152 assert!(with(&parked_task, &run), "the Parked status is the case");
12153
12154 let mut not_parked = run.clone();
12155 not_parked.parked = false;
12156 not_parked.status = RunStatus::Stalled;
12157 assert!(!with(&task, ¬_parked), "a stall is the conductor's");
12158
12159 let mut fresh = task.clone();
12160 fresh.fresh_start = true;
12161 assert!(!with(&fresh, &run), "a requeue asked for a new competition");
12162
12163 let mut review = task.clone();
12164 review.review_branch = Some("magi/x/A".to_owned());
12165 assert!(!with(&review, &run), "review is ranked before resume");
12166
12167 let mut held = task.clone();
12168 held.status = TaskStatus::Held;
12169 assert!(!with(&held, &run), "a hold stays visible to the conductor");
12170
12171 let mut released = run.clone();
12172 released.released_to = Some("20260901-000000-new1".to_owned());
12173 assert!(!with(&task, &released), "nothing left to resume into");
12174
12175 assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
12176 "unreadable"
12177 )));
12178 }
12179
12180 #[test]
12181 fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
12182 let mut released = RunState::new(
12183 PathBuf::from("/repo"),
12184 "main".to_owned(),
12185 "abc1234def".to_owned(),
12186 "add retries".to_owned(),
12187 Config::default(),
12188 );
12189 released.status = RunStatus::Blocked;
12190 assert_eq!(
12191 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
12192 Some(released.id.clone())
12193 );
12194 released.released_to = Some("20260901-000000-new1".to_owned());
12195 assert_eq!(
12196 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
12197 None,
12198 "there is nothing left to resume it into"
12199 );
12200 }
12201
12202 #[test]
12203 fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
12204 let mut exhausted = RunState::new(
12213 PathBuf::from("/repo"),
12214 "main".to_owned(),
12215 "abc1234def".to_owned(),
12216 "add retries".to_owned(),
12217 Config::default(),
12218 );
12219 exhausted.status = RunStatus::Blocked;
12220 exhausted.config.graph.review_rounds = 1;
12221 exhausted.reviews = vec![review_round(1)];
12222
12223 assert_eq!(
12224 unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
12225 None,
12226 "an exhausted `Blocked` run must not be offered as resumable"
12227 );
12228
12229 let mut has_budget_left = RunState::new(
12232 PathBuf::from("/repo"),
12233 "main".to_owned(),
12234 "abc1234def".to_owned(),
12235 "add retries".to_owned(),
12236 Config::default(),
12237 );
12238 has_budget_left.status = RunStatus::Blocked;
12239 has_budget_left.config.graph.review_rounds = 3;
12240 has_budget_left.reviews = vec![review_round(1)];
12241
12242 assert_eq!(
12243 unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
12244 Ok(has_budget_left.clone())
12245 }),
12246 Some(has_budget_left.id.clone())
12247 );
12248 }
12249
12250 #[test]
12251 fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
12252 let mut run = RunState::new(
12253 PathBuf::from("/repo"),
12254 "main".to_owned(),
12255 "abc1234def".to_owned(),
12256 "add retries".to_owned(),
12257 Config::default(),
12258 );
12259 run.status = RunStatus::Blocked;
12260 run.config.graph.review_rounds = 1;
12261 run.reviews = vec![review_round(1)];
12262 run.pr_publication_pending = true;
12263 assert_eq!(
12264 unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
12265 Some(run.id.clone()),
12266 "a spent review budget must not turn a failed publication into a re-competition"
12267 );
12268 }
12269
12270 #[test]
12271 fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
12272 let mut task = Task::new(
12273 "recover work".into(),
12274 "recover work".into(),
12275 PathBuf::from("/repo"),
12276 crate::queue::Source::Human,
12277 );
12278 let mut history = std::collections::BTreeMap::new();
12279 for index in 0..8 {
12280 let mut run = run_state(RunStatus::Blocked);
12281 run.id = format!("20260101-000000-{index:04}");
12282 run.base_commit = format!("upstream-{index}");
12283 if index > 0 {
12285 run.candidates.clear();
12286 }
12287 task.runs.extend([run.id.clone(), run.id.clone()]);
12288 history.insert(run.id.clone(), run);
12289 task.requeue();
12290 }
12291 let check = |task: &Task, starter: &Starter, limit| {
12292 retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
12293 };
12294 assert!(
12295 check(&task, &Starter::Start, 8)
12296 .unwrap()
12297 .contains("8 unretired")
12298 );
12299 assert!(check(&task, &Starter::Start, 9).is_none());
12300 assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
12301 task.release_operator("owner", None);
12302 assert_eq!(task.attempts, 0);
12303 let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
12304 assert!(check(&restored, &Starter::Start, 8).is_some());
12305 assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
12306 assert!(check(&restored, &Starter::Start, 0).is_none());
12307 }
12308
12309 #[test]
12310 fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
12311 let mut task = Task::new(
12312 "recover work".into(),
12313 "recover work".into(),
12314 PathBuf::from("/repo"),
12315 crate::queue::Source::Human,
12316 );
12317 let mut run = run_state(RunStatus::Superseded);
12318 run.candidates.clear();
12319 task.runs.push(run.id.clone());
12320 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
12321 run.retired_to = Some("authority".into());
12322 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
12323 run.retired_to = None;
12324 run.released_to = Some("authority".into());
12325 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
12326 assert!(
12327 retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
12328 .unwrap()
12329 .contains("Cannot verify")
12330 );
12331 assert!(
12333 retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
12334 panic!("resume must not load historical attempts")
12335 })
12336 .is_none()
12337 );
12338 }
12339
12340 #[test]
12341 fn retired_resume_requires_a_valid_same_repository_authority() {
12342 let mut source = run_state(RunStatus::Blocked);
12343 let mut empty = run_state(RunStatus::Blocked);
12344 empty.retired_to = Some(source.id.clone());
12345 let runs = vec![source.id.clone(), empty.id.clone()];
12346 let resolve = |source: &RunState, empty: &RunState| {
12347 unfinished_run_with(&runs, "fixture", |id| {
12348 if id == source.id {
12349 Ok(source.clone())
12350 } else if id == empty.id {
12351 Ok(empty.clone())
12352 } else {
12353 bail!("unreadable authority")
12354 }
12355 })
12356 };
12357 assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
12358 assert_eq!(
12359 choose_starter(None, false, resolve(&source, &empty).as_deref()),
12360 Starter::Resume(source.id.clone())
12361 );
12362 source.retired_to = Some(empty.id.clone());
12363 assert!(
12364 resolve(&source, &empty).is_none(),
12365 "cycles do not revive obsolete runs"
12366 );
12367 source.retired_to = None;
12368 source.repo = PathBuf::from("/another-repository");
12369 assert!(resolve(&source, &empty).is_none());
12370 source.repo = empty.repo.clone();
12371 source.released_to = Some("later".into());
12372 assert!(resolve(&source, &empty).is_none());
12373 empty.retired_to = Some("unlisted-run".into());
12374 assert!(resolve(&source, &empty).is_none());
12375 }
12376
12377 #[test]
12378 fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
12379 let mut older_stalled = RunState::new(
12387 PathBuf::from("/repo"),
12388 "main".to_owned(),
12389 "abc1234def".to_owned(),
12390 "add retries".to_owned(),
12391 Config::default(),
12392 );
12393 older_stalled.status = RunStatus::Stalled;
12394
12395 let mut newest_exhausted = RunState::new(
12396 PathBuf::from("/repo"),
12397 "main".to_owned(),
12398 "abc1234def".to_owned(),
12399 "add retries".to_owned(),
12400 Config::default(),
12401 );
12402 newest_exhausted.status = RunStatus::Blocked;
12403 newest_exhausted.config.graph.review_rounds = 1;
12404 newest_exhausted.reviews = vec![review_round(1)];
12405
12406 assert_eq!(
12407 unfinished_run_with(
12408 &[older_stalled.id.clone(), newest_exhausted.id.clone()],
12409 "t",
12410 |_| Ok(newest_exhausted.clone())
12411 ),
12412 None,
12413 "the newest run is exhausted, so nothing here is worth resuming - \
12414 least of all the older, already-superseded run"
12415 );
12416 }
12417
12418 #[test]
12419 fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
12420 assert_eq!(
12421 unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
12422 Err(anyhow::anyhow!("fixture is absent"))
12423 }),
12424 None
12425 );
12426 }
12427
12428 fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
12429 let mut q = ask::Question::new(
12430 run.to_owned(),
12431 "implement".to_owned(),
12432 "impl-A".to_owned(),
12433 "continue?".to_owned(),
12434 String::new(),
12435 vec!["resume で続行する".to_owned(), "other".to_owned()],
12436 );
12437 q.actions.insert("resume で続行する".to_owned(), action);
12438 q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
12439 .unwrap();
12440 q
12441 }
12442
12443 fn held_task_with(run: &str) -> Task {
12444 let mut t = task();
12445 t.runs = vec![run.to_owned()];
12446 t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
12447 t
12448 }
12449
12450 fn resume_action(run: &str) -> ask::ChoiceAction {
12451 ask::ChoiceAction::Resume { run: run.into() }
12452 }
12453
12454 #[test]
12455 fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
12456 for parked in [false, true] {
12457 let mut t = task();
12458 t.start("A".into());
12459 t.start("B".into());
12460 assert_eq!(t.runs, vec!["A", "B"]);
12461 t.start("A".into());
12462 let mut resumed = run_state(RunStatus::Blocked);
12463 resumed.id = "A".into();
12464 resumed.parked = parked;
12465 resumed.driver_exited = true;
12466 t.hold_machine(Some("resumed run stopped".into()));
12467 let q = action_question("A", resume_action("A"));
12468 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
12469 assert_eq!(
12470 decide_action(&t, &q, &PHRASES_EN, |id| {
12471 assert_eq!(id, "A");
12472 Ok(resumed.clone())
12473 }),
12474 ActionDecision::Resume("A".into())
12475 );
12476 assert_eq!(
12477 action_standing(&t, &action_question("B", resume_action("B"))),
12478 ActionStanding::Stale
12479 );
12480 t.release_operator("cli", None);
12481 let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
12482 assert_eq!(id, "A");
12483 Ok(resumed.clone())
12484 });
12485 assert_eq!(
12486 choose_starter(None, false, unfinished.as_deref()),
12487 Starter::Resume("A".into())
12488 );
12489 assert_eq!(t.runs, vec!["B", "A"]);
12490 }
12491 }
12492
12493 #[test]
12494 fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
12495 let mut state = crate::land::tests::repair_state(true, true);
12496 state.status = RunStatus::Landing;
12497 state.parked = true;
12498 state.driver_exited = true;
12499 let mut q = ask::Question::new(
12500 state.id.clone(),
12501 land::APPROVAL_NODE.into(),
12502 "land".into(),
12503 "Merge?".into(),
12504 String::new(),
12505 vec![land::APPROVE.into(), land::HOLD.into()],
12506 );
12507 q.id = state.id.clone();
12508 state.land_approval = Some(crate::run::LandApproval {
12509 question: q.id.clone(),
12510 head: "current-head".into(),
12511 });
12512 assert!(land::upgrade_repair_choice(&mut q, &state));
12513 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12514 let mut task = held_task_with(&state.id);
12515 task.status = TaskStatus::Parked;
12516 assert_eq!(
12517 decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
12518 ActionDecision::Resume(state.id.clone())
12519 );
12520 q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
12521 q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
12522 task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
12523 assert_eq!(
12524 decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
12525 ActionDecision::Resume(state.id.clone()),
12526 "a repair answer newer than the manual hold resumes the existing owner"
12527 );
12528 task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
12529 for answered_at in [q.answered_at, None] {
12530 let mut older = q.clone();
12531 older.answered_at = answered_at;
12532 let refused = decide_action(&task, &older, &PHRASES_EN, |_| {
12533 panic!("a later manual hold must prevent dispatch")
12534 });
12535 let ActionDecision::Refuse(reason) = refused else {
12536 panic!("expected an actionable refusal, got {refused:?}");
12537 };
12538 assert!(reason.contains("later operator decision"));
12539 assert!(reason.contains(&format!("magi task release {}", task.id)));
12540 }
12541 task.operator_decided_at = None;
12542 let mut superseded = state.clone();
12543 superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
12544 assert_eq!(
12545 decide_action(&task, &q, &PHRASES_EN, |_| Ok(superseded)),
12546 ActionDecision::Stale
12547 );
12548 for case in 1..4 {
12549 let mut changed = state.clone();
12550 match case {
12551 1 => changed.status = RunStatus::Blocked,
12552 2 => changed.released_to = Some("new-owner".into()),
12553 _ => changed.land_approval.as_mut().unwrap().head.clear(),
12554 }
12555 assert!(matches!(
12556 decide_action(&task, &q, &PHRASES_EN, |_| Ok(changed)),
12557 ActionDecision::Refuse(_)
12558 ));
12559 }
12560 assert!(matches!(
12561 decide_action(&task, &q, &PHRASES_EN, |_| anyhow::bail!("missing owner")),
12562 ActionDecision::Refuse(_)
12563 ));
12564 task.runs.push("replacement".into());
12565 task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
12566 assert_eq!(
12567 decide_action(&task, &q, &PHRASES_EN, |_| panic!(
12568 "old owner must not load"
12569 )),
12570 ActionDecision::Stale
12571 );
12572 }
12573
12574 #[test]
12575 fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
12576 let mut state = crate::land::tests::repair_state(true, true);
12577 state.status = RunStatus::Landing;
12578 state.parked = true;
12579 state.driver_exited = true;
12580 let mut q = ask::Question::new(
12581 state.id.clone(),
12582 land::APPROVAL_NODE.into(),
12583 "land".into(),
12584 "Merge?".into(),
12585 String::new(),
12586 vec![land::APPROVE.into(), land::HOLD.into()],
12587 );
12588 q.id = state.id.clone();
12589 state.land_approval = Some(crate::run::LandApproval {
12590 question: q.id.clone(),
12591 head: "current-head".into(),
12592 });
12593 state.save().unwrap();
12594 land::upgrade_repair_choice(&mut q, &state);
12595 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12596 Questions::open().put(&mut q).unwrap();
12597 let tmp = tempfile::tempdir().unwrap();
12598 let queue = Queue::at(tmp.path().join("queue"));
12599 let mut task = held_task_with(&state.id);
12600 task.status = TaskStatus::Parked;
12601 queue.put(&mut task).unwrap();
12602 let empty = Arc::new(tokio::sync::Semaphore::new(0));
12603 let free = Arc::new(tokio::sync::Semaphore::new(1));
12604 assert!(claim_dispatch(&queue, &task, false, &empty, &free).is_none());
12605 assert!(claim_dispatch(&queue, &task, true, &free, &free).is_none());
12606 let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
12607 assert!(claim.permit.is_some());
12608 assert!(claim_dispatch(&queue, &task, false, &free, &free).is_none());
12609 drop(claim);
12610 Questions::open()
12611 .update(&q.id, |q| {
12612 q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
12613 Ok(())
12614 })
12615 .unwrap();
12616 let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
12617 assert!(claim.permit.is_none());
12618 assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
12619 }
12620
12621 #[test]
12622 fn decide_action_resumes_only_the_latest_resumable_run() {
12623 let t = held_task_with("r1");
12624 let q = action_question("r1", resume_action("r1"));
12625 let load = |s: RunState| move |_: &str| Ok(s);
12626 assert_eq!(
12627 decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Blocked))),
12628 ActionDecision::Resume("r1".into())
12629 );
12630 let q_other = action_question("r1", resume_action("r0"));
12632 assert!(matches!(
12633 decide_action(
12634 &t,
12635 &q_other,
12636 &PHRASES_EN,
12637 load(run_state(RunStatus::Blocked))
12638 ),
12639 ActionDecision::Refuse(_)
12640 ));
12641 assert!(matches!(
12643 decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Ready))),
12644 ActionDecision::Refuse(_)
12645 ));
12646 let mut released = run_state(RunStatus::Blocked);
12648 released.released_to = Some("elsewhere".into());
12649 assert!(matches!(
12650 decide_action(&t, &q, &PHRASES_EN, load(released)),
12651 ActionDecision::Refuse(_)
12652 ));
12653 assert!(matches!(
12655 decide_action(&t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
12656 ActionDecision::Refuse(_)
12657 ));
12658 }
12659
12660 #[test]
12661 fn decide_action_ignores_a_question_about_an_earlier_run() {
12662 let mut t = held_task_with("r1");
12663 t.runs.push("r2".to_owned());
12664 let never = |_: &str| -> Result<RunState> { bail!("not read") };
12665 assert_eq!(
12666 decide_action(
12667 &t,
12668 &action_question("r1", ask::ChoiceAction::Done),
12669 &PHRASES_EN,
12670 never
12671 ),
12672 ActionDecision::Stale
12673 );
12674 }
12675
12676 #[test]
12677 fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
12678 let mut t = held_task_with("r1");
12679 let never = |_: &str| -> Result<RunState> { bail!("not read") };
12680 assert_eq!(
12681 decide_action(
12682 &t,
12683 &action_question("r1", ask::ChoiceAction::Requeue),
12684 &PHRASES_EN,
12685 never
12686 ),
12687 ActionDecision::Requeue
12688 );
12689 let done_q = action_question("r1", ask::ChoiceAction::Done);
12690 assert_eq!(
12691 decide_action(&t, &done_q, &PHRASES_EN, never),
12692 ActionDecision::Done
12693 );
12694 t.mark_action_applied(&done_q.id);
12695 assert_eq!(
12696 decide_action(&t, &done_q, &PHRASES_EN, never),
12697 ActionDecision::Skip
12698 );
12699
12700 let mut plain = action_question("r1", ask::ChoiceAction::Done);
12702 plain.actions.clear();
12703 assert_eq!(
12704 decide_action(&held_task_with("r1"), &plain, &PHRASES_EN, never),
12705 ActionDecision::Skip
12706 );
12707 let mut running = held_task_with("r1");
12709 running.status = TaskStatus::Running;
12710 assert_eq!(
12711 decide_action(
12712 &running,
12713 &action_question("r1", ask::ChoiceAction::Done),
12714 &PHRASES_EN,
12715 never
12716 ),
12717 ActionDecision::Skip
12718 );
12719 }
12720
12721 #[test]
12722 fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
12723 crate::run::pin_test_home();
12724 for legacy in [false, true] {
12725 let dir = tempfile::tempdir().unwrap();
12726 let queue = Queue::at(dir.path().join("queue"));
12727 let questions = Questions::at(dir.path().join("questions"));
12728 let run = "20260101-000000-hold";
12729 let mut task = held_task_with(run);
12730 task.status = TaskStatus::Parked;
12731 let mut q = ask::Question::new(
12732 run.into(),
12733 land::APPROVAL_NODE.into(),
12734 "land".into(),
12735 "Repair?".into(),
12736 String::new(),
12737 vec![land::REPAIR.into()],
12738 );
12739 q.actions.insert(land::REPAIR.into(), resume_action(run));
12740 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12741 q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
12743 q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
12744 questions.put(&mut q).unwrap();
12745 task.hold_manual(Some("Keep this PR paused".into()));
12746 if legacy {
12747 task.hold_source = None;
12748 }
12749 queue.put(&mut task).unwrap();
12750
12751 apply_task_choice_actions(&queue, &questions, dir.path());
12752 let after = queue.get(&task.id).unwrap();
12753 assert!(after.operator_held());
12754 assert_eq!(after.hold_source, task.hold_source);
12755 assert_eq!(after.operator_decided_at, task.operator_decided_at);
12756 assert_eq!(after.runs, task.runs);
12757 assert_eq!(after.instruction, task.instruction);
12758 assert!(after.resume_override.is_none());
12759 assert!(after.action_applied(&q.id));
12760 let reason = after.hold_reason.as_deref().unwrap();
12761 assert!(reason.starts_with("Keep this PR paused"));
12762 assert!(reason.contains("later operator decision"));
12763 assert!(reason.contains(&format!("magi task release {}", task.id)));
12764
12765 for recovery in [
12766 crate::conduct::Recovery::Review,
12767 crate::conduct::Recovery::Requeue,
12768 ] {
12769 crate::conduct::apply(
12770 &queue,
12771 &questions,
12772 &crate::conduct::Verdict {
12773 decisions: vec![crate::conduct::Decision {
12774 id: task.id.clone(),
12775 recovery: Some(recovery),
12776 ..Default::default()
12777 }],
12778 },
12779 )
12780 .unwrap();
12781 }
12782 apply_task_choice_actions(&queue, &questions, dir.path());
12785 let still_held = queue.get(&task.id).unwrap();
12786 assert!(still_held.operator_held());
12787 assert_eq!(still_held.hold_reason, after.hold_reason);
12788 assert_eq!(still_held.runs, task.runs);
12789 assert!(still_held.review_branch.is_none());
12790 assert!(!still_held.fresh_start);
12791 assert!(queue.next_runnable().is_none());
12792 }
12793 }
12794
12795 #[test]
12796 fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
12797 for held in [false, true] {
12798 for retry in [false, true] {
12799 let dir = tempfile::tempdir().unwrap();
12800 let queue = Queue::at(dir.path().join("queue"));
12801 let questions = Questions::at(dir.path().join("questions"));
12802 let home = dir.path().join("home");
12803 let mut t = task();
12804 if held {
12805 t.hold_machine(Some("driver state unknown".into()));
12806 }
12807 queue.put(&mut t).unwrap();
12808 let verdict = serde_json::from_value(serde_json::json!({
12809 "decisions": [{
12810 "id": t.id,
12811 "question": "Driver state unknown; retry the checks or hold?",
12812 "choices": ["daemon: recheck and retry", "daemon: hold the task"],
12813 "actions": {
12814 "daemon: recheck and retry": {"do": "requeue"},
12815 "daemon: hold the task": {"do": "hold"}
12816 }
12817 }]
12818 }))
12819 .unwrap();
12820 crate::conduct::apply(&queue, &questions, &verdict).unwrap();
12821 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
12822 let mut q = questions.list().pop().unwrap();
12823 let choice = if retry {
12824 "daemon: recheck and retry"
12825 } else {
12826 "daemon: hold the task"
12827 };
12828 assert_eq!(q.actions.len(), 2);
12829 q.answer(ask::Answer::Choice(choice.into())).unwrap();
12830 questions.put(&mut q).unwrap();
12831
12832 questions.beat(&q.id, ask::WaiterKind::Deputy);
12834 for _ in 0..2 {
12835 resolve_blockers(&queue, &questions);
12836 apply_task_choice_actions(&queue, &questions, &home);
12837 let waiting = queue.get(&t.id).unwrap();
12838 assert_eq!(waiting.status, TaskStatus::Blocked);
12839 assert_eq!(waiting.blocked_by, [q.id.clone()]);
12840 assert!(waiting.answers.is_empty());
12841 assert!(!waiting.action_applied(&q.id));
12842 assert!(runnable(&queue).is_empty());
12843 let free = Arc::new(tokio::sync::Semaphore::new(1));
12844 assert!(claim_dispatch(&queue, &t, false, &free, &free).is_none());
12845 }
12846 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
12847
12848 resolve_blockers(&queue, &questions);
12850 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
12851 apply_task_choice_actions(&queue, &questions, &home);
12852 let after = queue.get(&t.id).unwrap();
12853 assert_eq!(
12854 after.status,
12855 if retry {
12856 TaskStatus::Queued
12857 } else {
12858 TaskStatus::Held
12859 }
12860 );
12861 assert!(after.action_applied(&q.id));
12862 assert_eq!(after.operator_held(), !retry);
12863 assert_eq!(after.answers.len(), 1);
12864
12865 let mut changed = after;
12867 if retry {
12868 changed.hold_manual(Some("later hold".into()));
12869 } else {
12870 changed.release_operator("test", None);
12871 }
12872 let expected = changed.status;
12873 queue.put(&mut changed).unwrap();
12874 apply_task_choice_actions(&queue, &questions, &home);
12875 assert_eq!(queue.get(&t.id).unwrap().status, expected);
12876 }
12877 }
12878 }
12879
12880 #[test]
12881 fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
12882 let dir = tempfile::tempdir().unwrap();
12883 let queue = Queue::at(dir.path().join("queue"));
12884 let questions = Questions::at(dir.path().join("questions"));
12885 let home = dir.path().join("home");
12886 let mut state = run_state(RunStatus::Blocked);
12887 state.id = "20260101-000000-act1".to_owned();
12888 state.save_under(&home).unwrap();
12889
12890 let mut t = held_task_with(&state.id);
12891 queue.put(&mut t).unwrap();
12892 let mut q = action_question(&state.id, resume_action(&state.id));
12893 questions.put(&mut q).unwrap();
12894
12895 apply_task_choice_actions(&queue, &questions, &home);
12896 let after = queue.get(&t.id).unwrap();
12897 assert_eq!(after.status, TaskStatus::Queued);
12898 assert!(!after.fresh_start);
12899 assert!(after.action_applied(&q.id));
12900 let pin = after.resume_override.clone().unwrap();
12901 assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
12902 assert!(pin.forced);
12903
12904 let mut again = queue.get(&t.id).unwrap();
12906 again.hold_machine(Some("later".into()));
12907 queue.put(&mut again).unwrap();
12908 apply_task_choice_actions(&queue, &questions, &home);
12909 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12910 }
12911
12912 #[test]
12913 fn a_delivered_answer_is_still_acted_on_exactly_once() {
12914 let dir = tempfile::tempdir().unwrap();
12915 let queue = Queue::at(dir.path().join("queue"));
12916 let questions = Questions::at(dir.path().join("questions"));
12917 let home = dir.path().join("home");
12918 let mut state = run_state(RunStatus::Blocked);
12919 state.id = "20260101-000000-act2".to_owned();
12920 state.save_under(&home).unwrap();
12921
12922 let mut t = held_task_with(&state.id);
12923 queue.put(&mut t).unwrap();
12924 let mut q = action_question(&state.id, resume_action(&state.id));
12925 q.answer_delivered = true;
12926 questions.put(&mut q).unwrap();
12927
12928 apply_task_choice_actions(&queue, &questions, &home);
12931 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
12932 assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
12933
12934 let mut again = queue.get(&t.id).unwrap();
12936 again.hold_machine(Some("later".into()));
12937 queue.put(&mut again).unwrap();
12938 apply_task_choice_actions(&queue, &questions, &home);
12939 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12940 }
12941
12942 #[test]
12943 fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
12944 let dir = tempfile::tempdir().unwrap();
12945 let queue = Queue::at(dir.path().join("queue"));
12946 let questions = Questions::at(dir.path().join("questions"));
12947 let home = dir.path().join("home");
12948 let mut state = run_state(RunStatus::Blocked);
12949 state.id = "20260101-000000-act3".to_owned();
12950 state.save_under(&home).unwrap();
12951 let mut t = held_task_with(&state.id);
12952 queue.put(&mut t).unwrap();
12953 let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
12954 questions.put(&mut q).unwrap();
12955
12956 questions.beat(&q.id, crate::ask::WaiterKind::Asker);
12957 apply_task_choice_actions(&queue, &questions, &home);
12958 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12959
12960 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
12961 apply_task_choice_actions(&queue, &questions, &home);
12962 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
12963 }
12964
12965 #[test]
12966 fn action_standing_tells_the_reasons_apart() {
12967 let mut t = held_task_with("r1");
12968 let q = action_question("r1", ask::ChoiceAction::Requeue);
12969 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
12970 let mut plain = q.clone();
12971 plain.actions.clear();
12972 assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
12973
12974 t.mark_action_applied(&q.id);
12976 assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
12977
12978 let mut t = held_task_with("r1");
12980 t.start("r2".to_owned());
12981 assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
12982 let q2 = action_question("r2", ask::ChoiceAction::Requeue);
12984 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
12985 t.status = TaskStatus::Blocked;
12986 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
12987
12988 let mut c = action_question("r0", ask::ChoiceAction::Requeue);
12990 c.node = crate::conduct::NODE.to_owned();
12991 assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
12992 assert!(!ActionStanding::Busy.daemon_owns());
12993 }
12994
12995 #[test]
12996 fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
12997 let dir = tempfile::tempdir().unwrap();
12998 let queue = Queue::at(dir.path().join("queue"));
12999 let questions = Questions::at(dir.path().join("questions"));
13000 let home = dir.path().join("home");
13001 let mut state = run_state(RunStatus::Blocked);
13002 state.id = "20260101-000000-act4".to_owned();
13003 state.save_under(&home).unwrap();
13004 let mut t = held_task_with(&state.id);
13005 t.status = TaskStatus::Running;
13006 queue.put(&mut t).unwrap();
13007 let mut q = action_question(&state.id, ask::ChoiceAction::Done);
13008 q.cwd = Some(dir.path().display().to_string());
13009 questions.put(&mut q).unwrap();
13010
13011 let running = queue.get(&t.id).unwrap();
13014 assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
13015 assert!(matches!(
13016 crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
13017 crate::waiter::Action::Deliver(_)
13018 ));
13019 apply_task_choice_actions(&queue, &questions, &home);
13021 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
13022 let mut back = queue.get(&t.id).unwrap();
13023 back.hold_machine(Some("later".into()));
13024 queue.put(&mut back).unwrap();
13025 apply_task_choice_actions(&queue, &questions, &home);
13026 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
13027 let mut again = queue.get(&t.id).unwrap();
13028 again.hold_machine(Some("again".into()));
13029 queue.put(&mut again).unwrap();
13030 apply_task_choice_actions(&queue, &questions, &home);
13031 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13032 }
13033}