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::{BuildCache, 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 dispatch_wait: Option<DispatchWait>,
139 #[serde(default)]
141 pub question_recovery: Option<crate::question_delivery::Recovery>,
142 #[serde(default)]
144 pub worker_protocol: Option<u32>,
145}
146
147impl Status {
148 #[must_use]
150 pub fn new() -> Self {
151 let now = Timestamp::now();
152 Self {
153 schema: SCHEMA,
154 pid: std::process::id(),
155 started_at: now,
156 updated_at: now,
157 idle: true,
158 current: Vec::new(),
159 completed: 0,
160 polls: 0,
161 dispatch_wait: None,
162 question_recovery: None,
163 worker_protocol: Some(1),
164 }
165 }
166}
167
168impl Default for Status {
169 fn default() -> Self {
170 Self::new()
171 }
172}
173
174#[derive(Debug, Clone, Serialize, Deserialize)]
176#[serde(default)]
177pub struct Opts {
178 pub repo: PathBuf,
180 pub config: Option<PathBuf>,
182 pub poll: Duration,
184 pub max_attempts: usize,
186 pub once: bool,
188 pub merge: Option<String>,
190 pub worktrees_root: Option<PathBuf>,
199}
200
201impl Default for Opts {
202 fn default() -> Self {
203 Self {
204 repo: PathBuf::from("."),
205 config: None,
206 poll: POLL,
207 max_attempts: 2,
208 once: false,
209 merge: None,
210 worktrees_root: None,
211 }
212 }
213}
214
215impl Opts {
216 fn absolute(&self) -> Result<Self> {
217 let mut opts = self.clone();
218 opts.repo = std::path::absolute(&opts.repo)?;
219 opts.config = opts
220 .config
221 .as_deref()
222 .map(std::path::absolute)
223 .transpose()?;
224 opts.worktrees_root = opts
225 .worktrees_root
226 .as_deref()
227 .map(std::path::absolute)
228 .transpose()?;
229 Ok(opts)
230 }
231}
232
233fn max_concurrent(n: usize) -> usize {
238 n.max(1)
239}
240
241#[must_use]
243pub fn status_path() -> PathBuf {
244 crate::run::home().join("daemon.json")
245}
246
247pub fn write_status(status: &Status) -> Result<()> {
249 write_status_to(&status_path(), status)
250}
251
252pub fn write_status_to(path: &Path, status: &Status) -> Result<()> {
257 if let Some(parent) = path.parent() {
258 std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
259 }
260 let body = serde_json::to_string_pretty(status).context("serialize daemon status")?;
261 let tmp = path.with_extension("json.tmp");
262 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
263 std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
264 Ok(())
265}
266
267pub fn clear_status() {
270 clear_status_at(&status_path());
271}
272
273fn clear_status_at(path: &Path) {
277 let _ = std::fs::remove_file(path);
278}
279
280#[derive(Debug, Clone, Default)]
292pub struct Stop {
293 stopped: Arc<AtomicBool>,
297 busy: Arc<std::sync::atomic::AtomicUsize>,
299 wake: Arc<Notify>,
303 pause: crate::graph::Pause,
306}
307
308impl Stop {
309 #[must_use]
311 pub fn new() -> Self {
312 Self::default()
313 }
314
315 pub fn stop(&self) {
318 self.stopped.store(true, Ordering::SeqCst);
319 self.wake.notify_one();
323 }
324
325 #[must_use]
327 pub fn stopped(&self) -> bool {
328 self.stopped.load(Ordering::SeqCst)
329 }
330
331 #[must_use]
334 pub fn finishing(&self) -> bool {
335 self.stopped() && self.busy_now()
336 }
337
338 pub fn park(&self, cause: crate::run::ParkCause) {
344 self.pause.park_for(cause);
345 self.stop();
346 }
347
348 #[must_use]
350 pub fn parking(&self) -> bool {
351 self.pause.parked()
352 }
353
354 #[must_use]
356 pub fn pause(&self) -> crate::graph::Pause {
357 self.pause.clone()
358 }
359
360 #[must_use]
362 pub fn busy_now(&self) -> bool {
363 self.busy.load(Ordering::SeqCst) > 0
364 }
365
366 async fn idle(&self, poll: Duration) {
368 tokio::select! {
369 () = tokio::time::sleep(poll) => {}
370 () = self.wake.notified() => {}
371 }
372 }
373}
374
375#[derive(Debug, Clone, Default, Deserialize)]
382#[serde(default)]
383pub struct Reading {
384 pub schema: u32,
386 pub pid: Option<u32>,
388 pub started_at: Option<Timestamp>,
390 pub updated_at: Option<Timestamp>,
392 pub idle: bool,
394 #[serde(deserialize_with = "de_current")]
406 pub current: Vec<Current>,
407 pub completed: u64,
409 pub polls: u64,
411 pub dispatch_wait: Option<DispatchWait>,
413 #[serde(default)]
415 pub question_recovery: Option<crate::question_delivery::Recovery>,
416 pub worker_protocol: Option<u32>,
418}
419
420fn de_current<'de, D>(deserializer: D) -> std::result::Result<Vec<Current>, D::Error>
423where
424 D: serde::Deserializer<'de>,
425{
426 #[derive(Deserialize)]
427 #[serde(untagged)]
428 enum Shape {
429 Many(Vec<Current>),
430 One(Current),
431 }
432 Ok(
433 Option::<Shape>::deserialize(deserializer)?.map_or_else(Vec::new, |shape| match shape {
434 Shape::Many(v) => v,
435 Shape::One(c) => vec![c],
436 }),
437 )
438}
439
440impl Reading {
441 #[must_use]
444 pub fn age_secs(&self, now: Timestamp) -> Option<i64> {
445 self.updated_at
446 .map(|at| (now.as_second() - at.as_second()).max(0))
447 }
448
449 #[must_use]
453 pub fn running(&self, now: Timestamp) -> bool {
454 self.age_secs(now).is_some_and(|secs| secs <= STALE_SECS)
455 }
456}
457
458#[must_use]
465pub fn read_status(home: &Path) -> Option<Reading> {
466 let body = std::fs::read_to_string(home.join("daemon.json")).ok()?;
467 serde_json::from_str(&body).ok()
468}
469
470#[must_use]
479pub fn current_work(home: &Path, now: Timestamp) -> Vec<Current> {
480 let mut current = read_status(home)
481 .filter(|reading| reading.running(now))
482 .map(|reading| reading.current)
483 .unwrap_or_default();
484 let workers = crate::worker::observe_active(home).and_then(|jobs| {
485 jobs.into_iter()
486 .filter(|job| job.kind == "task")
487 .map(|job| {
488 let request: TaskWorker = serde_json::from_value(job.payload)?;
489 let run = Queue::at(request.queue)
490 .get(&request.task)
491 .ok()
492 .and_then(|task| task.execution_runs().last().cloned())
493 .unwrap_or_default();
494 Ok(Current {
495 worker: Some(job.id),
496 task: request.task,
497 run,
498 })
499 })
500 .collect::<Result<Vec<_>>>()
501 });
502 match workers {
503 Ok(workers) => {
504 for worker in workers {
505 if !current.iter().any(|claim| {
506 claim.task == worker.task
507 && claim.run == worker.run
508 && claim.worker == worker.worker
509 }) {
510 current.push(worker);
511 }
512 }
513 }
514 Err(error) => {
515 tracing::error!("cannot determine active workers: {error:#}");
518 current.extend(
519 Queue::at(home.join("queue"))
520 .list()
521 .into_iter()
522 .map(|task| Current {
523 worker: None,
524 task: task.id.clone(),
525 run: task.execution_runs().last().cloned().unwrap_or_default(),
526 }),
527 );
528 current.extend(
529 crate::run::list_ids_in(&home.join("runs"))
530 .into_iter()
531 .map(|run| Current {
532 worker: None,
533 task: String::new(),
534 run,
535 }),
536 );
537 }
538 }
539 current
540}
541
542#[must_use]
544pub fn is_working_on(home: &Path, run: &str, now: Timestamp) -> bool {
545 current_work(home, now).iter().any(|c| c.run == run)
546}
547
548pub(crate) fn is_working_on_other(home: &Path, run: &str, now: Timestamp) -> Result<bool> {
553 let same_home = std::env::var_os("MAGI_WORKER_HOME")
556 .is_some_and(|worker_home| Path::new(&worker_home) == home);
557 let caller = if same_home {
558 crate::worker::current_job(home)?
559 } else {
560 None
561 }
562 .filter(|job| {
563 job.kind == "task"
564 && job.status == crate::worker::Status::Running
565 && job.pid == Some(std::process::id())
566 });
567 Ok(other_claims_run(
568 ¤t_work(home, now),
569 run,
570 caller.as_ref().map(|job| job.id.as_str()),
571 ))
572}
573
574fn other_claims_run(claims: &[Current], run: &str, caller: Option<&str>) -> bool {
575 claims
576 .iter()
577 .any(|claim| claim.run == run && !(caller.is_some() && claim.worker.as_deref() == caller))
578}
579
580#[must_use]
590pub fn is_working_on_short(home: &Path, short: &str, now: Timestamp) -> bool {
591 current_work(home, now)
592 .iter()
593 .any(|c| crate::run::short_of(&c.run) == short)
594}
595
596#[must_use]
598pub fn is_working_on_task(home: &Path, task: &str, now: Timestamp) -> bool {
599 current_work(home, now).iter().any(|c| c.task == task)
600}
601
602pub fn sweep_stale_claims(queue: &Queue, older_than: Duration) -> Vec<String> {
642 sweep_stale_claims_with(queue, older_than, crate::proc::pid_alive)
643}
644
645fn sweep_stale_claims_with<F>(queue: &Queue, older_than: Duration, pid_alive: F) -> Vec<String>
649where
650 F: Fn(u32) -> bool,
651{
652 let this_process = std::process::id();
653 let mut swept: Vec<String> = std::fs::read_dir(queue.root())
654 .into_iter()
655 .flatten()
656 .flatten()
657 .map(|e| e.path())
658 .filter(|p| p.extension().is_some_and(|x| x == "lock"))
659 .filter(|p| {
660 match std::fs::read_to_string(p)
661 .ok()
662 .and_then(|body| body.trim().parse::<u32>().ok())
663 {
664 Some(pid) if pid == this_process => false,
668 Some(pid) => !pid_alive(pid),
669 None => p
670 .metadata()
671 .and_then(|m| m.modified())
672 .and_then(|t| t.elapsed().map_err(std::io::Error::other))
673 .is_ok_and(|age| age >= older_than),
674 }
675 })
676 .filter(|p| std::fs::remove_file(p).is_ok())
677 .filter_map(|p| {
678 p.file_stem()
679 .and_then(|s| s.to_str())
680 .map(std::borrow::ToOwned::to_owned)
681 })
682 .collect();
683 swept.sort_unstable();
684 swept
685}
686
687fn is_stalled(task: &Task, home: &Path, now: Timestamp) -> bool {
692 task.status == TaskStatus::Running
693 && (now.as_second() - task.updated_at.as_second()) >= STALLED_RUNNING.as_secs() as i64
694 && !is_working_on_task(home, &task.id, now)
695}
696
697fn stalled_tasks(queue: &Queue, home: &Path, now: Timestamp) -> Vec<Task> {
700 queue
701 .list()
702 .into_iter()
703 .filter(|t| is_stalled(t, home, now))
704 .collect()
705}
706
707fn queued_tasks(queue: &Queue) -> Vec<Task> {
713 queue
714 .list()
715 .into_iter()
716 .filter(|t| t.status == TaskStatus::Queued)
717 .collect()
718}
719
720fn finished_tasks(queue: &Queue) -> Vec<Task> {
723 queue
724 .list()
725 .into_iter()
726 .filter(|t| matches!(t.status, TaskStatus::Failed | TaskStatus::Held))
727 .collect()
728}
729
730fn resolve_blockers(queue: &Queue, questions: &Questions) {
747 for listed in queue.list() {
748 if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
749 continue;
750 }
751 let Ok(_claim) = queue.claim(&listed.id) else {
752 continue;
753 };
754 let Ok(mut task) = queue.get(&listed.id) else {
755 continue;
756 };
757 if task.status != TaskStatus::Blocked {
758 continue;
759 }
760 let deleted = queue.apply_deleted_blockers(&mut task, questions);
764 if !deleted.is_empty() {
765 record(queue, &mut task);
766 for id in &deleted {
767 queue.note_dependency_deleted(&task, id);
768 }
769 if task.status != TaskStatus::Blocked {
770 continue;
771 }
772 }
773 let missing = crate::queue::missing_blockers(queue, questions, &task.blocked_by);
774 if !missing.is_empty() {
775 let language = language_of(&task, Path::new("."));
776 let mut cause = missing.clone();
777 cause.sort();
778 cause.dedup();
779 task.notice_cause(&format!("missing-blockers:{}", cause.join(",")), None, None);
780 task.hold_machine(Some(crate::queue::missing_blocker_hold_reason_in(
781 &task.blocked_by,
782 &missing,
783 &language,
784 )));
785 record(queue, &mut task);
786 continue;
787 }
788 if let Some(q) = task.blocked_by.iter().find_map(|id| {
791 let crate::queue::Dependency::Question(full) =
792 crate::queue::dependency(queue, questions, id)
793 else {
794 return None;
795 };
796 questions.get_for_effects(&full).ok().filter(|q| {
797 q.node == crate::conduct::NODE && q.status == ask::QuestionStatus::Abandoned
798 })
799 }) {
800 let language = language_of(&task, Path::new("."));
801 task.notice_cause(&format!("unanswered-question:{}", q.id), None, None);
802 task.hold_machine(Some(unanswered_question_hold_reason(&q, &language)));
803 record(queue, &mut task);
804 continue;
805 }
806 let mut changed = false;
807 for id in task.blocked_by.clone() {
808 let resolved = crate::queue::dependency(queue, questions, &id);
809 if let crate::queue::Dependency::Task(full) = &resolved {
810 if queue
811 .get(full)
812 .is_ok_and(|dep| dep.status == TaskStatus::Done)
813 {
814 task.unblock(&id);
815 changed = true;
816 }
817 continue;
818 }
819 if let crate::queue::Dependency::Question(full) = resolved
820 && let Ok(q) = questions.get_for_effects(&full)
821 && q.status == ask::QuestionStatus::Answered
822 {
823 if q.node == crate::conduct::NODE
827 && q.chosen_action().is_some()
828 && !task.action_applied(&q.id)
829 {
830 continue;
831 }
832 let answer = match &q.answer {
833 Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
834 None => String::new(),
835 };
836 task.record_answer(q.summary.clone(), answer);
837 task.unblock(&id);
838 changed = true;
839 }
840 }
841 if changed {
842 record(queue, &mut task);
843 }
844 }
845}
846
847fn unanswered_question_hold_reason(q: &ask::Question, language: &str) -> String {
849 if crate::lang::is_japanese(language) {
850 format!(
851 "質問 {} 「{}」 に期限内の回答がなく、取り下げられました - `magi task triage` を参照",
852 q.short(),
853 q.summary
854 )
855 } else {
856 format!(
857 "question {} \"{}\" went unanswered and was abandoned - see `magi task triage`",
858 q.short(),
859 q.summary
860 )
861 }
862}
863
864#[derive(Debug, Clone, Copy, PartialEq, Eq)]
867pub(crate) enum ActionStanding {
868 NoAction,
870 Pending,
872 Applied,
875 Stale,
877 Busy,
879}
880
881impl ActionStanding {
882 pub(crate) fn daemon_owns(self) -> bool {
884 matches!(self, Self::Pending | Self::Applied | Self::Stale)
885 }
886}
887
888pub(crate) fn action_standing(task: &Task, q: &ask::Question) -> ActionStanding {
892 if task.stale_question(q) {
893 ActionStanding::Stale
894 } else if q.chosen_action().is_none() {
895 ActionStanding::NoAction
896 } else if task.action_applied(&q.id) {
897 ActionStanding::Applied
898 } else if q.node != crate::conduct::NODE && task.execution_runs().last() != Some(&q.run) {
899 ActionStanding::Stale
900 } else if matches!(
901 task.status,
902 TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
903 ) {
904 ActionStanding::Busy
905 } else {
906 ActionStanding::Pending
907 }
908}
909
910#[derive(Debug, Clone, PartialEq, Eq)]
912enum ActionDecision {
913 Skip,
915 Resume(String),
917 Requeue,
919 Hold,
921 Done,
923 Stale,
926 Refuse(String),
929}
930
931fn decide_action<F>(
940 home: &Path,
941 task: &Task,
942 q: &ask::Question,
943 p: &Phrases,
944 load: F,
945) -> ActionDecision
946where
947 F: FnOnce(&str) -> Result<RunState>,
948{
949 if task.stale_question(q) {
950 return ActionDecision::Stale;
951 }
952 let Some(action) = q.chosen_action() else {
953 return ActionDecision::Skip;
954 };
955 if task.action_applied(&q.id)
956 || matches!(
957 task.status,
958 TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
959 )
960 {
961 return ActionDecision::Skip;
962 }
963 if q.node != crate::conduct::NODE && task.execution_runs().last() != Some(&q.run) {
966 return ActionDecision::Stale;
967 }
968 let repair = q.node == land::APPROVAL_NODE && q.resolution().as_deref() == Some(land::REPAIR);
969 let stopping = q.node == land::APPROVAL_NODE
970 && q.resolution()
971 .as_deref()
972 .is_some_and(crate::merge_decision::stops);
973 let decision_at = q.answered_at.unwrap_or(q.asked_at);
977 if task.operator_decided_at.is_some_and(|at| at > decision_at) {
978 return if repair || stopping {
979 ActionDecision::Refuse(format!(
980 "{} 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 {}`",
981 if repair { "repair" } else { "stop" },
982 q.id,
983 q.run,
984 task.id
985 ))
986 } else {
987 ActionDecision::Stale
988 };
989 }
990 match action {
991 a if a.maintenance() => ActionDecision::Skip,
992 ask::ChoiceAction::RecoverBase { .. }
993 | ask::ChoiceAction::ResumeRun { .. }
994 | ask::ChoiceAction::ReleaseTask { .. }
995 | ask::ChoiceAction::RerunChecks { .. }
996 | ask::ChoiceAction::AbandonRun { .. } => unreachable!(),
997 ask::ChoiceAction::Requeue => ActionDecision::Requeue,
998 ask::ChoiceAction::Hold => ActionDecision::Hold,
999 ask::ChoiceAction::Done => ActionDecision::Done,
1000 ask::ChoiceAction::Resume { run } => {
1001 if task.execution_runs().last() != Some(run) {
1002 return ActionDecision::Refuse((p.resume_not_latest)(
1003 q.short(),
1004 ask::short_id(run),
1005 ));
1006 }
1007 match load(run) {
1008 Ok(s) if stopping => {
1009 if s.merge_decision.as_ref().is_some_and(|d| d.closed)
1010 || !s
1011 .land_approval
1012 .as_ref()
1013 .is_some_and(|binding| binding.question == q.id)
1014 {
1015 ActionDecision::Stale
1016 } else if s.liveness_under(home, false) == Liveness::Live {
1017 ActionDecision::Skip
1018 } else if s.status == RunStatus::Landing
1019 && !s.released()
1020 && s.retired_to.is_none()
1021 {
1022 ActionDecision::Resume(run.clone())
1023 } else {
1024 ActionDecision::Refuse("Owner stop decision cannot resume its original landing execution; inspect the existing run. No replacement or merge was started.".into())
1025 }
1026 }
1027 Ok(s)
1028 if q.node == land::APPROVAL_NODE
1029 && q.resolution().as_deref() == Some(land::REPAIR) =>
1030 {
1031 if s.merge_repairs.iter().any(|r| r.question == q.id)
1032 || s.land_approval.as_ref().is_some_and(|a| a.question != q.id)
1033 {
1034 ActionDecision::Stale
1037 } else if s.liveness_under(home, false) == Liveness::Live {
1038 ActionDecision::Skip
1039 } else if s.status != RunStatus::Landing
1040 || s.released()
1041 || s.reviews.is_empty()
1042 || !implementers_match(task, &s)
1043 || !s
1044 .land_approval
1045 .as_ref()
1046 .is_some_and(|a| a.question == q.id && !a.head.is_empty())
1047 {
1048 ActionDecision::Refuse(format!(
1049 "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",
1050 q.id, run, run
1051 ))
1052 } else {
1053 ActionDecision::Resume(run.clone())
1054 }
1055 }
1056 Ok(s) if s.liveness_under(home, false) == Liveness::Live => {
1057 ActionDecision::Refuse("run already has a live driver".into())
1058 }
1059 Ok(s) => match crate::handover::resume_refusal_under(&s, Some(home)) {
1060 None => ActionDecision::Resume(run.clone()),
1061 Some(reason) => ActionDecision::Refuse((p.resume_cannot_progress)(
1062 q.short(),
1063 ask::short_id(run),
1064 &reason.diagnostic(&s),
1065 )),
1066 },
1067 Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
1068 q.short(),
1069 ask::short_id(run),
1070 &format!("{e:#}"),
1071 )),
1072 }
1073 }
1074 }
1075}
1076
1077struct Phrases {
1091 graph_stopped: fn(&str, &str) -> String,
1093 quorum_lost: &'static str,
1094 quota_took_out: &'static str,
1096 run_ended: &'static str,
1098 waiting_for_answer: &'static str,
1100 recovered_running: &'static str,
1101 no_run_to_recover: &'static str,
1102 could_not_start: &'static str,
1103 resume_not_latest: fn(&str, &str) -> String,
1104 resume_cannot_progress: fn(&str, &str, &str) -> String,
1105 resume_unreadable: fn(&str, &str, &str) -> String,
1106 handover_refused: fn(&crate::handover::Refused) -> String,
1109 handover_hint: &'static str,
1111 reviewers_never_answered: fn(usize, usize) -> String,
1114}
1115
1116const PHRASES_EN: Phrases = Phrases {
1117 graph_stopped: |status, detail| {
1118 format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
1119 },
1120 quorum_lost: "the judging panel lost its quorum",
1121 quota_took_out: "; quota took out ",
1122 run_ended: "run ended ",
1123 waiting_for_answer: " - waiting for operator answer to question ",
1124 recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
1125 no_run_to_recover: "task was `running` with no live daemon and no readable \
1126 run to recover; held for a human to check what happened",
1127 could_not_start: "could not start the run: ",
1128 resume_not_latest: |q, run| {
1129 format!("question {q} asked to resume run {run}, which is not this task's latest run")
1130 },
1131 resume_cannot_progress: |q, run, reason| {
1132 format!("question {q} asked to resume run {run}, which cannot make progress: {reason}")
1133 },
1134 resume_unreadable: |q, run, e| {
1135 format!("question {q} asked to resume run {run}, which could not be read: {e}")
1136 },
1137 handover_refused: |r| r.to_string(),
1138 handover_hint: " (clean up the other worktree, then release the task from the queue)",
1139 reviewers_never_answered: |missing, rounds| {
1140 format!(
1141 "{missing} reviewer seat(s) never answered after {rounds} rounds; \
1142 refusing to call it clean"
1143 )
1144 },
1145};
1146
1147const PHRASES_JA: Phrases = Phrases {
1148 graph_stopped: |status, detail| {
1149 format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
1150 },
1151 quorum_lost: "審査パネルが定足数を失いました",
1152 quota_took_out: "。クォータで脱落: ",
1153 run_ended: "run 終了: ",
1154 waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
1155 recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
1156 no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
1157 何が起きたか人が確認するため保留にしました",
1158 could_not_start: "run を開始できませんでした: ",
1159 resume_not_latest: |q, run| {
1160 format!(
1161 "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
1162 )
1163 },
1164 resume_cannot_progress: |q, run, reason| {
1165 format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません: {reason}")
1166 },
1167 resume_unreadable: |q, run, e| {
1168 format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
1169 },
1170 handover_refused: |r| {
1171 use crate::handover::Refused;
1172 match r {
1173 Refused::Foreign { branch, path, why } => format!(
1174 "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
1175 削除しません。不要なら `git worktree remove` でその worktree を削除して\
1176 から、やり直してください(詳細: {why})"
1177 ),
1178 Refused::Unsafe { branch, path, why } => format!(
1179 "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
1180 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
1181 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
1182 ),
1183 Refused::ReleaseFailed { branch, path, run } => format!(
1184 "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
1185 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1186 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1187 ),
1188 }
1189 },
1190 handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1191 reviewers_never_answered: |missing, rounds| {
1192 format!(
1193 "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1194 クリーンとは認めません"
1195 )
1196 },
1197};
1198
1199fn phrases(language: &str) -> &'static Phrases {
1200 if crate::lang::is_japanese(language) {
1201 &PHRASES_JA
1202 } else {
1203 &PHRASES_EN
1204 }
1205}
1206
1207fn language_of(task: &Task, fallback: &Path) -> String {
1211 crate::lang::of_repo(&repo_for(task, fallback))
1212}
1213
1214pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1218 if q.node == crate::conduct::NODE {
1219 return tasks.iter().find(|t| t.id == q.run);
1220 }
1221 tasks.iter().find(|t| t.runs.contains(&q.run))
1222}
1223
1224fn repair_choice_offers(questions: &Questions) {
1227 let ownership = crate::task_chat::InquiryOwnership::default();
1228 for q in questions
1229 .list_for_effects_in(&ownership)
1230 .into_iter()
1231 .filter(|q| {
1232 q.status.open()
1233 && q.node == crate::conduct::NODE
1234 && q.choices
1235 .iter()
1236 .any(|c| crate::choice_effect::describe(q, c).is_none())
1237 })
1238 {
1239 let _ = questions.update_in(&q.id, &ownership, |current| {
1240 if current.status.open() {
1241 crate::choice_effect::executable_conductor(current);
1242 if let Some(deputy) = &mut current.deputy {
1243 deputy.brief = crate::deputy::brief(
1244 ¤t.run,
1245 ¤t.detail,
1246 ¤t.choices,
1247 ¤t.actions,
1248 );
1249 }
1250 }
1251 Ok(())
1252 });
1253 }
1254}
1255
1256pub async fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1259 apply_maintenance_choices(queue, questions, home).await;
1260 apply_task_choice_actions(queue, questions, home);
1261}
1262
1263async fn apply_maintenance_choices(queue: &Queue, questions: &Questions, home: &Path) {
1266 let ownership = crate::task_chat::InquiryOwnership::default();
1267 for q in questions.list_for_effects_in(&ownership) {
1268 let Ok(_execution) = crate::task_inquiry::Outbox::at(home).execution_claim(&q.id) else {
1270 continue;
1271 };
1272 let Ok(q) = questions.get_for_effects_in(&q.id, &ownership) else {
1273 continue;
1274 };
1275 let Some(action) = q.chosen_action().filter(|a| a.maintenance()) else {
1276 continue;
1277 };
1278 if asker_may_still_read(questions, &q, home) || !ask::valid_asset_name(&q.id) {
1281 continue;
1282 }
1283 if queue.list().iter().any(|task| {
1284 (task.id == q.run
1285 || task.runs.contains(&q.run)
1286 || q.routed_task.as_deref() == Some(&task.id))
1287 && task.stale_question(&q)
1288 }) {
1289 continue;
1290 }
1291 if let ask::ChoiceAction::RecoverBase { run, stop, episode } = action {
1292 let tasks = queue.list();
1293 let owner = crate::task_chat::task_of(&q, &tasks);
1294 if let Some(owner) = owner
1295 && q.routed_task
1296 .as_deref()
1297 .is_none_or(|routed| routed == owner)
1298 {
1299 let result = crate::base_recovery_control::recover(
1300 queue,
1301 home,
1302 crate::base_recovery_control::Request {
1303 run: run.clone(),
1304 head: stop.head.clone(),
1305 actor: "decisions".into(),
1306 request: q.id.clone(),
1307 decision: Some((owner, q.answered_at.unwrap_or(q.asked_at))),
1308 expected_stop: Some((stop.clone(), *episode)),
1309 },
1310 )
1311 .await;
1312 if let Err(error) = result {
1313 tracing::warn!(question = %q.id, %error, "base recovery decision refused");
1314 notices::raise_in(home, Notice::warn(
1315 &format!("base-recovery:{}", q.id),
1316 format!("Base recovery decision {} was refused: {error:#}. Inspect the existing run and request; no replacement run was started.", q.id),
1317 ).link(Link::Run { id: run.clone() }));
1318 }
1319 }
1320 continue;
1321 }
1322 let dir = home.join("choice-actions");
1323 if std::fs::create_dir_all(&dir).is_err() {
1324 continue;
1325 }
1326 let Ok(lock) = std::fs::OpenOptions::new()
1327 .create(true)
1328 .truncate(false)
1329 .write(true)
1330 .open(dir.join(format!("{}.lock", q.id)))
1331 else {
1332 continue;
1333 };
1334 if crate::pr_head::try_lock_file(&lock).is_err() {
1335 continue;
1336 }
1337 let fresh = !home
1338 .join("choice-actions")
1339 .join(format!("{}.json", q.id))
1340 .exists();
1341 let result = async {
1342 let receipt = dir.join(format!("{}.json", q.id));
1343 if receipt.exists() {
1344 let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&receipt)?)?;
1345 anyhow::ensure!(
1346 prior.get("status").and_then(|s| s.as_str()) == Some("applied"),
1347 "previous maintenance attempt did not confirm completion; inspect its receipt"
1348 );
1349 return Ok::<_, anyhow::Error>(());
1350 }
1351 let record = |status: &str| -> anyhow::Result<()> {
1354 let tmp = receipt.with_extension("tmp");
1355 std::fs::write(
1356 &tmp,
1357 serde_json::to_vec(&serde_json::json!({
1358 "action": action, "status": status,
1359 }))?,
1360 )?;
1361 std::fs::rename(tmp, &receipt)?;
1362 Ok(())
1363 };
1364 let applied = async {
1365 match action {
1366 ask::ChoiceAction::ResumeRun { run } => {
1367 crate::resume::validate(home, run)?;
1368 record("started")?;
1369 let decided = q.answered_at.unwrap_or(q.asked_at);
1370 if !crate::resume::pin_queued(queue, run, Some(decided), Some(&q.id))? {
1371 crate::resume::validate_unqueued(home, run)?;
1372 crate::resume::start(home, run.clone()).await?;
1373 }
1374 }
1375 ask::ChoiceAction::ReleaseTask {
1376 task,
1377 held_at,
1378 reason,
1379 } => {
1380 anyhow::ensure!(
1381 queue.resolve_id(task)? == *task,
1382 "task action requires an exact task ID"
1383 );
1384 let _claim = queue.claim(task)?;
1385 let mut task = queue.get(task)?;
1386 if task.action_applied(&q.id) {
1387 return Ok(());
1388 }
1389 if q.node == crate::conduct::NODE
1394 && q.run == task.id
1395 && task.status == TaskStatus::Blocked
1396 && task.blocked_from == Some(TaskStatus::Held)
1397 && task.blocked_by.as_slice() == [q.id.as_str()]
1398 {
1399 task.unblock(&q.id);
1400 }
1401 anyhow::ensure!(
1402 task.status == TaskStatus::Held
1403 && task.held_at == Some(*held_at)
1404 && task.hold_reason.as_deref() == reason.as_deref()
1405 && task
1406 .operator_decided_at
1407 .is_none_or(|at| at <= q.answered_at.unwrap_or(q.asked_at)),
1408 "task no longer has the hold this question names"
1409 );
1410 task.release_operator("choice", Some(&q.id));
1411 task.mark_action_applied(&q.id);
1412 queue.put(&mut task)?;
1413 }
1414 ask::ChoiceAction::AbandonRun { run } => {
1415 record("started")?;
1416 crate::driver::abandon_proven_dead(home, run)?;
1417 }
1418 ask::ChoiceAction::RerunChecks {
1419 repo,
1420 pr,
1421 head,
1422 runs,
1423 } => {
1424 rerun_checks_once(home, &q.id, repo, pr, head, runs, || record("started"))
1425 .await?;
1426 }
1427 _ => unreachable!(),
1428 }
1429 Ok::<_, anyhow::Error>(())
1430 }
1431 .await;
1432 match applied {
1433 Ok(()) => record("applied"),
1434 Err(e) => {
1435 record(&format!("refused or failed: {e:#}"))?;
1436 Err(e)
1437 }
1438 }
1439 }
1440 .await;
1441 if home
1446 .join("choice-actions")
1447 .join(format!("{}.json", q.id))
1448 .exists()
1449 && let Some(listed) = task_of_question(&queue.list(), &q)
1450 && !listed.action_applied(&q.id)
1451 && let Ok(_claim) = queue.claim(&listed.id)
1452 && let Ok(mut origin) = queue.get(&listed.id)
1453 {
1454 if !origin.operator_held()
1455 && origin.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1456 && !matches!(origin.status, TaskStatus::Running | TaskStatus::Done)
1457 {
1458 if result.is_err() || matches!(action, ask::ChoiceAction::ResumeRun { .. }) {
1459 origin.hold_machine(Some(format!(
1460 "Maintenance choice {} settled; inspect its target before releasing this task",
1461 q.id
1462 )));
1463 } else {
1464 origin.unblock(&q.id);
1465 }
1466 }
1467 origin.mark_action_applied(&q.id);
1468 let _ = queue.put(&mut origin);
1469 }
1470 if let Err(e) = result
1471 && fresh
1472 {
1473 notices::raise_in(
1474 home,
1475 Notice::warn(
1476 &format!("action:{}", q.id),
1477 format!("Choice action {} was not completed: {e:#}", q.id),
1478 )
1479 .link(if q.run_names_task() {
1480 Link::Task { id: q.run.clone() }
1481 } else {
1482 Link::Run { id: q.run.clone() }
1483 }),
1484 );
1485 }
1486 }
1487}
1488
1489pub(crate) async fn rerun_checks_once(
1496 home: &Path,
1497 request: &str,
1498 repo: &Path,
1499 pr: &str,
1500 head: &str,
1501 runs: &[String],
1502 started: impl FnOnce() -> anyhow::Result<()>,
1503) -> anyhow::Result<()> {
1504 use crate::release_watch::{GhForge, ReleaseForge};
1505 anyhow::ensure!(
1506 !runs.is_empty()
1507 && runs.len() <= 20
1508 && runs
1509 .iter()
1510 .all(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
1511 && !pr.starts_with('-'),
1512 "invalid rerun targets"
1513 );
1514 let snap = GhForge.snapshot(repo, pr).await?;
1515 anyhow::ensure!(
1516 snap.head == head && snap.state == crate::land::PrLifecycle::Open,
1517 "pull request head or lifecycle changed"
1518 );
1519 anyhow::ensure!(
1520 runs.iter().all(|r| snap
1521 .checks
1522 .iter()
1523 .any(|c| c.run.as_ref() == Some(r) && crate::release_watch::is_failed(c.verdict))),
1524 "named workflow is no longer failed on this pull request"
1525 );
1526 started()?;
1527 let dir = home.join("choice-actions");
1528 std::fs::create_dir_all(&dir)?;
1529 let rerun_lock = std::fs::OpenOptions::new()
1530 .create(true)
1531 .truncate(false)
1532 .write(true)
1533 .open(dir.join("reruns.lock"))?;
1534 crate::pr_head::try_lock_file(&rerun_lock)?;
1535 let ledger = dir.join("reruns.json");
1536 let mut recorded: std::collections::BTreeSet<String> = if ledger.exists() {
1537 serde_json::from_slice(&std::fs::read(&ledger)?)?
1538 } else {
1539 Default::default()
1540 };
1541 for run in runs {
1542 let key = serde_json::to_string(&(request, repo, pr, head, run))?;
1543 if !recorded.insert(key) {
1544 continue;
1545 }
1546 let tmp = ledger.with_extension("tmp");
1547 std::fs::write(&tmp, serde_json::to_vec(&recorded)?)?;
1548 std::fs::rename(tmp, &ledger)?;
1549 GhForge.rerun(repo, run).await?;
1550 }
1551 Ok(())
1552}
1553
1554pub(crate) fn apply_task_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1563 let tasks = queue.list();
1564 let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
1565 for q in questions.list_for_effects_in(&ownership) {
1566 let Ok(_execution) = crate::task_inquiry::Outbox::at(home).execution_claim(&q.id) else {
1568 continue;
1569 };
1570 let Ok(q) = questions.get_for_effects_in(&q.id, &ownership) else {
1571 continue;
1572 };
1573 if q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1575 continue;
1576 }
1577 if q.chosen_action().is_none_or(|a| a.maintenance()) {
1578 continue;
1579 }
1580 let Some(listed) = task_of_question(&tasks, &q) else {
1581 if q.node == land::APPROVAL_NODE
1582 && q.resolution().as_deref().is_some_and(|choice| {
1583 choice == land::REPAIR || crate::merge_decision::stops(choice)
1584 })
1585 {
1586 notices::raise_in(
1587 home,
1588 Notice::warn(
1589 &format!("repair-owner:{}", q.id),
1590 format!(
1591 "Approval action is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing task.",
1592 q.run, q.run
1593 ),
1594 ).link(Link::Run { id: q.run.clone() }),
1595 );
1596 }
1597 continue;
1598 };
1599 if listed.action_applied(&q.id) {
1600 continue;
1601 }
1602 let Ok(_claim) = queue.claim(&listed.id) else {
1603 continue;
1604 };
1605 let Ok(mut task) = queue.get(&listed.id) else {
1606 continue;
1607 };
1608 if q.node == crate::conduct::NODE && task.status == TaskStatus::Blocked {
1611 let blockers: Vec<_> = task
1612 .blocked_by
1613 .iter()
1614 .filter(|id| {
1615 crate::queue::dependency(queue, questions, id)
1616 == crate::queue::Dependency::Question(q.id.clone())
1617 })
1618 .cloned()
1619 .collect();
1620 if !blockers.is_empty() {
1621 for id in blockers {
1622 task.unblock(&id);
1623 }
1624 let answer = match &q.answer {
1625 Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
1626 None => String::new(),
1627 };
1628 task.record_answer(q.summary.clone(), answer);
1629 }
1630 }
1631 let language = language_of(&task, Path::new("."));
1632 let decision = decide_action(home, &task, &q, phrases(&language), |id| {
1633 RunState::load_under(id, home)
1634 });
1635 let ran = matches!(
1636 decision,
1637 ActionDecision::Resume(_)
1638 | ActionDecision::Requeue
1639 | ActionDecision::Hold
1640 | ActionDecision::Done
1641 );
1642 if ran && asker_may_still_read(questions, &q, home) {
1643 continue;
1652 }
1653 let done = matches!(decision, ActionDecision::Done);
1654 let completed = matches!(
1657 decision,
1658 ActionDecision::Requeue | ActionDecision::Hold | ActionDecision::Done
1659 );
1660 match decision {
1661 ActionDecision::Skip => continue,
1662 ActionDecision::Resume(run) => {
1663 task.release_operator("choice", Some(&q.id));
1664 task.resume_override = Some(crate::queue::OperatorResume {
1665 question_id: q.id.clone(),
1666 at: Timestamp::now(),
1667 conductor_rehold: None,
1668 forced: true,
1669 pinned_run: Some(run),
1670 });
1671 }
1672 ActionDecision::Stale => {}
1673 ActionDecision::Requeue => {
1674 task.release_operator("choice-requeue", Some(&q.id));
1675 task.requeue();
1676 }
1677 ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1678 ActionDecision::Done => task.succeed(),
1679 ActionDecision::Refuse(why) => {
1680 let _ =
1681 crate::task_inquiry::Outbox::at(home).update_decision(&q.id, |d| d.fail(&why));
1682 if task.operator_held() {
1683 task.hold_reason = Some(match task.hold_reason.take() {
1686 Some(reason) => format!("{reason}\n\n{why}"),
1687 None => why,
1688 });
1689 } else {
1690 task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1691 task.hold_machine(Some(why));
1692 }
1693 notices::raise(
1694 Notice::warn(
1695 &format!("action:{}", q.id),
1696 "An answer asked the daemon to resume a run that cannot be resumed; the task stays held.",
1697 )
1698 .link(Link::Task {
1699 id: task.id.clone(),
1700 }),
1701 );
1702 }
1703 }
1704 task.mark_action_applied(&q.id);
1705 if completed {
1706 task.decision_effects.insert(
1707 q.id.clone(),
1708 format!("decision: {}", q.resolution().expect("answered action")),
1709 );
1710 }
1711 record(queue, &mut task);
1714 if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1715 supersede_prior_runs(&task, home);
1716 }
1717 let _ = questions.update_in(&q.id, &ownership, |r| {
1720 r.answer_delivered = true;
1721 Ok(())
1722 });
1723 }
1724}
1725
1726fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1730 let now = Timestamp::now();
1731 if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1732 return true;
1733 }
1734 q.node != crate::conduct::NODE
1735 && RunState::load_under(&q.run, home).is_ok_and(|s| {
1736 s.seats_active()
1737 .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1738 })
1739}
1740
1741fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1752 let tasks = queue.list();
1753 let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
1754 let by_id: std::collections::BTreeMap<&str, &Task> =
1755 tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1756 let referenced: Vec<&str> = tasks
1757 .iter()
1758 .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1759 .collect();
1760
1761 for mut question in questions.list_for_effects_in(&ownership) {
1762 if !question.status.open()
1763 || question.node != crate::conduct::NODE
1764 || questions.held_reply_in(&question.id, &ownership)
1765 {
1766 continue;
1767 }
1768 if referenced
1773 .iter()
1774 .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1775 {
1776 continue;
1777 }
1778 let Some(task) = by_id.get(question.run.as_str()) else {
1779 continue;
1780 };
1781 question.abandon(format!(
1782 "task {} no longer waits for this answer",
1783 task.short()
1784 ));
1785 if let Err(e) = questions.put_in(&mut question, &ownership) {
1786 tracing::warn!(
1787 "could not retire question {} for task {}: {e:#}",
1788 question.short(),
1789 task.short()
1790 );
1791 }
1792 }
1793}
1794
1795#[derive(Debug, Clone, Copy)]
1802pub struct Verdict {
1803 pub status: RunStatus,
1805 pub left_pr: bool,
1807 pub quota_hit: bool,
1809 pub parked: bool,
1811 pub no_viable_candidates: bool,
1818}
1819
1820pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1879 settle_in(task, verdict, detail, max_attempts, &PHRASES_EN)
1880}
1881
1882fn settle_in(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize, p: &Phrases) {
1884 if verdict.parked {
1890 task.park(detail);
1891 return;
1892 }
1893 match verdict.status {
1894 RunStatus::Merged | RunStatus::Ready
1895 if task.pr_recovery.as_ref().is_some_and(|s| {
1896 s.disposition != Some(crate::pr_recovery::Disposition::Review)
1897 }) =>
1898 {
1899 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()));
1900 }
1901 RunStatus::Merged | RunStatus::Ready => task.succeed(),
1902 RunStatus::AlreadyInBase => task.already_landed(detail),
1903 RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1904 RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1905 task.stall(detail)
1906 }
1907 RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1908 RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1909 RunStatus::Blocked => task.fail(detail, max_attempts),
1910 RunStatus::VerifiedNoop => task.handed_off(detail),
1911 other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1912 }
1913}
1914
1915pub fn supersede_prior_runs(task: &Task, home: &Path) {
1964 let now = Timestamp::now();
1965 let last_run_succeeded = task
1972 .runs
1973 .last()
1974 .and_then(|id| RunState::load_under(id, home).ok())
1975 .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
1976 for id in task.superseded_attempts(last_run_succeeded) {
1977 let mut state = match RunState::load_under(id, home) {
1978 Ok(s) => s,
1979 Err(e) => {
1980 tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
1981 continue;
1982 }
1983 };
1984 if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
1985 continue;
1986 }
1987 let daemon_claims = is_working_on(home, id, now);
1988 if state.liveness(daemon_claims) == Liveness::Live {
1989 continue;
1990 }
1991 state.status = RunStatus::Superseded;
1992 if let Err(e) = state.save_under(home) {
1993 tracing::warn!("could not mark run {id} superseded: {e:#}");
1994 }
1995 }
1996}
1997
1998fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
2020 for task in queue.list() {
2021 if task.status != TaskStatus::Done || task.runs.len() < 2 {
2022 continue;
2023 }
2024 supersede_prior_runs(&task, home);
2025 }
2026}
2027
2028fn settle_and_diagnose(
2035 task: &mut Task,
2036 verdict: Verdict,
2037 detail: &str,
2038 max_attempts: usize,
2039 state: &RunState,
2040) {
2041 let p = phrases(&state.config.graph.language);
2042 if let Some(d) = &state.merge_decision {
2045 use crate::merge_decision as md;
2046 if task
2047 .execution_runs()
2048 .last()
2049 .is_some_and(|id| id != &state.id)
2050 {
2051 return;
2052 }
2053 if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
2054 task.succeed();
2055 } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
2056 if state.liveness(false) != Liveness::Dead {
2057 task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
2058 return;
2059 }
2060 let replacement = md::Replacement {
2061 question: d.question.clone(),
2062 run: state.id.clone(),
2063 pr: d.target.pr.clone(),
2064 agent: agent.to_owned(),
2065 context: format!(
2066 "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
2067 d.target.pr,
2068 state.id,
2069 serde_json::to_string(&state.reviews).unwrap_or_default()
2070 ),
2071 };
2072 task.requeue();
2073 task.pr_recovery = None;
2074 task.review_of = None;
2075 task.replacement = Some(replacement);
2076 } else {
2077 task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
2078 format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
2079 } 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())) }));
2080 }
2081 task.mark_action_applied(&d.question);
2082 if d.choice.eq_ignore_ascii_case(land::HOLD) {
2083 task.decision_effects
2084 .insert(d.question.clone(), format!("decision: {}", d.choice));
2085 }
2086 if let Some(pass) = state.passes.last() {
2087 task.record_pass_at(
2088 &state.id,
2089 pass.index,
2090 Some(pass.started_at),
2091 task.attempts,
2092 None,
2093 );
2094 }
2095 return;
2096 }
2097 if let Some(replacement) = &task.replacement
2098 && !state.parked
2099 && state.resource_block.is_none()
2100 && (state.viable().is_empty()
2101 || (state.status == RunStatus::Blocked && state.tally.is_none()))
2102 {
2103 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)));
2104 return;
2105 }
2106 if !verdict.parked && verdict.quota_hit && state.status == RunStatus::Stalled {
2107 let mut agents: Vec<_> = state
2108 .quota
2109 .iter()
2110 .filter(|q| {
2111 q.cause == crate::agent::QuotaCause::Authentication
2112 && state
2113 .passes
2114 .last()
2115 .is_none_or(|pass| q.at >= pass.started_at)
2116 })
2117 .map(|q| q.agent.as_str())
2118 .collect();
2119 agents.sort_unstable();
2120 agents.dedup();
2121 if !agents.is_empty() {
2122 task.stall(detail);
2123 task.notice_cause("agent-authentication", None, None);
2124 task.hold_machine(Some(format!("[authentication] Agents {} cannot authenticate; re-authenticate, then resume the held task. No attempt was spent.", agents.join(", "))));
2125 return;
2126 }
2127 }
2128 let attempts_before = task.attempts;
2129 if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
2136 let disk_checked_at = task.disk_checked_at;
2137 task.notice_cause(
2138 &format!("resource:{}:{}", block.kind, block.node),
2139 None,
2140 None,
2141 );
2142 task.last_error = Some(detail.to_owned());
2143 task.diagnostic = None;
2144 task.attempts = task.attempts.saturating_sub(1);
2145 if block.kind == "agent authentication" {
2146 task.hold_machine(Some(format!(
2147 "[authentication] {}; no attempt was spent",
2148 block.detail
2149 )));
2150 } else if block.kind == "agent usage limit" {
2151 if let Some(agent) = &state.config.graph.selected_implementer {
2153 task.hold_machine(Some(format!("[agent usage limit] Selected implementer `{agent}` is unavailable. No other implementer was dispatched; resume after usage is available. No attempt was spent.")));
2154 } else {
2155 task.status = TaskStatus::Failed;
2156 task.last_error = Some(block.detail.clone());
2157 }
2158 } else if block.kind == "disk pressure" {
2159 task.hold_machine(Some(format!(
2160 "{}{}",
2161 crate::disk::RUNNING_PRESSURE,
2162 block.detail
2163 )));
2164 } else {
2165 task.hold_machine(Some(format!(
2166 "{}{}; no attempt was spent; resume to retry the affected operation",
2167 crate::cache::RESOURCE_HOLD,
2168 block.description()
2169 )));
2170 }
2171 if matches!(block.kind.as_str(), "disk pressure" | "disk admission")
2172 && matches!(block.cause, crate::run::ResourceBlockCause::Other)
2173 {
2174 task.mark_disk_capacity();
2175 task.disk_checked_at = disk_checked_at;
2176 }
2177 if let Some(pass) = state.passes.last() {
2178 task.record_pass_at(
2179 &state.id,
2180 pass.index,
2181 Some(pass.started_at),
2182 attempts_before,
2183 None,
2184 );
2185 }
2186 return;
2187 }
2188 if let Some(hold) = state.land_unrelated.as_ref().filter(|hold| {
2189 state.parked
2190 && state.status == RunStatus::Landing
2191 && state
2192 .pr_pushed_head
2193 .as_ref()
2194 .is_none_or(|h| h == &hold.head)
2195 && task.execution_runs().last() == Some(&state.id)
2196 }) {
2197 let pass = state.passes.last().map_or(0, |p| p.index);
2200 if !task
2201 .passes
2202 .iter()
2203 .any(|p| p.run == state.id && p.pass_index == pass)
2204 {
2205 task.attempts = task.attempts.saturating_sub(1);
2206 }
2207 task.hold_machine(Some(format!(
2208 "[ci-unrelated] CI failure reproduced on base; owner question {}",
2209 hold.question
2210 )));
2211 task.last_error = Some(detail.to_owned());
2212 task.diagnostic = None;
2213 task.record_pass_at(
2214 &state.id,
2215 pass,
2216 state.passes.last().map(|p| p.started_at),
2217 attempts_before,
2218 Some(crate::run::ParkCause::Question),
2219 );
2220 return;
2221 }
2222 let unresolved = task.hold_notice_cause.clone();
2223 if state.base_sync_blocked() {
2224 task.hold_machine(Some(detail.to_owned()));
2226 task.last_error = Some(detail.to_owned());
2227 } else if !verdict.parked
2228 && task
2229 .pr_recovery
2230 .as_ref()
2231 .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
2232 && matches!(
2233 verdict.status,
2234 RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
2235 )
2236 {
2237 if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
2238 task.succeed();
2239 } else {
2240 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()));
2241 }
2242 } else if !verdict.parked
2243 && task.pr_recovery.is_some()
2244 && matches!(
2245 verdict.status,
2246 RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
2247 )
2248 && !verdict.quota_hit
2249 {
2250 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.")));
2251 } else {
2252 settle_in(task, verdict, detail, max_attempts, p);
2253 }
2254 if !verdict.parked
2255 && !verdict.quota_hit
2256 && matches!(
2257 verdict.status,
2258 RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
2259 )
2260 {
2261 task.recovery_failed(state);
2262 }
2263 if state.prep_failure.is_some() {
2264 task.hold_notice_cause = unresolved;
2267 task.startup_notice_cause("startup-candidates");
2268 }
2269 if let Some(pass) = state.passes.last() {
2272 let parked = match &pass.end {
2273 Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2274 _ => None,
2275 };
2276 task.record_pass_at(
2277 &state.id,
2278 pass.index,
2279 Some(pass.started_at),
2280 attempts_before,
2281 parked,
2282 );
2283 }
2284 if task.status == TaskStatus::Held {
2285 if state.base_sync_blocked() {
2286 task.base_sync_notice(state);
2287 } else if state.prep_failure.is_none() {
2288 task.notice_cause(
2289 label(verdict.status),
2290 Some(&state.id),
2291 state.passes.last().map(|p| p.index),
2292 );
2293 }
2294 task.diagnostic = diagnostic(state);
2295 note_open_question(task, &state.id, p);
2296 }
2297}
2298
2299fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2314 let Some(home) = crate::run::try_home() else {
2315 return;
2316 };
2317 let open = Questions::at(home.join("questions")).open_for(run);
2318 let Some(q) = open.first() else {
2319 return;
2320 };
2321 let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2322 decisions.sort_unstable();
2323 task.notice_cause(
2324 &format!("questions:{}", decisions.join(",")),
2325 Some(run),
2326 None,
2327 );
2328 let base = task.hold_reason.clone().unwrap_or_default();
2329 task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2330}
2331
2332fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2343 if let Some(request) = task.sync_only.clone() {
2344 crate::base_sync_only::settle(task, &request, last_run.as_ref(), None);
2345 return;
2346 }
2347 match last_run {
2348 Some(state) => {
2349 let verdict = Verdict {
2350 status: state.status,
2351 left_pr: state.pr.is_some(),
2352 quota_hit: state.quota.iter().any(|loss| {
2353 state
2354 .passes
2355 .last()
2356 .is_none_or(|pass| loss.at >= pass.started_at)
2357 }),
2358 parked: state.parked,
2359 no_viable_candidates: state.viable().is_empty(),
2360 };
2361 let detail = format!(
2362 "{}{}",
2363 phrases(&state.config.graph.language).recovered_running,
2364 describe(&state)
2365 );
2366 settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2367 }
2368 None => {
2369 let why = phrases(language).no_run_to_recover;
2372 task.last_error = Some(why.to_owned());
2373 task.notice_cause("missing-run", None, None);
2376 task.hold_machine(Some(why.to_owned()));
2377 }
2378 }
2379}
2380
2381fn reclaim_orphaned_running(
2403 queue: &Queue,
2404 max_attempts: usize,
2405 live_workers: &std::collections::BTreeSet<String>,
2406) -> Vec<String> {
2407 let mut reclaimed = Vec::new();
2408 for listed in queue.list() {
2409 if listed.status != TaskStatus::Running || live_workers.contains(&listed.id) {
2410 continue;
2411 }
2412 let Ok(_claim) = queue.claim(&listed.id) else {
2413 continue;
2414 };
2415 let Ok(mut task) = queue.get(&listed.id) else {
2419 continue;
2420 };
2421 if task.status != TaskStatus::Running {
2422 continue;
2423 }
2424 let last_run = task
2425 .execution_runs()
2426 .last()
2427 .and_then(|id| RunState::load(id).ok());
2428 if let Some(state) = &last_run
2438 && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2439 {
2440 tracing::warn!("abandon questions for {}: {e:#}", state.id);
2441 }
2442 let language = if last_run.is_none() {
2443 language_of(&task, Path::new("."))
2444 } else {
2445 String::new()
2446 };
2447 reclaim(&mut task, last_run, max_attempts, &language);
2448 if task.status == TaskStatus::Done {
2449 supersede_prior_runs(&task, &crate::run::home());
2450 }
2451 record(queue, &mut task);
2452 reclaimed.push(task.id.clone());
2453 }
2454 reclaimed
2455}
2456
2457fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2489 reclaim_abandoned_runs_with(
2490 home,
2491 now,
2492 crate::proc::pid_status,
2493 crate::proc::process_started_at,
2494 )
2495}
2496
2497fn reclaim_abandoned_runs_with<F, G>(
2503 home: &Path,
2504 now: Timestamp,
2505 query: F,
2506 identity: G,
2507) -> Vec<String>
2508where
2509 F: Fn(u32) -> Option<bool>,
2510 G: Fn(u32) -> Option<String>,
2511{
2512 let mut abandoned = Vec::new();
2513 for entry in std::fs::read_dir(home.join("runs"))
2514 .into_iter()
2515 .flatten()
2516 .flatten()
2517 {
2518 let id = entry.file_name().to_string_lossy().into_owned();
2519 if !crate::run::is_run_id(&id) {
2520 continue;
2521 }
2522 let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2525 continue;
2526 };
2527 let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2535 continue;
2536 };
2537 let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2538 continue;
2539 };
2540 if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2541 continue;
2542 }
2543 let daemon_claims = is_working_on(home, &id, now);
2555 if state.liveness_under_with(home, daemon_claims, &query, &identity)
2556 != crate::run::Liveness::Dead
2557 {
2558 continue;
2559 }
2560 state.abandon("daemon");
2561 if let Err(e) = state.save_under(home) {
2562 tracing::warn!("could not persist abandoned run {id}: {e:#}");
2563 continue;
2564 }
2565 if let Some(notice) = notices::run_ended(&state) {
2568 notices::raise_in(home, notice);
2569 }
2570 if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2578 tracing::warn!("abandon questions for {id}: {e:#}");
2579 }
2580 abandoned.push(id);
2581 }
2582 abandoned
2583}
2584
2585#[derive(Debug, Clone, Serialize, Deserialize)]
2586struct TaskWorker {
2587 opts: Opts,
2588 queue: PathBuf,
2589 task: String,
2590 #[serde(default)]
2591 lane: PermitKind,
2592 #[serde(default)]
2593 standalone: bool,
2594}
2595
2596fn task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2597 Ok(crate::worker::active(home)?
2598 .into_iter()
2599 .filter(|job| job.kind == "task")
2600 .collect())
2601}
2602
2603fn owned_task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2604 task_jobs(home)?
2605 .into_iter()
2606 .filter_map(
2607 |job| match serde_json::from_value::<TaskWorker>(job.payload.clone()) {
2608 Ok(request) if !request.standalone => Some(Ok(job)),
2609 Ok(_) => None,
2610 Err(error) => Some(Err(error.into())),
2611 },
2612 )
2613 .collect()
2614}
2615
2616#[must_use]
2618pub fn managed(home: &Path) -> bool {
2619 match crate::worker::active(home) {
2620 Err(error) => {
2621 tracing::error!("cannot determine scheduler ownership: {error:#}");
2622 true
2623 }
2624 Ok(jobs) if jobs.iter().any(|j| j.kind == "scheduler") => true,
2625 Ok(_) => {
2626 read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2627 && crate::worker::try_lease(home, "scheduler").map_or(true, |lease| lease.is_none())
2628 }
2629 }
2630}
2631
2632pub async fn spawn_detached(home: &Path, opts: &Opts) -> Result<crate::worker::Job> {
2634 anyhow::ensure!(
2635 crate::worker::control(home, "scheduler")?.is_none() || !managed(home),
2636 "the scheduler is stopping; wait for retirement before starting it again"
2637 );
2638 crate::worker::spawn(
2639 home,
2640 "scheduler",
2641 "scheduler",
2642 serde_json::to_value(opts.absolute()?)?,
2643 )
2644 .await
2645}
2646
2647fn park_request_path(home: &Path, job: &crate::worker::Job) -> PathBuf {
2648 home.join("worker-parks").join(format!("{}.json", job.id))
2649}
2650
2651fn request_task_park(
2652 home: &Path,
2653 job: &crate::worker::Job,
2654 cause: crate::run::ParkCause,
2655) -> Result<()> {
2656 let path = park_request_path(home, job);
2657 std::fs::create_dir_all(path.parent().context("worker park directory")?)?;
2658 std::fs::write(path, serde_json::to_vec(&cause)?)?;
2659 crate::worker::request(home, &job.key, crate::worker::Control::Park)
2660}
2661
2662pub fn request_control(home: &Path, control: crate::worker::Control) -> Result<()> {
2664 if control == crate::worker::Control::Park {
2665 for job in owned_task_jobs(home)? {
2666 request_task_park(home, &job, crate::run::ParkCause::Operator)?;
2667 }
2668 }
2669 crate::worker::request(home, "scheduler", control)
2670}
2671
2672pub(crate) fn scheduler_restart_options(home: &Path) -> Result<Option<Opts>> {
2674 if let Some(job) = crate::worker::active(home)?
2675 .into_iter()
2676 .find(|job| job.kind == "scheduler")
2677 {
2678 return serde_json::from_value(job.payload)
2679 .context("read detached scheduler options")
2680 .map(Some);
2681 }
2682 if read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2683 && crate::worker::try_lease(home, "scheduler")?.is_none()
2684 {
2685 let path = home.join("scheduler-options.json");
2686 let body = std::fs::read(&path).with_context(|| format!("read {}", path.display()))?;
2687 return serde_json::from_slice(&body)
2688 .context("decode detached scheduler options")
2689 .map(Some);
2690 }
2691 Ok(None)
2692}
2693
2694pub async fn restart_detached(home: &Path) -> Result<()> {
2696 let Some(opts) = scheduler_restart_options(home)? else {
2697 return Ok(());
2698 };
2699 request_control(home, crate::worker::Control::Stop)?;
2700 loop {
2701 let reserved = crate::worker::active(home)?
2702 .iter()
2703 .any(|job| job.kind == "scheduler");
2704 if !reserved && crate::worker::try_lease(home, "scheduler")?.is_some() {
2705 break;
2706 }
2707 tokio::time::sleep(Duration::from_millis(100)).await;
2708 }
2709 spawn_detached(home, &opts).await?;
2710 Ok(())
2711}
2712
2713pub async fn run_scheduler_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2715 let opts: Opts = serde_json::from_value(payload)?;
2716 let _ = home;
2717 serve_until(opts, Stop::new()).await
2718}
2719
2720pub async fn run_task_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2722 let request: TaskWorker = serde_json::from_value(payload)?;
2723 let queue = Queue::at(request.queue);
2724 let key = format!("task:{}", request.task);
2725 let job = task_jobs(home)?
2726 .into_iter()
2727 .find(|job| job.key == key)
2728 .context("task worker reservation is missing")?;
2729 let park_path = park_request_path(home, &job);
2730 let _claim = loop {
2733 match queue.claim(&request.task) {
2734 Ok(claim) => break claim,
2735 Err(e) if e.chain().any(|c| c.is::<std::io::Error>()) => {
2738 return Err(e.context("claim the task for its worker"));
2739 }
2740 Err(_) => {
2741 sweep_stale_claims(&queue, STALE_CLAIM);
2742 tokio::time::sleep(Duration::from_millis(50)).await;
2743 }
2744 }
2745 };
2746 let mut task = queue.get(&request.task)?;
2747 if !task.status.runnable()
2748 || (!request.standalone
2749 && request.lane
2750 != permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent))
2751 {
2752 return Ok(());
2753 }
2754 let stop = Stop::new();
2755 let watcher = {
2756 let home = home.to_path_buf();
2757 let stop = stop.clone();
2758 let park_path = park_path.clone();
2759 tokio::spawn(async move {
2760 loop {
2761 if crate::worker::control(&home, &key).ok().flatten().is_some() {
2762 let cause = std::fs::read(&park_path)
2763 .ok()
2764 .and_then(|body| serde_json::from_slice(&body).ok())
2765 .unwrap_or(crate::run::ParkCause::Operator);
2766 stop.park(cause);
2767 return;
2768 }
2769 tokio::time::sleep(Duration::from_millis(200)).await;
2770 }
2771 })
2772 };
2773 let quota = if request.standalone {
2774 run_claimed_until(&request.opts, &queue, &mut task, &stop).await
2775 } else {
2776 let status = Arc::new(Mutex::new(Status::new()));
2777 Box::pin(attempt(
2778 &request.opts,
2779 &queue,
2780 &status,
2781 &stop,
2782 crate::graph::Pause::new(),
2783 &mut task,
2784 ))
2785 .await
2786 };
2787 watcher.abort();
2788 let _ = std::fs::remove_file(park_path);
2789 persist_cooldown(home, "a).await?;
2790 Ok(())
2791}
2792
2793pub async fn spawn_claimed(
2796 home: &Path,
2797 opts: &Opts,
2798 queue: &Queue,
2799 task: &Task,
2800 claim: crate::queue::Claim,
2801) -> Result<crate::worker::Job> {
2802 let request = TaskWorker {
2803 opts: opts.absolute()?,
2804 queue: std::path::absolute(queue.root())?,
2805 task: task.id.clone(),
2806 lane: permit_kind(land_resume_state(task) == LandResume::Ready, task.urgent),
2807 standalone: true,
2808 };
2809 let job = crate::worker::spawn(
2810 home,
2811 "task",
2812 &format!("task:{}", task.id),
2813 serde_json::to_value(request)?,
2814 )
2815 .await?;
2816 drop(claim);
2817 Ok(job)
2818}
2819
2820pub async fn run_detached_claimed(
2823 opts: &Opts,
2824 queue: &Queue,
2825 task: &mut Task,
2826 claim: crate::queue::Claim,
2827) -> Result<()> {
2828 let home = crate::run::home();
2829 let job = spawn_claimed(&home, opts, queue, task, claim).await?;
2830 loop {
2831 crate::worker::active(&home)?;
2834 let current = crate::worker::get(&home, &job.id)?;
2835 if matches!(
2836 current.status,
2837 crate::worker::Status::Finished | crate::worker::Status::Failed
2838 ) {
2839 *task = queue.get(&task.id)?;
2840 anyhow::ensure!(
2841 current.status != crate::worker::Status::Failed,
2842 "task worker failed: {}",
2843 current.result.as_deref().unwrap_or("unknown failure")
2844 );
2845 return Ok(());
2846 }
2847 tokio::time::sleep(Duration::from_millis(200)).await;
2848 }
2849}
2850
2851async fn persist_cooldown(home: &Path, quota: &[QuotaLoss]) -> Result<()> {
2852 if let Some(until) = cooldown_until(quota, Timestamp::now()) {
2853 let _lease = loop {
2854 if let Some(lease) = crate::worker::try_lease(home, "task-quota-cooldown")? {
2855 break lease;
2856 }
2857 tokio::time::sleep(Duration::from_millis(10)).await;
2858 };
2859 if read_cooldown(home)?.is_none_or(|previous| previous < until) {
2860 let path = home.join("task-quota-cooldown.json");
2861 let temporary = path.with_extension("json.tmp");
2862 std::fs::write(&temporary, serde_json::to_vec(&until)?)?;
2863 std::fs::rename(temporary, path)?;
2864 }
2865 }
2866 Ok(())
2867}
2868
2869fn read_cooldown(home: &Path) -> Result<Option<Timestamp>> {
2870 match std::fs::read(home.join("task-quota-cooldown.json")) {
2871 Ok(body) => Ok(Some(serde_json::from_slice(&body)?)),
2872 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
2873 Err(error) => Err(error.into()),
2874 }
2875}
2876
2877pub async fn serve(opts: Opts) -> Result<()> {
2883 tracing::info!(
2884 "automatic update and restart requires magi web; standalone serve does not restart"
2885 );
2886 serve_until(opts, Stop::new()).await
2887}
2888
2889pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
2900 let opts = opts.absolute()?;
2901 let home = crate::run::home();
2902 let _scheduler = crate::worker::try_lease(&home, "scheduler")?
2903 .context("another scheduler already owns this home")?;
2904 if let Some(reading) = read_status(&home)
2905 && legacy_scheduler_running(&reading, Timestamp::now(), std::process::id())
2906 {
2907 bail!("a legacy scheduler is still running; stop it before starting independent dispatch");
2908 }
2909 if !crate::worker::active(&home)?
2910 .iter()
2911 .any(|job| job.kind == "scheduler")
2912 {
2913 crate::worker::clear_control(&home, "scheduler")?;
2914 }
2915 std::fs::write(
2916 home.join("scheduler-options.json"),
2917 serde_json::to_vec(&opts)?,
2918 )?;
2919 let control = {
2920 let home = home.clone();
2921 let stop = stop.clone();
2922 tokio::spawn(async move {
2923 loop {
2924 match crate::worker::control(&home, "scheduler").ok().flatten() {
2925 Some(crate::worker::Control::Park) => {
2926 let _ = request_control(&home, crate::worker::Control::Park);
2927 stop.park(crate::run::ParkCause::Operator);
2928 break;
2929 }
2930 Some(crate::worker::Control::Stop) => {
2931 stop.stop();
2932 break;
2933 }
2934 None => {}
2935 }
2936 tokio::time::sleep(Duration::from_millis(100)).await;
2937 }
2938 })
2939 };
2940 let signal = {
2941 let stop = stop.clone();
2942 tokio::spawn(async move {
2943 if tokio::signal::ctrl_c().await.is_ok() {
2944 stop.stop();
2945 tracing::info!("scheduler shutdown requested; independent workers continue");
2946 }
2947 })
2948 };
2949
2950 let worktrees_root = opts
2951 .worktrees_root
2952 .clone()
2953 .unwrap_or_else(crate::run::default_worktree_root);
2954 let outcome = drive(
2955 &opts,
2956 &Queue::open(),
2957 &status_path(),
2958 &crate::run::home(),
2959 &worktrees_root,
2960 &stop,
2961 )
2962 .await;
2963
2964 signal.abort();
2965 control.abort();
2966 outcome
2967}
2968
2969async fn drive(
2982 opts: &Opts,
2983 queue: &Queue,
2984 status_file: &Path,
2985 home: &Path,
2986 worktrees_root: &Path,
2987 stop: &Stop,
2988) -> Result<()> {
2989 let recovery_cfg = prepare(&opts.repo, opts).ok();
2997 let daemon_cfg = recovery_cfg
2998 .as_ref()
2999 .map(|c| c.daemon.clone())
3000 .unwrap_or_default();
3001 let reconciled = crate::driver::reconcile(home);
3002 if !reconciled.is_empty() {
3003 tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
3004 }
3005 let mut initial_status = Status::new();
3006 let owned = owned_task_jobs(home)?;
3007 initial_status.current = current_work(home, Timestamp::now())
3008 .into_iter()
3009 .filter(|current| {
3010 owned
3011 .iter()
3012 .any(|job| job.key.strip_prefix("task:") == Some(current.task.as_str()))
3013 })
3014 .collect();
3015 initial_status.idle = initial_status.current.is_empty();
3016 initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
3017 recovery_cfg.as_ref(),
3018 daemon_cfg.max_deputies,
3019 ));
3020 let status = Arc::new(Mutex::new(initial_status));
3021 write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
3022 let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
3023
3024 let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
3030
3031 tracing::info!(
3032 "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
3033 queue.root().display(),
3034 opts.poll.as_secs(),
3035 opts.max_attempts,
3036 concurrency,
3037 if daemon_cfg.pause_for_interrupts {
3038 ", interrupts enabled"
3039 } else {
3040 ""
3041 }
3042 );
3043
3044 let outcome = tokio::select! {
3045 outcome = poll(opts, queue, &status, home, worktrees_root, stop, DispatchLimits {
3046 max_concurrent: concurrency,
3047 pause_for_interrupts: daemon_cfg.pause_for_interrupts,
3048 recovery_cfg,
3049 }) => outcome,
3050 () = async {
3051 while !stop.stopped() {
3052 tokio::time::sleep(Duration::from_millis(25)).await;
3053 }
3054 } => {
3055 if stop.parking() {
3056 request_control(home, crate::worker::Control::Park)?;
3057 }
3058 Ok(())
3059 }
3060 };
3061
3062 stop.busy.store(0, Ordering::SeqCst);
3063 beat.abort();
3064 clear_status_at(status_file);
3065 outcome
3066}
3067
3068pub(crate) fn release_watch_settings_from_config(
3071 home: &Path,
3072 repo: &Path,
3073 cfg: &Config,
3074) -> (Vec<PathBuf>, u64) {
3075 let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
3076 .into_iter()
3077 .map(|r| r.path)
3078 .collect();
3079 let mut known: Vec<PathBuf> = Queue::at(home.join("queue"))
3082 .list()
3083 .into_iter()
3084 .map(|t| t.repo)
3085 .collect();
3086 let runs = home.join("runs");
3087 for id in crate::run::list_ids_in(&runs) {
3088 let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
3089 .ok()
3090 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
3091 .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
3092 known.extend(repo);
3093 }
3094 for k in known {
3095 let k = k.canonicalize().unwrap_or(k);
3096 if k.join(".git").exists() && !paths.contains(&k) {
3097 paths.push(k);
3098 }
3099 }
3100 let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
3101 if !paths.contains(&own) {
3102 paths.push(own);
3103 }
3104 (paths, cfg.daemon.release_stall_minutes)
3105}
3106
3107const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
3109
3110async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
3116 loop {
3117 tokio::time::sleep(HEARTBEAT).await;
3118 let snapshot = {
3119 let mut guard = lock(&status);
3120 guard.updated_at = Timestamp::now();
3121 guard.clone()
3122 };
3123 if let Err(e) = write_status_to(&path, &snapshot) {
3124 tracing::warn!("could not refresh the daemon status file: {e:#}");
3127 }
3128 }
3129}
3130
3131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3134enum LandResume {
3135 NotLanding,
3138 StillWaiting,
3143 Ready,
3147}
3148
3149fn land_resume_state(task: &Task) -> LandResume {
3153 if task.sync_only.is_some() {
3154 return LandResume::NotLanding;
3155 }
3156 let Some(run_id) = task.execution_runs().last() else {
3157 return LandResume::NotLanding;
3158 };
3159 let Ok(state) = RunState::load(run_id) else {
3160 return LandResume::NotLanding;
3161 };
3162 if !state.parked {
3163 return LandResume::NotLanding;
3164 }
3165 if state.status == RunStatus::Landing
3166 && state.land_approval.as_ref().is_some_and(|binding| {
3167 ask::Questions::open()
3168 .get_for_effects(&binding.question)
3169 .is_ok_and(|q| {
3170 q.run == state.id
3171 && q.resolution()
3172 .as_deref()
3173 .is_some_and(crate::merge_decision::stops)
3174 })
3175 })
3176 {
3177 return LandResume::Ready;
3178 }
3179 if !implementers_match(task, &state) {
3180 return LandResume::NotLanding;
3181 }
3182 let node = if state.status == RunStatus::Landing {
3186 land::APPROVAL_NODE
3187 } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
3188 crate::github_text::ASK_NODE
3189 } else {
3190 return LandResume::NotLanding;
3191 };
3192 let store = ask::Questions::open();
3193 let waiting = store
3194 .list_for_effects()
3195 .into_iter()
3196 .filter(|q| &q.run == run_id && q.node == node)
3197 .max_by(|a, b| a.id.cmp(&b.id));
3198 let Some(mut q) = waiting else {
3199 return LandResume::Ready;
3200 };
3201 if !q.status.open() {
3202 if q.resolution().as_deref() == Some(land::REPAIR) {
3205 return if state.liveness(false) == Liveness::Live {
3206 LandResume::StillWaiting
3207 } else {
3208 LandResume::NotLanding
3209 };
3210 }
3211 return LandResume::Ready;
3212 }
3213 let timeout = Duration::from_secs(state.config.graph.answer_timeout);
3220 let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
3221 if !store.held_reply(&q.id) && elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
3222 q.abandon(format!(
3223 "no answer within {}s of asking",
3224 timeout.as_secs().max(1)
3225 ));
3226 if store.put(&mut q).is_ok() {
3229 return LandResume::Ready;
3230 }
3231 }
3232 LandResume::StillWaiting
3233}
3234
3235const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
3243
3244const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
3256
3257#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3270enum Interrupt {
3271 Idle,
3273 Parking {
3285 parked: Vec<String>,
3286 interrupt_task: String,
3287 },
3288 Running {
3296 parked: Vec<String>,
3297 interrupt_task: String,
3298 },
3299 Resuming { parked: Vec<String> },
3306}
3307
3308fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
3329 match state {
3330 Interrupt::Idle => {
3331 if in_flight.len() != 1 {
3343 return Interrupt::Idle;
3344 }
3345 match runnable.iter().find(|t| t.interrupt) {
3346 Some(t) => Interrupt::Parking {
3347 parked: in_flight.to_vec(),
3348 interrupt_task: t.id.clone(),
3349 },
3350 None => Interrupt::Idle,
3351 }
3352 }
3353 Interrupt::Parking {
3354 parked,
3355 interrupt_task,
3356 } => {
3357 if in_flight.iter().any(|id| parked.contains(id)) {
3358 Interrupt::Parking {
3360 parked,
3361 interrupt_task,
3362 }
3363 } else if in_flight.contains(&interrupt_task) {
3364 Interrupt::Running {
3365 parked,
3366 interrupt_task,
3367 }
3368 } else if runnable.iter().any(|t| t.id == interrupt_task) {
3369 Interrupt::Parking {
3373 parked,
3374 interrupt_task,
3375 }
3376 } else {
3377 Interrupt::Resuming { parked }
3382 }
3383 }
3384 Interrupt::Running {
3385 parked,
3386 interrupt_task,
3387 } => {
3388 if in_flight.contains(&interrupt_task) {
3389 Interrupt::Running {
3390 parked,
3391 interrupt_task,
3392 }
3393 } else {
3394 Interrupt::Resuming { parked }
3400 }
3401 }
3402 Interrupt::Resuming { parked } => {
3403 if in_flight.iter().any(|id| parked.contains(id)) {
3404 Interrupt::Idle
3410 } else if runnable.iter().any(|t| parked.contains(&t.id)) {
3411 Interrupt::Resuming { parked }
3412 } else {
3413 Interrupt::Idle
3416 }
3417 }
3418 }
3419}
3420
3421fn advance_interrupt_tick(
3427 enabled: bool,
3428 state: Interrupt,
3429 in_flight: &[String],
3430 runnable: &[Task],
3431) -> Interrupt {
3432 if !enabled {
3433 return Interrupt::Idle;
3434 }
3435 advance_interrupt(state, in_flight, runnable)
3436}
3437
3438fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
3443 match state {
3444 Interrupt::Idle => candidates,
3445 Interrupt::Parking {
3446 parked,
3447 interrupt_task,
3448 } => {
3449 if in_flight.iter().any(|id| parked.contains(id)) {
3450 Vec::new()
3451 } else {
3452 candidates
3453 .into_iter()
3454 .filter(|t| &t.id == interrupt_task)
3455 .collect()
3456 }
3457 }
3458 Interrupt::Running { .. } => Vec::new(),
3459 Interrupt::Resuming { parked } => candidates
3467 .into_iter()
3468 .find(|t| parked.contains(&t.id))
3469 .into_iter()
3470 .collect(),
3471 }
3472}
3473
3474struct DispatchLimits {
3478 max_concurrent: usize,
3481 pause_for_interrupts: bool,
3483 recovery_cfg: Option<Config>,
3484}
3485
3486#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3495enum PermitKind {
3496 None,
3501 Urgent,
3508 #[default]
3511 Ordinary,
3512}
3513
3514fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
3517 if priority {
3518 PermitKind::None
3519 } else if urgent {
3520 PermitKind::Urgent
3521 } else {
3522 PermitKind::Ordinary
3523 }
3524}
3525
3526fn available_slots(requests: &[TaskWorker], limit: usize) -> (usize, usize) {
3527 let (ordinary, urgent) = requests.iter().filter(|request| !request.standalone).fold(
3528 (0usize, 0usize),
3529 |(ordinary, urgent), request| match request.lane {
3530 PermitKind::Ordinary => (ordinary + 1, urgent),
3531 PermitKind::Urgent => (ordinary, urgent + 1),
3532 PermitKind::None => (ordinary, urgent),
3533 },
3534 );
3535 (
3536 limit.saturating_sub(ordinary),
3537 1usize.saturating_sub(urgent),
3538 )
3539}
3540
3541#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
3543enum SkipReason {
3544 ClaimUnavailable,
3545 RereadFailed,
3546 NoLongerRunnable,
3547 WaitingOnLanding,
3548 CoolingDown,
3549 OrdinaryCapacity,
3550 UrgentCapacity,
3551 InterruptGate,
3552}
3553
3554impl SkipReason {
3555 fn key(self) -> &'static str {
3556 match self {
3557 Self::ClaimUnavailable => "claim_unavailable",
3558 Self::RereadFailed => "reread_failed",
3559 Self::NoLongerRunnable => "no_longer_runnable",
3560 Self::WaitingOnLanding => "waiting_on_landing",
3561 Self::CoolingDown => "cooling_down",
3562 Self::OrdinaryCapacity => "ordinary_capacity",
3563 Self::UrgentCapacity => "urgent_capacity",
3564 Self::InterruptGate => "interrupt_gate",
3565 }
3566 }
3567
3568 fn describe(self) -> &'static str {
3569 match self {
3570 Self::ClaimUnavailable => "could not claim it (held elsewhere or claim failed)",
3571 Self::RereadFailed => "could not re-read it",
3572 Self::NoLongerRunnable => "no longer runnable",
3573 Self::WaitingOnLanding => "waiting on landing",
3574 Self::CoolingDown => "quota cooldown",
3575 Self::OrdinaryCapacity => "no free ordinary slot",
3576 Self::UrgentCapacity => "urgent slot busy",
3577 Self::InterruptGate => "withheld by the interrupt sequence",
3578 }
3579 }
3580}
3581
3582#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3584pub struct DispatchReasonCount {
3585 pub reason: String,
3587 pub count: usize,
3589}
3590
3591#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3593pub struct DispatchWait {
3594 pub runnable: usize,
3596 pub reasons: Vec<DispatchReasonCount>,
3598}
3599
3600type DispatchSkips = std::collections::BTreeSet<(String, SkipReason)>;
3601
3602fn aggregate_dispatch_wait(runnable: usize, skips: &DispatchSkips) -> Option<DispatchWait> {
3603 if runnable == 0 {
3604 return None;
3605 }
3606 let mut counts = std::collections::BTreeMap::new();
3607 for (_, reason) in skips {
3608 *counts.entry(*reason).or_insert(0usize) += 1;
3609 }
3610 let mut counts: Vec<_> = counts.into_iter().collect();
3611 counts.sort_by(|(a, n), (b, m)| m.cmp(n).then(a.cmp(b)));
3612 Some(DispatchWait {
3613 runnable,
3614 reasons: counts
3615 .into_iter()
3616 .map(|(reason, count)| DispatchReasonCount {
3617 reason: reason.key().to_owned(),
3618 count,
3619 })
3620 .collect(),
3621 })
3622}
3623
3624fn interrupt_skips(before: &[String], after: &[Task]) -> DispatchSkips {
3625 before
3626 .iter()
3627 .filter(|id| !after.iter().any(|task| &task.id == *id))
3628 .map(|id| (id.clone(), SkipReason::InterruptGate))
3629 .collect()
3630}
3631
3632fn changed_dispatch_skips(previous: &mut DispatchSkips, current: DispatchSkips) -> bool {
3633 if *previous == current {
3634 return false;
3635 }
3636 *previous = current;
3637 true
3638}
3639
3640struct DispatchClaim {
3641 task: Task,
3642 claim: crate::queue::Claim,
3643 permit: Option<tokio::sync::OwnedSemaphorePermit>,
3644}
3645
3646fn claim_dispatch(
3649 queue: &Queue,
3650 candidate: &Task,
3651 cooling_down: bool,
3652 ordinary: &Arc<tokio::sync::Semaphore>,
3653 urgent: &Arc<tokio::sync::Semaphore>,
3654) -> std::result::Result<DispatchClaim, SkipReason> {
3655 let claim = queue
3656 .claim(&candidate.id)
3657 .map_err(|_| SkipReason::ClaimUnavailable)?;
3658 let task = match queue.get(&candidate.id) {
3659 Ok(t) if t.status.runnable() => t,
3660 Ok(_) => return Err(SkipReason::NoLongerRunnable),
3661 Err(e) => {
3662 tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
3663 return Err(SkipReason::RereadFailed);
3664 }
3665 };
3666 let resume = land_resume_state(&task);
3667 if resume == LandResume::StillWaiting {
3668 return Err(SkipReason::WaitingOnLanding);
3669 }
3670 let priority = resume == LandResume::Ready;
3671 if !priority && cooling_down {
3672 return Err(SkipReason::CoolingDown);
3673 }
3674 let permit = match permit_kind(priority, task.urgent) {
3677 PermitKind::None => None,
3678 PermitKind::Urgent => Some(
3679 Arc::clone(urgent)
3680 .try_acquire_owned()
3681 .map_err(|_| SkipReason::UrgentCapacity)?,
3682 ),
3683 PermitKind::Ordinary => Some(
3684 Arc::clone(ordinary)
3685 .try_acquire_owned()
3686 .map_err(|_| SkipReason::OrdinaryCapacity)?,
3687 ),
3688 };
3689 let stamp = Timestamp::now();
3692 let mut task = task;
3693 task.dispatched_at = Some(stamp);
3694 if let Err(e) = queue.modify(&task.id, |t| {
3695 t.dispatched_at = Some(stamp);
3696 true
3697 }) {
3698 tracing::warn!("could not record dispatch order of {}: {e:#}", task.short());
3699 }
3700 Ok(DispatchClaim {
3701 task,
3702 claim,
3703 permit,
3704 })
3705}
3706
3707#[derive(Serialize, Deserialize)]
3726struct ServiceWorker {
3727 opts: Opts,
3728 queue: PathBuf,
3729 worktrees_root: PathBuf,
3730 operation: String,
3731}
3732
3733fn load_conductor(home: &Path) -> Result<Conductor> {
3734 match std::fs::read(home.join("conductor-state.json")) {
3735 Ok(body) => serde_json::from_slice(&body).context("read conductor state"),
3736 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Conductor::new()),
3737 Err(error) => Err(error.into()),
3738 }
3739}
3740
3741fn conductor_work(queue: &Queue, home: &Path) -> (Vec<Task>, Vec<Task>, Vec<Task>) {
3742 let live: std::collections::BTreeSet<_> = current_work(home, Timestamp::now())
3743 .into_iter()
3744 .map(|c| c.task)
3745 .collect();
3746 let stalled = stalled_tasks(queue, home, Timestamp::now());
3747 let stalled_ids: std::collections::BTreeSet<_> = stalled.iter().map(|t| t.id.clone()).collect();
3748 let finished = finished_tasks(queue)
3749 .into_iter()
3750 .filter(|t| !live.contains(&t.id) && !stalled_ids.contains(&t.id))
3751 .filter(|t| !awaiting_resume_with(t, |id| RunState::load_under(id, home)))
3752 .collect();
3753 let queued = queued_tasks(queue)
3754 .into_iter()
3755 .filter(|t| !live.contains(&t.id))
3756 .collect();
3757 (queued, stalled, finished)
3758}
3759
3760fn retention_service_receipt(
3763 home: &Path,
3764 operation: &str,
3765 phase: &str,
3766 outcome: &str,
3767 detail: &str,
3768 cfg: Option<&Config>,
3769) {
3770 if !matches!(operation, "housekeeping" | "disk-pressure") {
3771 return;
3772 }
3773 let receipt = serde_json::json!({"checked_at": Timestamp::now(),
3774 "version": env!("CARGO_PKG_VERSION"), "pid": std::process::id(),
3775 "operation": operation, "outcome": outcome, "detail": detail,
3776 "auto_fold": cfg.map(|c| c.disk.auto_fold),
3777 "reclaim_bytes": cfg.map(|c| c.disk.worktree_reclaim_bytes)});
3778 if let Err(error) = crate::fold_evidence::atomic_write(
3779 &home.join(format!("source-eviction-{operation}-{phase}.json")),
3780 &serde_json::to_vec(&receipt).expect("service receipt"),
3781 ) {
3782 tracing::warn!("retention service receipt failed: {error:#}");
3783 }
3784}
3785
3786async fn start_service(
3787 home: &Path,
3788 opts: &Opts,
3789 queue: &Queue,
3790 worktrees_root: &Path,
3791 operation: &str,
3792 cfg: Option<&Config>,
3793 busy: bool,
3794) -> Result<()> {
3795 let fetch_cfg = if operation == "fetch" {
3798 match prepare(&opts.repo, opts) {
3799 Ok(cfg) => Some(cfg),
3800 Err(error) => {
3801 tracing::warn!("could not reload periodic fetch configuration: {error:#}");
3802 return Ok(());
3803 }
3804 }
3805 } else {
3806 None
3807 };
3808 let cfg = fetch_cfg.as_ref().or(cfg);
3809 let ticks = home.join("service-ticks");
3810 std::fs::create_dir_all(&ticks)?;
3811 let receipt = ticks.join(format!("daemon-{operation}"));
3812 let last = std::fs::read(&receipt)
3813 .ok()
3814 .and_then(|body| serde_json::from_slice::<Timestamp>(&body).ok());
3815 let interval = match operation {
3816 "disk-pressure" => 30,
3817 "chat-goals" => 60,
3818 "cache" => CACHE_CHECK_INTERVAL_SECS,
3819 "fetch" => cfg.map_or(60, |cfg| cfg.repos.fetch_interval.max(1)),
3820 _ => opts.poll.as_secs().max(1),
3821 };
3822 let now = Timestamp::now();
3823 if !cache_check_due(last, now, interval) {
3824 retention_service_receipt(
3825 home,
3826 operation,
3827 "dispatch",
3828 "skipped",
3829 "cadence not due",
3830 cfg,
3831 );
3832 return Ok(());
3833 }
3834 let key = format!("service:daemon-{operation}");
3835 if crate::worker::active(home)?
3836 .iter()
3837 .any(|job| job.key == key)
3838 {
3839 retention_service_receipt(
3840 home,
3841 operation,
3842 "dispatch",
3843 "skipped",
3844 "service worker already active",
3845 cfg,
3846 );
3847 return Ok(());
3848 }
3849 let eligible = match operation {
3850 "conductor" => {
3851 let (queued, stalled, finished) = conductor_work(queue, home);
3852 !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3853 && load_conductor(home)?.worth_a_look(queue, &stalled, &finished)
3854 }
3855 "maintenance" => {
3856 queue.list().iter().any(|task| {
3857 crate::triage::disk_wait_eligible(task)
3858 && task
3859 .disk_checked_at
3860 .is_none_or(|at| now.as_second() - at.as_second() >= 60)
3861 }) || Questions::at(home.join("questions"))
3862 .list_for_effects()
3863 .iter()
3864 .any(|q| {
3865 q.chosen_action().is_some_and(|action| action.maintenance())
3866 && !home
3867 .join("choice-actions")
3868 .join(format!("{}.json", q.id))
3869 .exists()
3870 })
3871 }
3872 "housekeeping" => !busy && runnable(queue).is_empty(),
3873 "cache" => {
3874 !busy
3875 && !runnable(queue).is_empty()
3876 && cfg.is_some_and(|cfg| cfg.disk.cache_limit_bytes > 0)
3877 }
3878 "disk-pressure" => busy,
3879 "fetch" => {
3880 cfg.is_some_and(|cfg| cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty())
3881 }
3882 "chat-goals" => crate::talk::Talks::at(home.join("talks"))
3883 .list()
3884 .iter()
3885 .any(|talk| {
3886 talk.status.open()
3887 && talk.pending.is_empty()
3888 && talk.pending_attachments.is_empty()
3889 && talk.goals.iter().any(|goal| goal.active())
3890 }),
3891 _ => false,
3892 };
3893 if !eligible {
3894 retention_service_receipt(
3895 home,
3896 operation,
3897 "dispatch",
3898 "skipped",
3899 if operation == "housekeeping" {
3900 "active work or runnable task queue"
3901 } else {
3902 "no active work; idle housekeeping owns scan"
3903 },
3904 cfg,
3905 );
3906 return Ok(());
3907 }
3908 retention_service_receipt(
3909 home,
3910 operation,
3911 "dispatch",
3912 "launching",
3913 "eligible and cadence due",
3914 cfg,
3915 );
3916 let request = ServiceWorker {
3917 opts: opts.absolute()?,
3918 queue: std::path::absolute(queue.root())?,
3919 worktrees_root: std::path::absolute(worktrees_root)?,
3920 operation: operation.to_owned(),
3921 };
3922 if let Err(error) =
3923 crate::worker::spawn(home, "daemon-service", &key, serde_json::to_value(request)?).await
3924 {
3925 retention_service_receipt(
3926 home,
3927 operation,
3928 "dispatch",
3929 "error",
3930 &format!("worker launch: {error:#}"),
3931 cfg,
3932 );
3933 tracing::warn!(operation, "could not launch daemon service: {error:#}");
3934 }
3935 std::fs::write(receipt, serde_json::to_vec(&now)?)?;
3936 Ok(())
3937}
3938
3939pub async fn run_service_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
3942 let request: ServiceWorker = serde_json::from_value(payload)?;
3943 let opts = &request.opts;
3944 let queue = Queue::at(request.queue);
3945 let questions = Questions::at(home.join("questions"));
3946 match request.operation.as_str() {
3947 "chat-goals" => {
3948 let talks = crate::talk::Talks::at(home.join("talks"));
3949 crate::chat_goal_runtime::sweep(&talks, false).await;
3950 }
3951 "maintenance" => {
3952 apply_maintenance_choices(&queue, &questions, home).await;
3953 triage::monitor_disk_waits(
3954 &queue,
3955 &questions,
3956 opts.config.as_deref(),
3957 Timestamp::now(),
3958 );
3959 }
3960 "conductor" => {
3961 let path = home.join("conductor-state.json");
3962 let mut conductor = load_conductor(home)?;
3963 let (queued, stalled, finished) = conductor_work(&queue, home);
3964 if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3965 && conductor.worth_a_look(&queue, &stalled, &finished)
3966 {
3967 let cfg = prepare(&opts.repo, opts)?;
3968 conductor
3969 .maybe_run(
3970 &cfg,
3971 &opts.repo,
3972 &queue,
3973 &questions,
3974 home,
3975 &queued,
3976 &stalled,
3977 &finished,
3978 opts.max_attempts,
3979 )
3980 .await;
3981 let temporary = path.with_extension("json.tmp");
3982 std::fs::write(&temporary, serde_json::to_vec(&conductor)?)?;
3983 std::fs::rename(temporary, path)?;
3984 }
3985 }
3986 "fetch" => {
3987 let cfg = prepare(&opts.repo, opts)?;
3988 if cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty() {
3989 let outcome = clean::fetch_origins(&cfg.repos.roots, FETCH_TIMEOUT, || false).await;
3990 tracing::debug!("fetch origins: {outcome:?}");
3991 }
3992 }
3993 "cache" => {
3994 if task_jobs(home)?.is_empty() {
3995 let mut checked = None;
3996 maybe_prune_cache_between_runs(
3997 &opts.repo,
3998 opts,
3999 home,
4000 &Stop::new(),
4001 &mut checked,
4002 Timestamp::now(),
4003 )
4004 .await;
4005 }
4006 }
4007 "disk-pressure" => {
4008 if let Ok(cfg) = prepare(&opts.repo, opts) {
4009 retention_service_receipt(
4010 home,
4011 "disk-pressure",
4012 "worker",
4013 "running",
4014 "retention sweep",
4015 Some(&cfg),
4016 );
4017 crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
4018 if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
4019 tracing::warn!("disk pressure cache cleanup failed: {e:#}");
4020 }
4021 if let Err(e) = crate::build_target::prune_registered(home, &cfg.disk) {
4022 tracing::warn!("disk pressure isolated build cleanup failed: {e:#}");
4023 }
4024 for current in current_work(home, Timestamp::now()) {
4025 if let Ok(state) = RunState::load_under(¤t.run, home)
4026 && let Some(reason) = disk_gate(&state.repo, &state.config)
4027 {
4028 for job in owned_task_jobs(home)?.into_iter().filter(|job| {
4029 job.key.strip_prefix("task:") == Some(current.task.as_str())
4030 }) {
4031 request_task_park(
4032 home,
4033 &job,
4034 crate::run::ParkCause::Interrupt {
4035 reason: reason.clone(),
4036 },
4037 )?;
4038 }
4039 notices::raise_in(
4040 home,
4041 Notice::warn(
4042 "disk:pressure",
4043 "Disk pressure persists after cleanup; active workers were asked to checkpoint and park. New starts and resumes wait for free space.",
4044 ),
4045 );
4046 }
4047 }
4048 } else {
4049 retention_service_receipt(
4050 home,
4051 "disk-pressure",
4052 "worker",
4053 "error",
4054 "configuration could not be loaded",
4055 None,
4056 );
4057 }
4058 }
4059 "housekeeping" => {
4060 if task_jobs(home)?.is_empty() {
4061 match prepare(&opts.repo, opts) {
4062 Ok(cfg) => {
4063 retention_service_receipt(
4064 home,
4065 "housekeeping",
4066 "worker",
4067 "running",
4068 "retention sweep",
4069 Some(&cfg),
4070 );
4071 crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
4072 }
4073 Err(error) => retention_service_receipt(
4074 home,
4075 "housekeeping",
4076 "worker",
4077 "error",
4078 &format!("configuration: {error:#}"),
4079 None,
4080 ),
4081 }
4082 janitor(&opts.repo, opts, home, &request.worktrees_root).await;
4083 resweep_superseded_attempts(&queue, home);
4084 triage_held(&queue, home, opts).await;
4085 } else {
4086 retention_service_receipt(
4087 home,
4088 "housekeeping",
4089 "worker",
4090 "skipped",
4091 "task worker became active",
4092 None,
4093 );
4094 }
4095 }
4096 operation => bail!("unknown daemon service {operation}"),
4097 }
4098 Ok(())
4099}
4100
4101fn task_worker_spawn_error(home: &Path, request: &TaskWorker, error: anyhow::Error) -> Result<()> {
4105 let key = format!("task:{}", request.task);
4106 let payload = serde_json::to_value(request)?;
4107 if crate::worker::active(home)?
4108 .iter()
4109 .any(|job| job.key == key && job.kind == "task" && job.payload != payload)
4110 {
4111 tracing::warn!(
4112 "task {} acquired a competing worker reservation: {error:#}",
4113 crate::run::short_of(&request.task)
4114 );
4115 return Ok(());
4116 }
4117 tracing::error!("task worker startup stopped dispatch: {error:#}");
4118 notices::raise_in(
4119 home,
4120 Notice::error(
4121 "loop:worker-startup",
4122 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),
4125 ).link(Link::Task { id: request.task.clone() }),
4126 );
4127 Err(error).with_context(|| {
4128 format!(
4129 "cannot start task {} worker; dispatcher stopped; any unacknowledged reservation remains occupied",
4130 crate::run::short_of(&request.task)
4131 )
4132 })
4133}
4134
4135async fn poll(
4136 opts: &Opts,
4137 queue: &Queue,
4138 status: &Arc<Mutex<Status>>,
4139 home: &Path,
4140 worktrees_root: &Path,
4141 stop: &Stop,
4142 limits: DispatchLimits,
4143) -> Result<()> {
4144 let mut attempted = Vec::new();
4145 let mut settling_once_services = false;
4146 let interrupt_path = home.join("scheduler-interrupt.json");
4147 let mut interrupt = match std::fs::read(&interrupt_path) {
4148 Ok(body) => serde_json::from_slice(&body).context("read scheduler interrupt state")?,
4149 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Interrupt::Idle,
4150 Err(error) => return Err(error.into()),
4151 };
4152 let mut previous = std::collections::BTreeSet::<String>::new();
4153 let mut previous_skips = DispatchSkips::new();
4154 while !stop.stopped() {
4155 let jobs: Vec<_> = crate::worker::active(home)?
4156 .into_iter()
4157 .filter(|job| job.kind == "task")
4158 .collect();
4159 let requests: Vec<_> = jobs
4160 .iter()
4161 .map(|job| {
4162 serde_json::from_value::<TaskWorker>(job.payload.clone())
4163 .with_context(|| format!("read live task worker {}", job.id))
4164 })
4165 .collect::<Result<_>>()?;
4166 let live: std::collections::BTreeSet<_> = requests.iter().map(|r| r.task.clone()).collect();
4167 let owned: std::collections::BTreeSet<_> = requests
4168 .iter()
4169 .filter(|r| !r.standalone)
4170 .map(|r| r.task.clone())
4171 .collect();
4172 let current: Vec<_> = requests
4173 .iter()
4174 .zip(&jobs)
4175 .filter(|(request, _)| !request.standalone)
4176 .map(|(request, job)| Current {
4177 worker: Some(job.id.clone()),
4178 task: request.task.clone(),
4179 run: queue
4180 .get(&request.task)
4181 .ok()
4182 .and_then(|task| task.execution_runs().last().cloned())
4183 .unwrap_or_default(),
4184 })
4185 .collect();
4186 {
4187 let mut snapshot = lock(status);
4188 snapshot.polls += 1;
4189 snapshot.completed += previous.difference(&owned).count();
4190 snapshot.current = current;
4191 snapshot.idle = owned.is_empty();
4192 snapshot.dispatch_wait = None;
4193 }
4194 previous = owned.clone();
4195 stop.busy.store(owned.len(), Ordering::SeqCst);
4196
4197 let (ordinary, urgent) = available_slots(&requests, limits.max_concurrent);
4200 let sem = Arc::new(tokio::sync::Semaphore::new(ordinary));
4201 let urgent_sem = Arc::new(tokio::sync::Semaphore::new(urgent));
4202 let mut permits = Vec::new();
4203 sweep_stale_claims(queue, STALE_CLAIM);
4204 reclaim_orphaned_running(queue, opts.max_attempts, &live);
4205 reclaim_abandoned_runs(home, Timestamp::now());
4206 let questions = Questions::at(home.join("questions"));
4207
4208 crate::task_chat::sweep(
4211 queue,
4212 &crate::talk::Talks::at(home.join("talks")),
4213 &questions,
4214 home,
4215 );
4216 if let Err(error) = crate::task_inquiry::Outbox::at(home)
4217 .sweep(queue, &crate::talk::Talks::at(home.join("talks")))
4218 {
4219 tracing::warn!("task inquiry delivery remains pending: {error:#}");
4220 }
4221 repair_choice_offers(&questions);
4222 resolve_blockers(queue, &questions);
4223 apply_task_choice_actions(queue, &questions, home);
4224 triage::apply_answers(queue, &questions);
4225 reconcile_task_questions(queue, &questions);
4226 let talks = crate::talk::Talks::at(home.join("talks"));
4227 crate::chat_notify::sweep(queue, &talks, home);
4228 crate::notice_delivery::sweep(queue, &talks, home, &opts.repo);
4229 crate::chat_watch::sweep(home, &talks);
4230 if let Err(error) = crate::chat_control::reconcile_decisions(queue, home) {
4231 tracing::warn!("decision receipt reconciliation remains pending: {error:#}");
4232 }
4233 let mut turns = tokio::task::JoinSet::new();
4234 crate::chat_notify::start_turns(&talks, stop.parking(), &mut turns);
4235 while turns.join_next().await.is_some() {}
4237
4238 crate::consult::start_services(
4239 home,
4240 &opts.repo,
4241 limits.recovery_cfg.as_ref(),
4242 opts.config.as_deref(),
4243 )
4244 .await?;
4245 for operation in [
4246 "conductor",
4247 "maintenance",
4248 "housekeeping",
4249 "disk-pressure",
4250 "cache",
4251 "fetch",
4252 "chat-goals",
4253 ] {
4254 if settling_once_services {
4258 break;
4259 }
4260 if operation == "chat-goals" && stop.parking() {
4261 continue;
4262 }
4263 start_service(
4264 home,
4265 opts,
4266 queue,
4267 worktrees_root,
4268 operation,
4269 limits.recovery_cfg.as_ref(),
4270 !live.is_empty(),
4271 )
4272 .await?;
4273 }
4274 let latest = crate::worker::active(home)?;
4275 if latest.iter().any(|job| job.key == "service:daemon-cache")
4276 || latest
4277 .iter()
4278 .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4279 {
4280 stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4281 continue;
4282 }
4283 let candidates: Vec<Task> = runnable(queue)
4284 .into_iter()
4285 .filter(|task| !live.contains(&task.id))
4286 .filter(|task| !opts.once || !attempted.contains(&task.id))
4287 .collect();
4288 let in_flight: Vec<_> = owned.iter().cloned().collect();
4289 let prior_interrupt = std::mem::discriminant(&interrupt);
4290 interrupt = advance_interrupt_tick(
4291 limits.pause_for_interrupts,
4292 interrupt,
4293 &in_flight,
4294 &candidates,
4295 );
4296 if prior_interrupt != std::mem::discriminant(&interrupt) {
4299 let temporary = interrupt_path.with_extension("json.tmp");
4300 std::fs::write(&temporary, serde_json::to_vec(&interrupt)?)?;
4301 std::fs::rename(temporary, &interrupt_path)?;
4302 }
4303 if let Interrupt::Parking {
4304 parked,
4305 interrupt_task,
4306 } = &interrupt
4307 {
4308 for job in jobs.iter().filter(|job| {
4309 parked
4310 .iter()
4311 .any(|id| job.key.strip_prefix("task:") == Some(id.as_str()))
4312 }) {
4313 if crate::worker::control(home, &job.key)?.is_none() {
4314 request_task_park(
4315 home,
4316 job,
4317 crate::run::ParkCause::Interrupt {
4318 reason: format!(
4319 "task {} asked to run first",
4320 crate::run::short_of(interrupt_task)
4321 ),
4322 },
4323 )?;
4324 }
4325 }
4326 }
4327 let candidate_ids: Vec<_> = candidates.iter().map(|task| task.id.clone()).collect();
4328 let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
4329 let mut skips = interrupt_skips(&candidate_ids, &candidates);
4330 let cooling = read_cooldown(home)?.is_some_and(|until| Timestamp::now() < until);
4331 let mut started = false;
4332 let mut resync = false;
4333 for candidate in candidates {
4334 if stop.stopped() {
4335 break;
4336 }
4337 let DispatchClaim {
4338 task,
4339 claim,
4340 permit,
4341 } = match claim_dispatch(queue, &candidate, cooling, &sem, &urgent_sem) {
4342 Ok(claim) => claim,
4343 Err(reason) => {
4344 skips.insert((candidate.id, reason));
4345 continue;
4346 }
4347 };
4348 if crate::worker::active(home)?
4349 .iter()
4350 .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4351 {
4352 drop(claim);
4353 resync = true;
4354 break;
4355 }
4356 let lane = permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent);
4357 let request = TaskWorker {
4358 opts: opts.absolute()?,
4359 queue: std::path::absolute(queue.root())?,
4360 task: task.id.clone(),
4361 lane,
4362 standalone: false,
4363 };
4364 if let Err(error) = crate::worker::spawn(
4367 home,
4368 "task",
4369 &format!("task:{}", task.id),
4370 serde_json::to_value(&request)?,
4371 )
4372 .await
4373 {
4374 task_worker_spawn_error(home, &request, error)?;
4375 drop(claim);
4376 resync = true;
4377 break;
4378 }
4379 drop(claim);
4380 permits.extend(permit);
4381 attempted.push(task.id);
4382 started = true;
4383 }
4384 if !resync && !stop.stopped() {
4385 if !started {
4386 lock(status).dispatch_wait = aggregate_dispatch_wait(candidate_ids.len(), &skips);
4387 }
4388 if changed_dispatch_skips(&mut previous_skips, skips) {
4389 if previous_skips.is_empty() {
4390 tracing::info!("dispatch skips cleared");
4391 }
4392 for (task, reason) in &previous_skips {
4393 tracing::info!(
4394 task,
4395 reason = reason.key(),
4396 "task {} skipped: {}",
4397 crate::run::short_of(task),
4398 reason.describe()
4399 );
4400 }
4401 }
4402 }
4403 if started || resync {
4404 continue;
4405 }
4406 if owned.is_empty() && opts.once {
4407 settling_once_services = true;
4408 if crate::worker::active(home)?.iter().any(|job| {
4412 job.kind == "daemon-service"
4413 && matches!(
4414 job.key.as_str(),
4415 "service:daemon-housekeeping"
4416 | "service:daemon-conductor"
4417 | "service:daemon-maintenance"
4418 )
4419 }) {
4420 stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4421 continue;
4422 }
4423 break;
4424 }
4425 stop.idle(if live.is_empty() {
4426 opts.poll
4427 } else {
4428 RECHECK_WHILE_BUSY.min(opts.poll)
4429 })
4430 .await;
4431 }
4432 stop.busy.store(0, Ordering::SeqCst);
4435 lock(status).dispatch_wait = None;
4436 Ok(())
4437}
4438
4439async fn resume_owner_lock(home: &Path, id: &str) -> Result<crate::pr_head::OwnerLock> {
4443 let busy = |error: &anyhow::Error| {
4444 error.downcast_ref::<std::io::Error>().is_some_and(|error| {
4445 error.kind() == std::io::ErrorKind::WouldBlock
4446 || cfg!(windows) && error.raw_os_error() == Some(33)
4447 })
4448 };
4449 match crate::pr_head::owner_lock(home, id) {
4450 Ok(lock) => return Ok(lock),
4451 Err(error) if busy(&error) => {}
4452 Err(error) => return Err(error),
4453 }
4454 let wait = RunState::load_under(id, home)?
4455 .config
4456 .graph
4457 .timeout_resource_wait;
4458 crate::pr_head::owner_lock_wait(home, id, Duration::from_secs(wait)).await
4459}
4460
4461async fn public_resume_owner(
4465 home: &Path,
4466 runs: &[String],
4467 repo: &Path,
4468) -> Result<Option<RunState>> {
4469 let mut owner = None;
4470 for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
4471 let _lock = resume_owner_lock(home, id).await?;
4472 let state = RunState::load_under(id, home)?;
4473 if state.released()
4474 || state.retired_to.is_some()
4475 || state.pr_taken_over_by.is_some()
4476 || !crate::handover::landing_checkpoint(&state)
4477 {
4478 continue;
4479 }
4480 anyhow::ensure!(
4481 crate::git::toplevel(&state.repo).await?.canonicalize()?
4482 == crate::git::toplevel(repo).await?.canonicalize()?,
4483 "public owner repository differs; inspect run lineage"
4484 );
4485 anyhow::ensure!(
4486 owner.is_none(),
4487 "multiple retained public owners; inspect run lineage"
4488 );
4489 if let Some(reason) = crate::handover::resume_refusal_under(&state, Some(home)) {
4490 anyhow::bail!(reason.diagnostic(&state));
4491 }
4492 let claimed = is_working_on_other(home, id, Timestamp::now())?;
4493 anyhow::ensure!(
4494 state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
4495 "public owner's driver is live or unknown; wait before retrying"
4496 );
4497 owner = Some(state);
4498 }
4499 Ok(owner)
4500}
4501
4502async fn attempt(
4508 opts: &Opts,
4509 queue: &Queue,
4510 status: &Arc<Mutex<Status>>,
4511 stop: &Stop,
4512 interrupt_pause: crate::graph::Pause,
4513 task: &mut Task,
4514) -> Vec<QuotaLoss> {
4515 if let Some(request) = task.sync_only.clone() {
4516 Box::pin(attempt_sync_only(
4517 queue,
4518 status,
4519 stop,
4520 interrupt_pause,
4521 task,
4522 request,
4523 ))
4524 .await;
4525 return Vec::new();
4526 }
4527 let repo = repo_for(task, &opts.repo);
4528 tracing::info!(
4529 "task {} — {} (repo {})",
4530 task.short(),
4531 task.title,
4532 repo.display()
4533 );
4534
4535 let public_owner = match public_resume_owner(&crate::run::home(), &task.runs, &repo).await {
4536 Ok(owner) => owner,
4537 Err(e) => {
4538 task.hold_machine(Some(format!(
4539 "Cannot verify existing public owner: {e:#}; no attempt started."
4540 )));
4541 record(queue, task);
4542 return Vec::new();
4543 }
4544 };
4545 let resume_runs = public_owner
4546 .as_ref()
4547 .map(|s| vec![s.id.clone()])
4548 .unwrap_or_else(|| task.execution_runs().to_vec());
4549
4550 if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
4554 && previous
4555 .merge_decision
4556 .as_ref()
4557 .is_some_and(|decision| !decision.closed)
4558 && previous.status != RunStatus::Landing
4559 && !crate::merge_decision::resumable_hold(&previous)
4560 {
4561 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)));
4562 record(queue, task);
4563 return Vec::new();
4564 }
4565 let stop_owner = resume_runs
4566 .last()
4567 .and_then(|id| RunState::load(id).ok())
4568 .filter(|state| {
4569 crate::merge_decision::resumable_hold(state)
4570 || state.status == RunStatus::Landing
4571 && state.land_approval.as_ref().is_some_and(|binding| {
4572 Questions::open()
4573 .get_for_effects(&binding.question)
4574 .is_ok_and(|q| {
4575 q.run == state.id
4576 && q.resolution()
4577 .as_deref()
4578 .is_some_and(crate::merge_decision::stops)
4579 })
4580 })
4581 });
4582 if let Some(owner) = stop_owner {
4583 let mut runner = match Runner::resume(&owner.id) {
4584 Ok(runner) => runner,
4585 Err(e) => {
4586 task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
4587 record(queue, task);
4588 return Vec::new();
4589 }
4590 };
4591 runner.on_pause(stop.pause());
4592 runner.watch_interrupt(interrupt_pause);
4593 let quota_before = runner.state.quota.clone();
4594 let before_start = task.clone();
4595 task.start(owner.id.clone());
4596 if let Err(error) = queue.put(task) {
4597 *task = before_start;
4598 let error = runner.fail_startup("task-start", error);
4599 if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
4600 task.record_startup_failure(failure.clone());
4601 }
4602 task.hold_manual(Some(format!(
4603 "Could not persist task start; no agents dispatched: {error:#}"
4604 )));
4605 record(queue, task);
4606 return Vec::new();
4607 }
4608 lock(status).current.push(Current {
4609 worker: None,
4610 task: task.id.clone(),
4611 run: owner.id,
4612 });
4613 runner.state.carry_dispatched_resumes(task);
4614 runner.state.next_pass_task_entry = true;
4615 let result = runner.execute().await;
4616 return finish_attempt(
4617 opts.max_attempts,
4618 queue,
4619 task,
4620 &runner.state,
4621 "a_before,
4622 result,
4623 );
4624 }
4625
4626 if let Some(owner) = &public_owner
4627 && (task.fresh_start || !may_resume_run(owner, task))
4628 {
4629 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)));
4630 record(queue, task);
4631 return Vec::new();
4632 }
4633
4634 if let Some(state) = task
4635 .execution_runs()
4636 .last()
4637 .and_then(|id| RunState::load(id).ok())
4638 && let Some(reason) = crate::repair_budget::conflict_failure(task, &state)
4639 {
4640 task.hold_machine(Some(reason));
4641 record(queue, task);
4642 return Vec::new();
4643 }
4644
4645 if let Some(held) = crate::base_sync_recovery::held_run(queue, task)
4646 && !task.fresh_start
4647 && task.pr_recovery.is_none()
4648 {
4649 let authorized = if crate::repair_budget::conflict_pending(task, &held) {
4652 true
4653 } else if task.resumption.is_some() && compatible_run_instruction(&held, task) {
4654 let home = queue.root().parent().expect("queue has a home");
4655 match Runner::authorize_base_recovery_from_resumption(home, &held.id, &task.id).await {
4656 Ok(()) => true,
4657 Err(error) => {
4658 tracing::debug!(run = %held.id, %error, "base recovery resumption refused");
4659 false
4660 }
4661 }
4662 } else {
4663 false
4664 };
4665 if !authorized {
4666 task.hold_machine(Some(format!("Base synchronization remains stopped. {} A release without a new owner approval grants no additional synchronization budget and starts no replacement competition.", held.base_sync_next_action())));
4667 task.base_sync_notice(&held);
4669 task.resume_override = None;
4670 record(queue, task);
4671 return Vec::new();
4672 }
4673 }
4674 let unfinished = (!task.fresh_start)
4675 .then(|| unfinished_run(&resume_runs, task.short()))
4676 .flatten()
4677 .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
4678 let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
4679 if task.repair_grants.last().is_some_and(|receipt| {
4680 task.execution_runs().last() == Some(&receipt.request.run)
4681 && task.operator_decided_at == receipt.decision
4682 && previous
4683 .as_ref()
4684 .is_none_or(|run| run.id != receipt.request.run)
4685 }) {
4686 task.hold_unrequested_retry(Some(
4687 "The retained repair run cannot be read or no longer owns this task's recovery. Inspect the saved grant and run; no replacement was started.".into(),
4688 ));
4689 record(queue, task);
4690 return Vec::new();
4691 }
4692 if let Some(id) = &task.disk_resume_run
4693 && unfinished.as_ref() != Some(id)
4694 {
4695 task.hold_manual(Some("Automatic disk recovery cannot resume the retained execution safely. Inspect its state and recovery approvals; no replacement competition was started.".into()));
4696 record(queue, task);
4697 return Vec::new();
4698 }
4699
4700 if !task.fresh_start
4701 && task.pr_recovery.is_none()
4702 && task.review_branch.is_none()
4703 && task.resume_override.is_none()
4704 && previous
4705 .as_ref()
4706 .is_some_and(|run| run.retired_to.is_some())
4707 && unfinished.is_none()
4708 {
4709 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()));
4710 record(queue, task);
4711 return Vec::new();
4712 }
4713
4714 let saved_recovery = previous.as_ref().filter(|run| {
4715 task.replacement.is_none()
4716 && task.pr_recovery.as_ref().is_some_and(|selected| {
4717 selected
4718 .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
4719 .is_ok()
4720 && selected_starter(selected, Some(run), unfinished.as_deref())
4721 == Starter::Resume(run.id.clone())
4722 })
4723 });
4724
4725 let explicit = match &task.overrides {
4729 Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
4730 Some(_) => opts.config.as_deref(),
4731 None => opts.config.as_deref(),
4732 };
4733 let (mut config, layers) = if let Some(run) = saved_recovery {
4734 let mut saved = run.clone();
4737 if let Err(e) = saved.configure_recovery_resume() {
4738 task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
4739 record(queue, task);
4740 return Vec::new();
4741 }
4742 (saved.config, Vec::new())
4743 } else {
4744 let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
4745 Ok(loaded) => loaded,
4746 Err(e) => {
4747 let reason = format!("[config] {e:#}");
4748 record_config_failure(task, &e);
4749 task.last_error = Some(reason.clone());
4750 task.hold_machine(Some(reason));
4751 record(queue, task);
4752 return Vec::new();
4753 }
4754 };
4755 if let Err(e) = apply_options(&mut config, opts, task) {
4756 task.hold_manual(Some(format!(
4757 "[config] {e:#}; correct the merge override before releasing the task"
4758 )));
4759 record(queue, task);
4760 return Vec::new();
4761 }
4762 if let Some(selected) = &task.pr_recovery
4763 && let Err(e) = selected.configure(&mut config)
4764 {
4765 task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
4766 record(queue, task);
4767 return Vec::new();
4768 }
4769 (config, layers)
4770 };
4771 let config_evidence = crate::pr_recovery::ConfigEvidence {
4772 layers,
4773 overrides: task.overrides.clone(),
4774 daemon_merge: task
4775 .overrides
4776 .as_ref()
4777 .is_none_or(|o| o.inherit_daemon_options)
4778 .then(|| opts.merge.clone())
4779 .flatten(),
4780 };
4781 apply_task_implementers(&mut config, task);
4782 if let Some(replacement) = &task.replacement {
4783 let safe = RunState::load(&replacement.run).is_ok_and(|old| {
4784 old.liveness(false) == Liveness::Dead
4785 && old.merge_decision.as_ref().is_some_and(|d| {
4786 d.closed
4787 && d.question == replacement.question
4788 && d.replacement_run.as_ref().is_none_or(|run| {
4789 task.execution_runs().last() == Some(run)
4790 && RunState::load(run).is_ok_and(|current| {
4791 current.replaces.as_ref().is_some_and(|pin| {
4792 pin.question == replacement.question
4793 && pin.agent == replacement.agent
4794 })
4795 })
4796 })
4797 })
4798 });
4799 if !safe {
4800 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()));
4801 record(queue, task);
4802 return Vec::new();
4803 }
4804 match config.agent(&replacement.agent) {
4805 Ok(agent) if crate::agent::installed(agent) => {}
4806 _ => {
4807 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)));
4808 record(queue, task);
4809 return Vec::new();
4810 }
4811 }
4812 config.graph.implementers = 1;
4813 config.graph.land_approval = true;
4814 config.merge.mode = MergeMode::Pr;
4815 config.graph.selected_implementer = Some(replacement.agent.clone());
4816 }
4817 let p = phrases(&config.graph.language);
4818 let start_failed = p.could_not_start;
4819 if let Ok(base) =
4824 crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
4825 .await
4826 && let Ok(head) =
4827 crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
4828 {
4829 let mut inputs = crate::queue::recovery_inputs(&task.sources);
4830 if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
4831 let source = crate::git::rev_parse(&repo, branch)
4832 .await
4833 .unwrap_or_default();
4834 inputs.push_str(&format!(";review:{branch}:{source}"));
4835 }
4836 if let Some(reason) = task
4837 .recovery_exhausted(
4838 &head,
4839 &inputs,
4840 task.attempt_limit
4841 .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
4842 )
4843 .filter(|_| {
4844 !task.repair_grants.last().is_some_and(|receipt| {
4845 RunState::load(&receipt.request.run)
4846 .is_ok_and(|run| crate::repair_budget::pending(task, &run))
4847 })
4848 })
4849 {
4850 task.hold_recovery_budget(
4851 reason,
4852 crate::queue::RecoveryAdmission { base: head, inputs },
4853 );
4854 record(queue, task);
4855 return Vec::new();
4856 }
4857 task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
4858 }
4859
4860 let consume_review = !previous
4881 .as_ref()
4882 .is_some_and(|state| crate::repair_budget::pending(task, state));
4883 let review_branch = consume_review
4884 .then(|| review_branch_for(task, previous.as_ref()))
4885 .flatten();
4886 let branch_exists = match review_branch {
4887 Some(branch) => crate::git::branch_exists(&repo, branch)
4888 .await
4889 .unwrap_or(false),
4890 None => false,
4891 };
4892 let proposed = review_retry_starter(
4896 task,
4897 previous.as_ref(),
4898 review_branch,
4899 branch_exists,
4900 unfinished.as_deref(),
4901 );
4902 let retry_selected = task.replacement.is_some()
4903 && task.resumption.is_some()
4904 && !task.fresh_start
4905 && previous.as_ref().is_some_and(|run| {
4906 run.replaces.is_some()
4907 && ((run.status == RunStatus::Failed && run.viable().is_empty())
4908 || (run.status == RunStatus::Blocked && run.tally.is_none()))
4909 });
4910 let stop_pin = task
4911 .resume_override
4912 .as_ref()
4913 .filter(|pin| {
4914 Questions::open()
4915 .get_for_effects(&pin.question_id)
4916 .is_ok_and(|q| {
4917 q.node == land::APPROVAL_NODE
4918 && q.resolution()
4919 .as_deref()
4920 .is_some_and(crate::merge_decision::stops)
4921 })
4922 })
4923 .and_then(|pin| pin.pinned_run.clone());
4924 let granted_run = task.repair_grants.last().and_then(|receipt| {
4925 let state = RunState::load(&receipt.request.run).ok()?;
4926 crate::repair_budget::pending(task, &state).then(|| receipt.request.run.clone())
4927 });
4928 let starter = if let Some(run) = granted_run {
4929 Starter::Resume(run)
4930 } else if let Some(owner) = &public_owner {
4931 Starter::Resume(owner.id.clone())
4932 } else if let Some(run) = stop_pin {
4933 Starter::Resume(run)
4936 } else if retry_selected {
4937 Starter::Resume(previous.as_ref().unwrap().id.clone())
4938 } else if let Some(selected) = &task.pr_recovery {
4939 if selected
4940 .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
4941 .is_ok()
4942 {
4943 selected_starter(selected, previous.as_ref(), unfinished.as_deref())
4944 } else {
4945 Starter::Review(selected.branch.clone())
4946 }
4947 } else {
4948 starter_with_implementers(task, previous.as_ref(), proposed)
4949 };
4950 let disk_reason = match &starter {
4953 Starter::Resume(id) => previous.as_ref().filter(|run| &run.id == id).map_or_else(
4954 || {
4955 RunState::load(id)
4956 .ok()
4957 .and_then(|run| disk_gate(&run.repo, &run.config))
4958 },
4959 |run| disk_gate(&run.repo, &run.config),
4960 ),
4961 _ => disk_gate(&repo, &config),
4962 };
4963 if let Some(reason) = disk_reason {
4964 task.notice_cause("disk-space", None, None);
4965 task.last_error = Some(reason.clone());
4966 let disk_checked_at = task.disk_checked_at;
4967 task.hold_machine(Some(reason.clone()));
4968 if matches!(starter, Starter::Resume(_)) {
4969 task.mark_disk_capacity();
4970 } else {
4971 task.mark_startup_disk_capacity();
4972 }
4973 task.disk_checked_at = disk_checked_at;
4974 record(queue, task);
4975 tracing::warn!("holding {} for want of disk space: {reason}", task.short());
4976 notices::raise(
4977 Notice::warn(
4978 &format!("disk:{}", repo.display()),
4979 format!("Task {} is waiting for disk space. It will resume automatically when disk and output admission checks succeed.", task.id),
4980 )
4981 .link(Link::Task {
4982 id: task.id.clone(),
4983 }),
4984 );
4985 return Vec::new();
4986 }
4987 let review_branch = if consume_review {
4988 let valid = review_branch.is_some();
4989 task.review_instruction = None;
4990 task.review_branch.take().filter(|_| valid)
4991 } else {
4992 None
4993 };
4994 if let Some(pin) = &task.resume_override
4997 && let Some(run) = &pin.pinned_run
4998 && starter != Starter::Resume(run.clone())
4999 {
5000 let run = run.clone();
5001 task.notice_cause("resume-owner", Some(&run), None);
5002 task.hold_machine(Some(format!(
5003 "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
5004 task.id
5005 )));
5006 record(queue, task);
5007 return Vec::new();
5008 }
5009 if let Some(run) = &task.disk_resume_run
5013 && starter != Starter::Resume(run.clone())
5014 {
5015 task.hold_manual(Some("Automatic disk recovery cannot resume the retained execution safely: the task's current settings would start a different run. Inspect its state and recovery approvals; no replacement competition was started.".into()));
5016 record(queue, task);
5017 return Vec::new();
5018 }
5019 if task.replacement.is_some()
5020 && previous.as_ref().is_some_and(|run| run.replaces.is_some())
5021 && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
5022 {
5023 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()));
5024 record(queue, task);
5025 return Vec::new();
5026 }
5027 if let Some(reason) = retained_attempt_hold(
5028 task,
5029 &starter,
5030 config.disk.retained_attempt_limit,
5031 RunState::load,
5032 ) {
5033 if let Starter::Review(branch) = &starter {
5036 task.review_branch = Some(branch.clone());
5037 }
5038 task.hold_unrequested_retry(Some(reason));
5039 record(queue, task);
5040 return Vec::new();
5041 }
5042 let attachments = match task_attachments(queue, task) {
5047 Ok(a) => a,
5048 Err(e) => {
5049 task.attempts += 1;
5050 task.fail_startup_target(
5051 "startup-attachments",
5052 e.name.clone(),
5053 format!("{start_failed}{e:#}"),
5054 opts.max_attempts,
5055 );
5056 record(queue, task);
5057 return Vec::new();
5058 }
5059 };
5060 let startup_pause = stop.pause();
5061 let startup_interrupt = interrupt_pause.clone();
5062 let wait = crate::repo_lock::WaitPolicy::new(
5063 Duration::from_secs(config.graph.timeout_resource_wait),
5064 move || startup_pause.parked() || startup_interrupt.parked(),
5065 );
5066 let started = wait.scope(Box::pin(async { match &starter {
5069 Starter::Review(_) if task.pr_recovery.is_some() => {
5070 let selected = task.pr_recovery.clone().expect("selected recovery");
5071 match selected.check_task_assignment(&task.id, &task.instruction, task.reassignments.len()) {
5072 Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
5073 .await
5074 .map(|mut r| {
5075 r.state.attachments = attachments.clone();
5076 r
5077 }),
5078 Err(e) => Err(e),
5079 }
5080 }
5081 Starter::Review(branch) => {
5082 tracing::info!(
5083 "task {} reopens `{branch}` as a review-only pass",
5084 task.short()
5085 );
5086 let takeover = crate::handover::Takeover {
5089 earlier: task.earlier_attempts().to_vec(),
5090 home: crate::run::home(),
5091 choice: take_divergence_answer(branch, &config.merge.remote, task),
5092 task_instruction: Some(instruction_for(task)),
5093 };
5094 Runner::review_taking_over(
5095 &repo,
5096 branch,
5097 config,
5098 Some(takeover),
5099 crate::run::Origin::queue(&task.id),
5100 )
5101 .await
5102 }
5103 Starter::Resume(id) => {
5104 tracing::info!("resuming run {id} rather than competing again");
5105 Runner::resume(id).and_then(|mut r| {
5106 if retry_selected {
5107 for candidate in &mut r.state.candidates {
5110 candidate.failed = None;
5111 candidate.empty = false;
5112 candidate.commits = 0;
5113 }
5114 r.state.status = RunStatus::Implementing;
5115 r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
5116 }
5117 if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
5118 r.state.sources = task.sources.clone();
5119 }
5120 if r.state.prep_failure.is_some() {
5121 let approval = task
5122 .resumption
5123 .as_ref()
5124 .context("preparation retry requires an explicit task release")?;
5125 r.retry_preparation(approval.at)?;
5126 }
5127 if let Some(instruction) =
5128 prepare_instruction(&starter, Some(&r.state.instruction), task)
5129 {
5130 r.state.instruction = instruction;
5131 }
5132 r.state.attachments = attachments.clone();
5133 if task.replacement.is_some() {
5134 r.state.config.merge.mode = MergeMode::Pr;
5135 r.state.config.graph.land_approval = true;
5136 }
5137 if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
5141 .overrides
5142 .as_ref()
5143 .and_then(|o| o.merge.as_deref())
5144 .and_then(|m| merge_mode(m).ok())
5145 {
5146 r.state.config.merge.mode = mode;
5147 }
5148 Ok(r)
5149 })
5150 }
5151 Starter::Start => {
5152 if let Some(branch) = &review_branch {
5153 tracing::warn!(
5154 "conductor chose review for task {} but branch `{branch}` no longer \
5155 exists; requeuing as a fresh competition instead",
5156 task.short()
5157 );
5158 }
5159 let instruction = prepare_instruction(&starter, None, task)
5160 .unwrap_or_else(|| task.instruction.clone());
5161 Runner::start_naming(
5162 &repo,
5163 instruction,
5164 &task.title,
5165 config,
5166 crate::run::Origin::queue(&task.id),
5167 )
5168 .await
5169 .map(|mut r| {
5170 r.state.attachments = attachments.clone();
5171 r.state.sources = task.sources.clone();
5172 r
5173 })
5174 }
5175 }})).await;
5176 if let Err(error) = &started
5177 && let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>()
5178 {
5179 task.record_startup_failure(failure.clone());
5180 }
5181 let mut runner = match started {
5182 Ok(r) => r,
5183 Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
5184 let detail = format!("{e:#}");
5185 task.last_error = Some(detail.clone());
5186 if e.is::<crate::build_target::AdmissionDiskWait>()
5187 && let Starter::Review(branch) = &starter
5188 && review_branch.is_some()
5189 {
5190 task.review_branch = Some(branch.clone());
5191 task.review_instruction = Some(task.instruction.clone());
5192 }
5193 if stop.parking() || interrupt_pause.parked() {
5194 let attempts = task.attempts;
5195 task.park(e.to_string());
5196 task.attempts = attempts;
5198 } else if e.is::<crate::build_target::AdmissionDiskWait>() {
5199 let disk_checked_at = task.disk_checked_at;
5200 task.hold_machine(Some(detail));
5201 task.mark_startup_disk_capacity();
5202 task.disk_checked_at = disk_checked_at;
5203 } else {
5204 task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
5205 }
5206 record(queue, task);
5207 return Vec::new();
5208 }
5209 Err(e) if task.pr_recovery.is_some() => {
5213 task.startup_notice_cause("startup-public-head");
5214 task.attempts += 1;
5215 task.last_error = Some(format!("{start_failed}{e:#}"));
5216 task.hold_unrequested_retry(Some(format!(
5217 "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."
5218 )));
5219 record(queue, task);
5220 return Vec::new();
5221 }
5222 Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
5223 let detail = match e.downcast_ref::<crate::handover::Refused>() {
5224 Some(r) => (p.handover_refused)(r),
5225 None => format!("{e:#}"),
5226 };
5227 task.startup_notice_cause("startup-handover");
5228 let reason = format!("{start_failed}{detail}");
5229 task.last_error = Some(reason.clone());
5230 let branch = match &starter {
5233 Starter::Review(branch) => Some(branch.clone()),
5234 _ => None,
5235 };
5236 task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
5240 record(queue, task);
5241 tracing::warn!(
5242 "holding {} for a branch it cannot take over: {e:#}",
5243 task.short()
5244 );
5245 return Vec::new();
5246 }
5247 Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
5252 let d = e
5253 .downcast_ref::<crate::reconcile::Diverged>()
5254 .expect("checked by the guard");
5255 let mut q = ask::Question::new(
5256 task.id.clone(),
5257 crate::reconcile::NODE.to_owned(),
5258 crate::reconcile::SEAT.to_owned(),
5259 d.summary(),
5260 d.detail(),
5261 d.choices(),
5262 );
5263 match Questions::open().put(&mut q) {
5264 Ok(()) => {
5265 task.last_error = Some(format!("{e:#}"));
5266 task.review_branch = Some(d.branch.clone());
5269 task.review_instruction = Some(task.instruction.clone());
5270 task.block(vec![q.id.clone()], Some(d.summary()));
5271 }
5272 Err(put) => {
5273 tracing::warn!("could not file the divergence question: {put:#}");
5274 task.attempts += 1;
5275 task.fail_startup(
5276 "startup-question-store",
5277 format!("{start_failed}{e:#}"),
5278 opts.max_attempts,
5279 );
5280 }
5281 }
5282 record(queue, task);
5283 return Vec::new();
5284 }
5285 Err(e) => {
5286 if e.downcast_ref::<crate::reconcile::Stale>().is_some()
5292 && let Starter::Review(branch) = &starter
5293 {
5294 task.review_branch = Some(branch.clone());
5295 task.review_instruction = Some(task.instruction.clone());
5296 task.last_error = Some(format!("{start_failed}{e:#}"));
5297 task.status = crate::queue::TaskStatus::Failed;
5298 record(queue, task);
5299 return Vec::new();
5300 }
5301 task.attempts += 1;
5302 task.last_error = Some(format!("{start_failed}{e:#}"));
5303 task.startup_notice_cause("startup-source");
5304 task.hold_unrequested_retry(Some(format!(
5305 "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
5306 )));
5307 record(queue, task);
5308 return Vec::new();
5309 }
5310 };
5311 if !matches!(starter, Starter::Resume(_))
5312 && let Some((mode, source)) = task.build_cache_override(&runner.state.config)
5313 {
5314 runner
5315 .state
5316 .event("build-cache", format!("{mode} selected by {source}"));
5317 }
5318 if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
5319 runner.state.recovery_config = Some(config_evidence);
5320 }
5321 if let Some(replacement) = &task.replacement {
5322 if matches!(starter, Starter::Start) {
5323 runner.state.instruction.push_str(&format!(
5324 "\n\n# Replacement review context\n{}",
5325 replacement.context
5326 ));
5327 }
5328 runner.state.replaces = Some(replacement.clone());
5329 runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
5330 if let Ok(mut old) = RunState::load(&replacement.run)
5331 && let Some(d) = &mut old.merge_decision
5332 {
5333 d.replacement_run = Some(runner.state.id.clone());
5334 old.event(
5335 "replacement",
5336 format!(
5337 "replacement run {} owns the next attempt; old PR remains closed",
5338 runner.state.id
5339 ),
5340 );
5341 if let Err(e) = old.save() {
5342 let error = runner.fail_startup("replacement-history", e);
5343 if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5344 task.record_startup_failure(failure.clone());
5345 }
5346 task.hold_manual(Some(format!(
5347 "Could not link replacement history: {error:#}; no agents dispatched"
5348 )));
5349 record(queue, task);
5350 return Vec::new();
5351 }
5352 }
5353 }
5354 runner.state.task_instruction = Some(task.instruction.clone());
5355 runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
5358 if runner.state.origin_chat.is_none() {
5359 runner.state.origin_chat = task.chat_talk().map(str::to_owned);
5360 }
5361 runner.on_pause(stop.pause());
5363 runner.watch_interrupt(interrupt_pause);
5367
5368 let run = runner.state.id.clone();
5371 let before_start = task.clone();
5372 task.start(run.clone());
5373 if let Err(error) = queue.put(task) {
5374 *task = before_start;
5375 let error = runner.fail_startup("task-start", error);
5376 if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5377 task.record_startup_failure(failure.clone());
5378 }
5379 task.hold_manual(Some(format!(
5380 "Could not persist task start; no agents dispatched: {error:#}"
5381 )));
5382 record(queue, task);
5383 return Vec::new();
5384 }
5385 if task.status != TaskStatus::Running {
5386 return Vec::new();
5388 }
5389 lock(status).current.push(Current {
5390 worker: None,
5391 task: task.id.clone(),
5392 run,
5393 });
5394
5395 let quota_before = runner.state.quota.clone();
5398 runner.state.carry_dispatched_resumes(task);
5399 runner.state.next_pass_task_entry = true;
5400 let result = runner.execute().await;
5401 finish_attempt(
5402 opts.max_attempts,
5403 queue,
5404 task,
5405 &runner.state,
5406 "a_before,
5407 result,
5408 )
5409}
5410
5411async fn attempt_sync_only(
5412 queue: &Queue,
5413 status: &Arc<Mutex<Status>>,
5414 stop: &Stop,
5415 interrupt: crate::graph::Pause,
5416 task: &mut Task,
5417 request: crate::base_sync_only::Request,
5418) {
5419 let result = async {
5420 anyhow::ensure!(
5421 task.status == TaskStatus::Queued
5422 && task.execution_runs().last() == Some(&request.run)
5423 && task.resume_override.as_ref().is_some_and(
5424 |pin| pin.at == request.at && pin.pinned_run.as_ref() == Some(&request.run)
5425 ),
5426 "sync-base-only request no longer owns the exact queued run"
5427 );
5428 let mut runner = Runner::resume(&request.run)?;
5429 anyhow::ensure!(
5430 public_resume_owner(&crate::run::home(), &task.runs, &runner.state.repo)
5431 .await?
5432 .is_none(),
5433 "the task still has a public execution owner"
5434 );
5435 anyhow::ensure!(
5436 !stop.parking() && !interrupt.parked(),
5437 "paused before base synchronization"
5438 );
5439 let original = task.clone();
5440 task.start(request.run.clone());
5441 task.attempts = original.attempts;
5442 if let Err(error) = queue.put(task) {
5443 *task = original;
5444 return Err(error);
5445 }
5446 if task.status != TaskStatus::Running || task.sync_only.as_ref() != Some(&request) {
5447 return Ok(());
5448 }
5449 lock(status).current.push(Current {
5450 worker: None,
5451 task: task.id.clone(),
5452 run: request.run.clone(),
5453 });
5454 runner.on_pause(stop.pause());
5455 runner.watch_interrupt(interrupt);
5456 runner.execute_sync_only(request.clone()).await
5457 }
5458 .await;
5459 if task.sync_only.as_ref() == Some(&request) {
5460 let saved = RunState::load(&request.run).ok();
5461 let detail = result.err().map(|error| {
5462 format!("Base synchronization only: {error:#}; verification was not allowed")
5463 });
5464 crate::base_sync_only::settle(task, &request, saved.as_ref(), detail);
5465 record(queue, task);
5466 }
5467}
5468
5469pub fn finish_attempt(
5474 max_attempts: usize,
5475 queue: &Queue,
5476 task: &mut Task,
5477 state: &RunState,
5478 quota_before: &[QuotaLoss],
5479 result: Result<()>,
5480) -> Vec<QuotaLoss> {
5481 let detail = match result {
5482 Ok(()) => describe(state),
5483 Err(e) => format!("{e:#}"),
5484 };
5485 let fresh = losses_this_attempt(quota_before, &state.quota);
5486 let verdict = Verdict {
5487 status: state.status,
5488 left_pr: state.pr.is_some(),
5491 quota_hit: !fresh.is_empty(),
5497 parked: state.parked,
5501 no_viable_candidates: state.viable().is_empty(),
5504 };
5505 if let Some(replacement) = &state.replaces
5506 && let Some(pr) = &state.pr
5507 && let Ok(mut old) = RunState::load(&replacement.run)
5508 && let Some(d) = &mut old.merge_decision
5509 {
5510 d.replacement_pr = Some(pr.url.clone());
5511 let _ = old.save();
5512 }
5513 settle_and_diagnose(task, verdict, &detail, max_attempts, state);
5514 if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
5515 task.hold_unrequested_retry(Some(format!(
5516 "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.",
5517 task.short()
5518 )));
5519 }
5520 if task.status == TaskStatus::Done {
5521 supersede_prior_runs(task, &crate::run::home());
5522 }
5523 record(queue, task);
5524 tracing::info!(
5525 "task {} is {} after run {} ({})",
5526 task.short(),
5527 task.status.as_str(),
5528 state.short(),
5529 label(state.status)
5530 );
5531 fresh
5532}
5533
5534pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
5538 if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
5541 && !awaiting_resume_with(task, RunState::load)
5542 && withheld_text_wait(task).is_none()
5546 && !(task.fresh_start && task.replacement.is_some())
5547 {
5548 let why = task.last_error.clone().map_or_else(
5549 || "the run did not finish".to_owned(),
5550 |e| format!("the run did not finish: {e}"),
5551 );
5552 task.hold_unrequested_retry(Some(format!(
5553 "{why}. It was started by hand, so it is not retried \
5554 automatically; `magi task release` retries it."
5555 )));
5556 record(queue, task);
5557 }
5558}
5559
5560#[must_use]
5564pub fn loop_would_resume(run: &str) -> bool {
5565 unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
5566}
5567
5568#[must_use]
5578pub fn foreign_loop(
5579 reading: Option<&Reading>,
5580 now: Timestamp,
5581 own_pid: u32,
5582) -> Option<Option<u32>> {
5583 let reading = reading.filter(|r| r.running(now))?;
5584 match reading.pid {
5585 Some(pid) if pid == own_pid => None,
5586 pid => Some(pid),
5587 }
5588}
5589
5590fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
5591 reading.worker_protocol != Some(1)
5592 && (foreign_loop(Some(reading), now, own_pid).is_some()
5593 || reading
5594 .pid
5595 .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
5596}
5597
5598pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
5609 run_claimed_until(opts, queue, task, &Stop::new()).await;
5610}
5611
5612async fn run_claimed_until(
5613 opts: &Opts,
5614 queue: &Queue,
5615 task: &mut Task,
5616 stop: &Stop,
5617) -> Vec<QuotaLoss> {
5618 let status = Arc::new(Mutex::new(Status::new()));
5619 let mut quota = Box::pin(attempt(
5622 opts,
5623 queue,
5624 &status,
5625 stop,
5626 crate::graph::Pause::new(),
5627 task,
5628 ))
5629 .await;
5630 let mut resumes = 0;
5639 while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
5640 let Some(timeout) = withheld_text_wait(task) else {
5641 break;
5642 };
5643 eprintln!(
5644 "waiting for the owner's answer on a withheld pull request text \
5645 (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
5646 );
5647 let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
5650 let ready = loop {
5651 match land_resume_state(task) {
5652 LandResume::StillWaiting
5653 if !stop.parking() && std::time::Instant::now() < limit =>
5654 {
5655 tokio::time::sleep(WITHHELD_POLL).await;
5656 }
5657 LandResume::Ready => break true,
5658 _ => break false,
5659 }
5660 };
5661 if !ready || stop.parking() {
5662 break;
5663 }
5664 resumes += 1;
5665 quota.extend(
5666 Box::pin(attempt(
5667 opts,
5668 queue,
5669 &status,
5670 stop,
5671 crate::graph::Pause::new(),
5672 task,
5673 ))
5674 .await,
5675 );
5676 }
5677 hold_if_runnable(queue, task);
5678 quota
5679}
5680
5681const MAX_WITHHELD_RESUMES: u32 = 3;
5684
5685const WITHHELD_POLL: Duration = Duration::from_secs(15);
5687
5688fn withheld_text_wait(task: &Task) -> Option<u64> {
5691 let id = task.execution_runs().last()?;
5692 let s = RunState::load(id).ok()?;
5693 (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
5694 .then_some(s.config.graph.answer_timeout)
5695}
5696
5697fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
5707 after
5708 .iter()
5709 .filter(|q| !before.contains(q))
5710 .cloned()
5711 .collect()
5712}
5713
5714fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
5717 let quota: Vec<_> = quota
5718 .iter()
5719 .filter(|q| q.cause == crate::agent::QuotaCause::UsageLimit)
5720 .collect();
5721 if quota.is_empty() {
5722 return None;
5723 }
5724 let with_hint = quota.iter().find(|q| q.reset.is_some());
5725 let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
5726 let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
5727 let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
5728 Some(
5729 now.checked_add(jiff::SignedDuration::from_secs(secs))
5730 .unwrap_or(Timestamp::MAX),
5731 )
5732}
5733
5734fn implementers_match(task: &Task, state: &RunState) -> bool {
5736 task.replacement.as_ref().map_or_else(
5737 || {
5738 task.implementers()
5739 .is_none_or(|n| n == state.config.graph.implementers)
5740 },
5741 |replacement| {
5742 state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
5743 && state.config.graph.implementers == 1
5744 },
5745 )
5746}
5747
5748fn starter_with_implementers(
5750 task: &Task,
5751 previous: Option<&RunState>,
5752 proposed: Starter,
5753) -> Starter {
5754 if previous.is_some_and(|s| !implementers_match(task, s)) {
5755 task.review_of
5756 .as_ref()
5757 .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
5758 } else {
5759 proposed
5760 }
5761}
5762
5763fn apply_task_implementers(config: &mut Config, task: &Task) {
5765 if let Some(n) = task.implementers() {
5766 config.graph.implementers = n;
5767 }
5768}
5769
5770#[cfg(test)]
5775fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
5776 let explicit = match &task.overrides {
5777 Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
5778 _ => opts.config.as_deref(),
5779 };
5780 let (mut config, _) = Config::discover(repo, explicit)?;
5781 apply_options(&mut config, opts, task)?;
5782 Ok(config)
5783}
5784
5785fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
5786 if task
5787 .overrides
5788 .as_ref()
5789 .is_none_or(|o| o.inherit_daemon_options)
5790 && let Some(mode) = opts.merge.as_deref()
5791 {
5792 config.merge.mode = merge_mode(mode)?;
5793 }
5794 if let Some(o) = &task.overrides {
5795 o.apply(config);
5796 }
5797 if let Some((mode, _)) = task.build_cache_override(config) {
5798 config.verify.build_cache = mode;
5799 }
5800 Ok(())
5801}
5802
5803fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
5805 let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
5806 if let Some(mode) = &opts.merge {
5807 config.merge.mode = merge_mode(mode)?;
5808 }
5809 Ok(config)
5810}
5811
5812async fn maybe_prune_cache_between_runs(
5817 repo: &Path,
5818 opts: &Opts,
5819 home: &Path,
5820 stop: &Stop,
5821 last_checked: &mut Option<Timestamp>,
5822 now: Timestamp,
5823) {
5824 if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
5825 return;
5826 }
5827 *last_checked = Some(now);
5828 let cfg = match prepare(repo, opts) {
5829 Ok(cfg) => cfg,
5830 Err(e) => {
5831 tracing::warn!("cache check: no config: {e:#}");
5832 return;
5833 }
5834 };
5835 match clean::prune_cache_if_over_limit(&cfg, home) {
5836 Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
5837 "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
5838 pruned.files,
5839 pruned.freed
5840 ),
5841 Ok(_) => {}
5842 Err(e) => {
5843 tracing::warn!("housekeep: prune cache: {e:#}");
5844 notices::raise_in(
5845 home,
5846 Notice::warn(
5847 "housekeep:cache",
5848 format!(
5849 "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
5850 e.to_string()
5851 .lines()
5852 .next()
5853 .unwrap_or("unknown cleanup error")
5854 ),
5855 ),
5856 );
5857 }
5858 }
5859}
5860
5861fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
5865 last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
5866}
5867
5868async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
5887 let cfg = match prepare(repo, opts) {
5888 Ok(cfg) => cfg,
5889 Err(e) => {
5890 tracing::warn!("housekeep: no config: {e:#}");
5891 return;
5892 }
5893 };
5894 let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
5903 let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
5904 if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
5909 let mut extra = Vec::new();
5910 if out.unreadable > 0 {
5911 extra.push(format!("{} unreadable", out.unreadable));
5912 }
5913 if out.orphaned_worktrees > 0 {
5914 extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
5915 }
5916 let detail = if extra.is_empty() {
5917 String::new()
5918 } else {
5919 format!(" ({})", extra.join(", "))
5920 };
5921 tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
5922 }
5923 if out.external_merges_recorded > 0 {
5924 tracing::info!(
5925 "housekeep: recorded {} run(s) as merged externally",
5926 out.external_merges_recorded
5927 );
5928 }
5929 if out.stale_pr_states_repaired > 0 {
5930 tracing::info!(
5931 "housekeep: rewrote {} run record(s) whose pull request had already settled",
5932 out.stale_pr_states_repaired
5933 );
5934 }
5935 if out.cache_files > 0 {
5936 tracing::info!(
5937 "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
5938 out.cache_files,
5939 out.cache_freed
5940 );
5941 }
5942 if out.questions_abandoned > 0 {
5943 tracing::info!(
5944 "housekeep: abandoned {} question(s) left open by a finished run",
5945 out.questions_abandoned
5946 );
5947 }
5948}
5949
5950async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
5959 let questions = Questions::at(home.join("questions"));
5960 let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
5961 if report.is_empty() {
5962 return;
5963 }
5964 if !report.quarantined.is_empty() {
5965 tracing::info!(
5966 "triage: held {} blocked task(s) whose blocked-on task or \
5967 question no longer exists: {}",
5968 report.quarantined.len(),
5969 report.quarantined.join(", ")
5970 );
5971 }
5972 if !report.resumed.is_empty() {
5973 tracing::info!(
5974 "triage: resumed {} held task(s) whose machine hold had resolved: {}",
5975 report.resumed.len(),
5976 report.resumed.join(", ")
5977 );
5978 }
5979 if !report.asked.is_empty() {
5980 tracing::info!(
5981 "triage: asked about {} held task(s): {}",
5982 report.asked.len(),
5983 report.asked.join(", ")
5984 );
5985 }
5986 if !report.answered.is_empty() {
5987 tracing::info!(
5988 "triage: applied {} operator answer(s): {}",
5989 report.answered.len(),
5990 report.answered.join(", ")
5991 );
5992 }
5993}
5994
5995pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
6002 disk_gate_at(repo, config, crate::run::home)
6003}
6004
6005pub(crate) fn disk_gate_at(
6006 repo: &Path,
6007 config: &Config,
6008 home: impl FnOnce() -> PathBuf,
6009) -> Option<String> {
6010 let measure = if crate::build_target::isolated(config) {
6011 crate::disk::managed_free_bytes
6012 } else {
6013 crate::disk::free_bytes
6014 };
6015 disk_gate_with(repo, config, home, measure)
6016}
6017
6018fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
6022 repo: &Path,
6023 config: &Config,
6024 home: impl FnOnce() -> PathBuf,
6025 free_bytes: F,
6026) -> Option<String> {
6027 let min = config.disk.min_free_bytes;
6028 if min == 0 {
6029 return None;
6030 }
6031 let output = match config.verify.build_cache {
6032 BuildCache::Shared => config.cache_dir(),
6033 BuildCache::Isolated => Some(home()),
6034 };
6035 let default_worktree_root;
6036 let worktree_root = match config.graph.worktree_root.as_deref() {
6037 Some(root) => root,
6038 None => {
6039 default_worktree_root = crate::run::default_worktree_root();
6040 &default_worktree_root
6041 }
6042 };
6043 for path in [Some(repo), output.as_deref(), Some(worktree_root)]
6044 .into_iter()
6045 .flatten()
6046 {
6047 let probe = if path == repo {
6048 path
6049 } else {
6050 path.ancestors().find(|p| p.exists()).unwrap_or(path)
6051 };
6052 let reason = match free_bytes(probe) {
6053 Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
6054 Err(e) => Some(crate::disk::unmeasured_in(
6055 probe,
6056 &e,
6057 &config.graph.language,
6058 )),
6059 };
6060 if reason.is_some() {
6061 return reason;
6062 }
6063 }
6064 None
6065}
6066
6067const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
6074
6075const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
6079
6080fn quota_wait(
6089 reset_at: Option<Timestamp>,
6090 now: Timestamp,
6091 fallback: Duration,
6092 cap: Duration,
6093) -> Duration {
6094 match reset_at {
6095 Some(at) if at > now => {
6096 let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
6097 Duration::from_secs(secs).min(cap)
6098 }
6099 _ => fallback,
6100 }
6101}
6102
6103fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
6117 parse_reset_hint_zoned(text, now)
6118 .or_else(|| parse_reset_hint_dated(text))
6119 .or_else(|| parse_reset_hint_relative(text, recorded))
6120}
6121
6122fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
6126 let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
6127 let mut rest = rest.trim();
6128 if rest.is_empty() {
6129 return None;
6130 }
6131 let mut total: i64 = 0;
6132 let mut matched = false;
6133 for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
6134 if let Some((digits, tail)) = rest.split_once(unit)
6135 && !digits.is_empty()
6136 && digits.bytes().all(|b| b.is_ascii_digit())
6137 {
6138 total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
6139 rest = tail;
6140 matched = true;
6141 }
6142 }
6143 if !rest.is_empty() || !matched {
6144 return None;
6145 }
6146 recorded
6147 .checked_add(jiff::SignedDuration::from_secs(total))
6148 .ok()
6149}
6150
6151fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
6155 let clock = clock.trim().to_lowercase();
6156 let (digits, pm) = clock
6157 .strip_suffix("am")
6158 .map(|d| (d, false))
6159 .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
6160 let (h, m) = digits.trim().split_once(':')?;
6161 let mut hour: i8 = h.trim().parse().ok()?;
6162 let minute: i8 = m.trim().parse().ok()?;
6163 if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
6164 return None;
6165 }
6166 if pm && hour != 12 {
6167 hour += 12;
6168 } else if !pm && hour == 12 {
6169 hour = 0;
6170 }
6171 Some((hour, minute))
6172}
6173
6174fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
6179 let open = text.find('(')?;
6180 let close = text.rfind(')')?;
6181 if close <= open {
6182 return None;
6183 }
6184 let zone = text[open + 1..close].trim();
6185 let (hour, minute) = parse_12h_clock(&text[..open])?;
6186 let tz = jiff::tz::TimeZone::get(zone).ok()?;
6187 let candidate = now
6188 .to_zoned(tz)
6189 .with()
6190 .hour(hour)
6191 .minute(minute)
6192 .second(0)
6193 .millisecond(0)
6194 .microsecond(0)
6195 .nanosecond(0)
6196 .build()
6197 .ok()?;
6198 let mut at = candidate.timestamp();
6199 if at <= now {
6200 at += jiff::SignedDuration::from_hours(24);
6201 }
6202 Some(at)
6203}
6204
6205fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
6214 let words: Vec<&str> = text.split_whitespace().collect();
6215 if words.len() < 5 {
6216 return None;
6217 }
6218 (0..=words.len() - 5)
6219 .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
6220}
6221
6222fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
6228 if trailing.is_some_and(|next| next.starts_with('(')) {
6229 return None;
6230 }
6231 let month = month_number(window[0])?;
6232 let day_token = window[1].strip_suffix(',')?.to_lowercase();
6233 let day_digits = ["st", "nd", "rd", "th"]
6234 .iter()
6235 .find_map(|suffix| day_token.strip_suffix(*suffix))?;
6236 let day: i8 = day_digits.parse().ok()?;
6237 let year_token = window[2];
6238 if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
6239 return None;
6240 }
6241 let year: i16 = year_token.parse().ok()?;
6242 let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
6246 let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
6247 let date = jiff::civil::Date::new(year, month, day).ok()?;
6248 let candidate = date
6249 .at(hour, minute, 0, 0)
6250 .to_zoned(jiff::tz::TimeZone::UTC)
6251 .ok()?;
6252 Some(candidate.timestamp())
6253}
6254
6255fn month_number(name: &str) -> Option<i8> {
6258 const NAMES: [&str; 12] = [
6259 "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
6260 ];
6261 let lower = name.to_lowercase();
6262 NAMES
6263 .iter()
6264 .position(|n| *n == lower.as_str())
6265 .map(|i| i as i8 + 1)
6266}
6267
6268#[cfg(test)]
6270fn exhausted_review_budget(state: &RunState) -> bool {
6271 !crate::handover::can_resume(state)
6274 && state.status == RunStatus::Blocked
6275 && !state.released()
6276 && state.retired_to.is_none()
6277}
6278
6279fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
6316 unfinished_run_with(runs, short, RunState::load)
6317}
6318
6319pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
6322where
6323 F: FnMut(&str) -> Result<RunState>,
6324{
6325 let mut id = runs.last()?.clone();
6326 let mut visited = std::collections::BTreeSet::new();
6327 let mut repo = None;
6328 loop {
6329 if !runs.contains(&id) || !visited.insert(id.clone()) {
6330 tracing::warn!("invalid or cyclic recovery authority for task {short}");
6331 return None;
6332 }
6333 let state = match load(&id) {
6334 Ok(state) if state.id == id => state,
6335 Ok(_) => return None,
6336 Err(e) => {
6337 tracing::warn!("could not read run {id} for task {short}: {e:#}");
6338 return None;
6339 }
6340 };
6341 if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
6342 return None;
6343 }
6344 repo = Some(state.repo.clone());
6345 if let Some(authority) = state.retired_to {
6346 id = authority;
6347 continue;
6348 }
6349 return (crate::handover::can_resume(&state)
6350 && state.liveness(false) != crate::run::Liveness::Live)
6351 .then_some(id);
6352 }
6353}
6354
6355fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
6363where
6364 F: FnOnce(&str) -> Result<RunState>,
6365{
6366 if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
6368 || task.fresh_start
6369 || task.review_branch.is_some()
6370 {
6371 return false;
6372 }
6373 let Some(id) = task.execution_runs().last() else {
6374 return false;
6375 };
6376 load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
6377}
6378
6379#[derive(Debug, Clone, PartialEq, Eq)]
6382enum Starter {
6383 Review(String),
6386 Resume(String),
6388 Start,
6390}
6391
6392fn retained_attempt_hold(
6397 task: &Task,
6398 starter: &Starter,
6399 limit: usize,
6400 mut load: impl FnMut(&str) -> Result<RunState>,
6401) -> Option<String> {
6402 if limit == 0 || matches!(starter, Starter::Resume(_)) {
6403 return None;
6404 }
6405 let mut retained = 0;
6406 for id in task
6407 .runs
6408 .iter()
6409 .chain(task.startup_failures.iter().map(|failure| &failure.run))
6410 .collect::<std::collections::BTreeSet<_>>()
6411 {
6412 let state = match load(id) {
6413 Ok(state) if state.id == *id => state,
6414 _ => {
6415 return Some(format!(
6416 "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
6417 ));
6418 }
6419 };
6420 if state.retired_to.is_some() || state.released() {
6421 continue;
6422 }
6423 retained += 1;
6426 }
6427 (retained >= limit).then(|| format!(
6428 "[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."
6429 ))
6430}
6431
6432fn selected_starter(
6434 selected: &crate::pr_recovery::Selection,
6435 previous: Option<&RunState>,
6436 unfinished: Option<&str>,
6437) -> Starter {
6438 if let Some(id) = unfinished
6439 && previous.is_some_and(|r| {
6440 r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
6441 })
6442 {
6443 Starter::Resume(id.to_owned())
6444 } else {
6445 Starter::Review(selected.branch.clone())
6446 }
6447}
6448
6449fn take_divergence_answer(
6453 branch: &str,
6454 remote: &str,
6455 task: &mut Task,
6456) -> Option<crate::reconcile::Choice> {
6457 let summary = crate::reconcile::summary_for(branch, remote);
6458 let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
6459 (a.question == summary)
6460 .then(|| crate::reconcile::Choice::from_answer(&a.answer))
6461 .flatten()
6462 .map(|c| (i, c))
6463 })?;
6464 task.answers.remove(idx);
6465 Some(choice)
6466}
6467
6468fn choose_starter(
6480 review_branch: Option<&str>,
6481 branch_exists: bool,
6482 unfinished: Option<&str>,
6483) -> Starter {
6484 match review_branch {
6485 Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
6486 Some(_) => Starter::Start,
6487 None => match unfinished {
6488 Some(id) => Starter::Resume(id.to_owned()),
6489 None => Starter::Start,
6490 },
6491 }
6492}
6493
6494fn review_retry_starter(
6498 task: &Task,
6499 previous: Option<&RunState>,
6500 branch: Option<&str>,
6501 exists: bool,
6502 unfinished: Option<&str>,
6503) -> Starter {
6504 if let Some(run) = previous
6505 && unfinished == Some(run.id.as_str())
6506 && run.reviewed_commits.is_some()
6507 && branch.is_some_and(|branch| {
6508 exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
6509 })
6510 && may_resume_run(run, task)
6511 {
6512 return Starter::Resume(run.id.clone());
6513 }
6514 match (branch, unfinished, &task.review_of) {
6515 (None, None, Some(branch)) => Starter::Review(branch.clone()),
6516 _ => choose_starter(branch, exists, unfinished),
6517 }
6518}
6519
6520fn review_branch_for<'a>(task: &'a Task, previous: Option<&RunState>) -> Option<&'a str> {
6522 task.review_branch
6523 .as_deref()
6524 .filter(|&branch| match &task.review_instruction {
6525 Some(authored) => *authored == task.instruction,
6526 None => previous.map_or_else(
6529 || task.review_of.as_deref() == Some(branch),
6530 |run| compatible_run_instruction(run, task),
6531 ),
6532 })
6533}
6534
6535fn may_resume_run(run: &RunState, task: &Task) -> bool {
6538 if !task.assignment_accepts(run) {
6539 return false;
6540 }
6541 task.resume_override
6542 .as_ref()
6543 .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
6544 || compatible_run_instruction(run, task)
6545}
6546
6547pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
6549 if let Some(authored) = &run.task_instruction {
6550 return compatible_instruction(authored, task);
6551 }
6552 if compatible_instruction(&run.instruction, task) {
6553 return true;
6554 }
6555 if run.reviewed_commits.is_some() {
6558 if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
6559 return strip_answers_block(authored, task).trim() == task.instruction.trim();
6560 }
6561 if let Some(branch) = &task.review_of {
6562 let canonical = format!(
6563 "Review the branch `{branch}` (review-only: no implementation, no judging)."
6564 );
6565 let generated = format!(
6566 "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"
6567 );
6568 return task.instruction == canonical && run.instruction.starts_with(&generated);
6569 }
6570 }
6571 false
6572}
6573
6574pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
6576 strip_answers_block(old, task) == task.instruction
6577}
6578
6579fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
6582 if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
6583 return fallback.to_path_buf();
6584 }
6585 task.repo.clone()
6586}
6587
6588const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
6592
6593fn answers_block(task: &Task, count: usize) -> String {
6595 let mut s = ANSWERS_HEADER.to_owned();
6596 for a in &task.answers[..count] {
6597 s.push_str(&format!("- {}: {}\n", a.question, a.answer));
6598 }
6599 s
6600}
6601
6602fn resumption_block(r: &crate::queue::Resumption) -> String {
6605 format!(
6606 "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
6607 Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
6608 r.generation, r.at, r.instruction, r.answers_through,
6609 )
6610}
6611
6612fn append_answers(base: &str, task: &Task) -> String {
6614 let mut s = base.to_owned();
6615 if !task.answers.is_empty() {
6616 s.push_str(&answers_block(task, task.answers.len()));
6617 }
6618 if let Some(r) = &task.resumption {
6619 s.push_str(&resumption_block(r));
6620 }
6621 s
6622}
6623
6624fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
6628 let mut instruction = instruction;
6629 for approval in task
6630 .resumption
6631 .iter()
6632 .chain(task.resumption_history.iter().rev())
6633 {
6634 if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
6635 instruction = base;
6636 break;
6637 }
6638 }
6639 for count in (1..=task.answers.len()).rev() {
6640 let block = answers_block(task, count);
6641 if let Some(base) = instruction.strip_suffix(&block) {
6642 return base;
6643 }
6644 }
6645 instruction
6646}
6647
6648fn instruction_for(task: &Task) -> String {
6656 append_answers(&task.instruction, task)
6657}
6658
6659fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
6671 append_answers(strip_answers_block(old_instruction, task), task)
6672}
6673
6674fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
6676 let failure = error.downcast_ref::<crate::config::ConfigFailure>();
6677 task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
6678 if let Some(cause) = task.hold_notice_cause.as_mut() {
6679 cause.target = failure.map(|f| f.target.clone());
6680 }
6681}
6682
6683#[derive(Debug, thiserror::Error)]
6684#[error("attachment `{name}` is recorded on the task but {path} is missing")]
6685struct MissingAttachment {
6686 name: String,
6687 path: PathBuf,
6688}
6689
6690fn task_attachments(
6692 queue: &Queue,
6693 task: &Task,
6694) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
6695 let paths = queue.attachment_paths(task);
6696 for (name, path) in task.attachments.iter().zip(&paths) {
6697 if !path.is_file() {
6698 return Err(MissingAttachment {
6699 name: name.clone(),
6700 path: path.clone(),
6701 });
6702 }
6703 }
6704 Ok(paths)
6705}
6706
6707fn prepare_instruction(
6718 starter: &Starter,
6719 old_instruction: Option<&str>,
6720 task: &Task,
6721) -> Option<String> {
6722 match starter {
6723 Starter::Start => Some(instruction_for(task)),
6724 Starter::Resume(_) => Some(resumed_instruction(
6725 old_instruction.expect("a resumed run always has a prior instruction"),
6726 task,
6727 )),
6728 Starter::Review(_) => None,
6729 }
6730}
6731
6732fn record(queue: &Queue, task: &mut Task) {
6736 if let Err(e) = queue.put(task) {
6737 tracing::error!("could not record task {}: {e:#}", task.short());
6738 let notice = Notice::error(
6739 "loop:record",
6740 format!(
6741 "Task {} state could not be saved: {}. Check the disk.",
6742 task.id,
6743 e.to_string().lines().next().unwrap_or("unknown save error")
6744 ),
6745 )
6746 .link(Link::Task {
6747 id: task.id.clone(),
6748 });
6749 match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
6751 Some(home) => notices::raise_in(home, notice),
6752 None => notices::raise(notice),
6753 }
6754 }
6755}
6756
6757fn runnable(queue: &Queue) -> Vec<Task> {
6763 let mut tasks: Vec<Task> = queue
6764 .list()
6765 .into_iter()
6766 .filter(|t| t.status.runnable())
6767 .collect();
6768 tasks.sort_unstable_by(crate::queue::dispatch_order);
6769 tasks
6770}
6771
6772fn describe(state: &RunState) -> String {
6786 let p = phrases(&state.config.graph.language);
6787 let mut detail = if state.status == RunStatus::Stalled {
6788 let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
6789 seats.sort_unstable();
6790 seats.dedup();
6791 if seats.is_empty() {
6792 p.quorum_lost.to_owned()
6793 } else {
6794 format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
6795 }
6796 } else {
6797 format!("{}{}", p.run_ended, state.status.display_label())
6798 };
6799 if let Some(cause) = state.verification_blocking_cause() {
6800 detail.push_str(&format!(" ({cause})"));
6801 } else if let Some(last) = state.events.last() {
6802 let unanswered = state
6806 .reviews
6807 .last()
6808 .filter(|r| {
6809 state.status == RunStatus::Blocked
6810 && last.node == "review"
6811 && r.incomplete()
6812 && r.blocking == 0
6813 && r.round == state.config.graph.review_rounds
6814 && r.e2e.iter().all(crate::run::CommandOutcome::ok)
6815 })
6816 .map(|r| (r.expected - r.answered, r.round));
6817 match unanswered {
6818 Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
6819 detail.push_str(&format!(
6820 " ({}: {})",
6821 last.node,
6822 (p.reviewers_never_answered)(missing, rounds)
6823 ));
6824 }
6825 _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
6826 }
6827 }
6828 detail.push_str(&format!(" [run {}]", state.id));
6829 detail
6830}
6831
6832const DIAGNOSTIC_MAX: usize = 4_000;
6838
6839const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
6844
6845fn diagnostic(state: &RunState) -> Option<String> {
6859 let mut parts: Vec<String> = Vec::new();
6860
6861 for o in state.gate.iter().filter(|o| !o.ok()) {
6863 parts.push(format!(
6864 "gate `{}` failed ({}):\n{}",
6865 o.command,
6866 notices::exit_status(o.code),
6867 crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
6868 ));
6869 }
6870
6871 if let Some(last) = state
6874 .events
6875 .iter()
6876 .rev()
6877 .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
6878 {
6879 parts.push(last.message.clone());
6880 }
6881
6882 if state.viable().is_empty() {
6889 for c in &state.candidates {
6890 if let Some(evidence) = &c.verified_noop {
6891 parts.push(format!(
6892 "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
6893 c.label
6894 ));
6895 } else if !c.summary.trim().is_empty() {
6896 parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
6897 } else if let Some(why) = &c.failed {
6898 parts.push(format!("candidate {}: {why}", c.label));
6899 }
6900 }
6901 }
6902
6903 if parts.is_empty() {
6904 return None;
6905 }
6906 Some(crate::run::tail(
6911 &parts.join("\n\n"),
6912 DIAGNOSTIC_MAX.saturating_sub(100),
6913 ))
6914}
6915
6916fn label(status: RunStatus) -> &'static str {
6924 status.as_str()
6925}
6926
6927pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
6929 match mode {
6930 "none" => Ok(MergeMode::None),
6931 "local" => Ok(MergeMode::Local),
6932 "pr" => Ok(MergeMode::Pr),
6933 other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
6934 }
6935}
6936
6937fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
6942 mutex
6943 .lock()
6944 .unwrap_or_else(std::sync::PoisonError::into_inner)
6945}
6946
6947#[cfg(test)]
6948mod tests {
6949 use super::*;
6950 use crate::queue::{Source, TaskStatus};
6951 use crate::run::{Candidate, CommandOutcome};
6952 use pretty_assertions::assert_eq;
6953
6954 fn task() -> Task {
6955 Task::new(
6956 "add retries".to_owned(),
6957 "add retries".to_owned(),
6958 PathBuf::from("/repo"),
6959 Source::Human,
6960 )
6961 }
6962
6963 #[test]
6964 fn dispatch_wait_aggregates_unique_skips_in_stable_count_order() {
6965 let skips = DispatchSkips::from([
6966 ("a".into(), SkipReason::CoolingDown),
6967 ("b".into(), SkipReason::WaitingOnLanding),
6968 ("c".into(), SkipReason::WaitingOnLanding),
6969 ("d".into(), SkipReason::OrdinaryCapacity),
6970 ]);
6971 let wait = aggregate_dispatch_wait(4, &skips).unwrap();
6972 assert_eq!(wait.runnable, 4);
6973 assert_eq!(
6974 wait.reasons
6975 .iter()
6976 .map(|r| (r.reason.as_str(), r.count))
6977 .collect::<Vec<_>>(),
6978 [
6979 ("waiting_on_landing", 2),
6980 ("cooling_down", 1),
6981 ("ordinary_capacity", 1)
6982 ]
6983 );
6984 assert_eq!(aggregate_dispatch_wait(0, &DispatchSkips::new()), None);
6985 assert!(
6986 aggregate_dispatch_wait(2, &DispatchSkips::new())
6987 .unwrap()
6988 .reasons
6989 .is_empty()
6990 );
6991 }
6992
6993 #[test]
6994 fn dispatch_wait_tracks_interrupt_withholding_and_set_changes() {
6995 let before = vec!["a".into(), "b".into(), "c".into()];
6996 let allowed = vec![task_with_id("b")];
6997 let skips = interrupt_skips(&before, &allowed);
6998 assert_eq!(
6999 skips,
7000 DispatchSkips::from([
7001 ("a".into(), SkipReason::InterruptGate),
7002 ("c".into(), SkipReason::InterruptGate),
7003 ])
7004 );
7005 let mut previous = DispatchSkips::new();
7006 assert!(!changed_dispatch_skips(&mut previous, DispatchSkips::new()));
7007 assert!(changed_dispatch_skips(&mut previous, skips.clone()));
7008 assert!(!changed_dispatch_skips(&mut previous, skips));
7009 assert!(changed_dispatch_skips(
7010 &mut previous,
7011 DispatchSkips::from([("a".into(), SkipReason::CoolingDown),])
7012 ));
7013 assert!(changed_dispatch_skips(&mut previous, DispatchSkips::new()));
7014 }
7015
7016 #[test]
7017 fn dispatch_wait_status_reads_legacy_and_future_reason_keys() {
7018 let mut value = serde_json::to_value(Status::new()).unwrap();
7019 value.as_object_mut().unwrap().remove("dispatch_wait");
7020 assert!(
7021 serde_json::from_value::<Status>(value.clone())
7022 .unwrap()
7023 .dispatch_wait
7024 .is_none()
7025 );
7026 assert!(
7027 serde_json::from_value::<Reading>(value.clone())
7028 .unwrap()
7029 .dispatch_wait
7030 .is_none()
7031 );
7032 value["dispatch_wait"] = serde_json::json!({
7033 "runnable": 3, "reasons": [{"reason": "future_reason", "count": 3}]
7034 });
7035 let reading = serde_json::from_value::<Reading>(value).unwrap();
7036 assert_eq!(
7037 reading.dispatch_wait.unwrap().reasons[0].reason,
7038 "future_reason"
7039 );
7040 }
7041
7042 fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
7043 let job = crate::worker::Job {
7044 id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
7045 sequence: 1,
7046 kind: "task".into(),
7047 key: format!("task:{}", request.task),
7048 payload: serde_json::to_value(request).unwrap(),
7049 generation: "a".repeat(64),
7050 version: None,
7051 status: crate::worker::Status::Starting,
7052 result: None,
7053 pid: None,
7054 created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
7055 finished_at: None,
7056 };
7057 let dir = home.join("workers/jobs").join(&job.id);
7058 std::fs::create_dir_all(&dir).unwrap();
7059 std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
7060 job
7061 }
7062
7063 #[test]
7064 fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
7065 let home = tempfile::tempdir().unwrap();
7066 let request = TaskWorker {
7067 opts: Opts::default(),
7068 queue: home.path().join("queue"),
7069 task: "startup".into(),
7070 lane: PermitKind::Ordinary,
7071 standalone: false,
7072 };
7073 let job = starting_task_reservation(home.path(), &request);
7074 let error = task_worker_spawn_error(
7075 home.path(),
7076 &request,
7077 anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
7078 )
7079 .expect_err("our own reservation must not turn a failed spawn into a resync");
7080 let active = crate::worker::active(home.path()).unwrap();
7081 assert_eq!(active.len(), 1);
7082 assert_eq!(active[0].id, job.id);
7083 assert_eq!(active[0].status, crate::worker::Status::Starting);
7084 assert!(
7085 crate::worker::control(home.path(), &job.key)
7086 .unwrap()
7087 .is_none()
7088 );
7089 let notices = notices::Notices::at(home.path().join("notifications")).list();
7090 assert_eq!(notices.len(), 1);
7091 assert_eq!(notices[0].key, "loop:worker-startup");
7092 assert!(!notices[0].message.contains("private-error-detail"));
7093 assert!(notices[0].message.contains(&request.task));
7094 assert!(
7095 notices[0]
7096 .message
7097 .contains("could not be started or acknowledged")
7098 );
7099 assert!(notices[0].message.contains("worker.log"));
7100 assert_eq!(
7101 notices[0].link,
7102 Some(Link::Task {
7103 id: request.task.clone()
7104 })
7105 );
7106 assert!(format!("{error:#}").contains("private-error-detail"));
7107 }
7108
7109 #[test]
7110 fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
7111 let home = tempfile::tempdir().unwrap();
7112 let mut request = TaskWorker {
7113 opts: Opts::default(),
7114 queue: home.path().join("queue"),
7115 task: "handoff".into(),
7116 lane: PermitKind::Ordinary,
7117 standalone: true,
7118 };
7119 let job = starting_task_reservation(home.path(), &request);
7120 request.standalone = false;
7121 task_worker_spawn_error(
7122 home.path(),
7123 &request,
7124 anyhow::anyhow!("operation key is already reserved for a different request"),
7125 )
7126 .expect("a different standalone request is the handoff race, not our startup failure");
7127 let active = crate::worker::active(home.path()).unwrap();
7128 assert_eq!(active.len(), 1);
7129 assert_eq!(active[0].id, job.id);
7130 assert_eq!(active[0].payload, job.payload);
7131 assert!(
7132 notices::Notices::at(home.path().join("notifications"))
7133 .list()
7134 .is_empty()
7135 );
7136 }
7137
7138 #[test]
7139 fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
7140 let home = tempfile::tempdir().unwrap();
7141 let queue = Queue::at(home.path().join("queue"));
7142 let mut task = task();
7143 task.runs = vec!["previous".into()];
7144 queue.put(&mut task).unwrap();
7145 let request = TaskWorker {
7146 opts: Opts::default(),
7147 queue: home.path().join("queue"),
7148 task: task.id.clone(),
7149 lane: PermitKind::Ordinary,
7150 standalone: false,
7151 };
7152 let job = starting_task_reservation(home.path(), &request);
7153 let claims = current_work(home.path(), Timestamp::now());
7154 assert_eq!(claims.len(), 1);
7155 assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
7156 assert_eq!(claims[0].run, "previous");
7157 assert!(other_claims_run(&claims, "previous", None));
7158 assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
7161 assert!(is_working_on(home.path(), "previous", Timestamp::now()));
7162 }
7163
7164 #[test]
7165 fn admission_excludes_only_the_callers_exact_reservation() {
7166 let own = Current {
7167 worker: Some("own".into()),
7168 task: "same-task".into(),
7169 run: "previous".into(),
7170 };
7171 assert!(!other_claims_run(
7172 std::slice::from_ref(&own),
7173 "previous",
7174 Some("own")
7175 ));
7176 assert!(other_claims_run(
7177 std::slice::from_ref(&own),
7178 "previous",
7179 None
7180 ));
7181 for worker in [None, Some("other".into())] {
7182 let other = Current {
7183 worker,
7184 ..own.clone()
7185 };
7186 assert!(other_claims_run(
7187 &[own.clone(), other],
7188 "previous",
7189 Some("own")
7190 ));
7191 }
7192 let legacy: Current =
7193 serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
7194 assert!(other_claims_run(&[legacy], "previous", Some("own")));
7195 }
7196
7197 #[test]
7198 fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
7199 let mut task = task();
7200 let mut run = run_state(RunStatus::Reviewing);
7201 run.task_instruction = Some(task.instruction.clone());
7202 run.reviewed_commits = Some(vec!["committed-fix".into()]);
7203 let branch = "magi/test/B";
7204 run.candidates.push(crate::run::Candidate {
7205 branch: branch.into(),
7206 ..candidate('B', "preserved work", false, None)
7207 });
7208 task.runs = vec![run.id.clone()];
7209 let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
7210 assert_eq!(
7211 review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
7212 Starter::Resume(run.id.clone())
7213 );
7214 assert!(matches!(
7215 review_retry_starter(
7216 &task,
7217 Some(&run),
7218 Some("different"),
7219 true,
7220 unfinished.as_deref()
7221 ),
7222 Starter::Review(_)
7223 ));
7224 assert_eq!(
7225 review_retry_starter(
7226 &task,
7227 Some(&run),
7228 Some(branch),
7229 false,
7230 unfinished.as_deref()
7231 ),
7232 Starter::Start
7233 );
7234 task.instruction.push_str(" changed criteria");
7235 assert!(matches!(
7236 review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
7237 Starter::Review(_)
7238 ));
7239 assert!(matches!(
7240 review_retry_starter(&task, Some(&run), Some(branch), true, None),
7241 Starter::Review(_)
7242 ));
7243 }
7244
7245 #[test]
7246 fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
7247 let dir = tempfile::tempdir().unwrap();
7248 let queue = Queue::at(dir.path().join("queue"));
7249 let mut task = task();
7250 task.status = TaskStatus::Running;
7251 task.attempts = 1;
7252 queue.put(&mut task).unwrap();
7253 let live = std::collections::BTreeSet::from([task.id.clone()]);
7254 assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
7255 drop(queue.claim(&task.id).unwrap());
7256 let saved = queue.get(&task.id).unwrap();
7257 assert_eq!(saved.status, TaskStatus::Running);
7258 assert_eq!(saved.attempts, 1);
7259 assert!(saved.last_error.is_none());
7260 }
7261
7262 #[test]
7263 fn standalone_workers_do_not_consume_scheduler_lanes() {
7264 let request = |task: &str, lane, standalone| TaskWorker {
7265 opts: Opts::default(),
7266 queue: PathBuf::from("/queue"),
7267 task: task.to_owned(),
7268 lane,
7269 standalone,
7270 };
7271 let mut jobs = vec![
7272 request("ordinary", PermitKind::Ordinary, false),
7273 request("standalone-urgent", PermitKind::Urgent, true),
7274 request("standalone-ordinary", PermitKind::Ordinary, true),
7275 request("decision", PermitKind::None, false),
7276 ];
7277 assert_eq!(available_slots(&jobs, 2), (1, 1));
7278 jobs.push(request("urgent", PermitKind::Urgent, false));
7279 assert_eq!(available_slots(&jobs, 2), (1, 0));
7280 assert_eq!(available_slots(&jobs, 0), (0, 0));
7281 }
7282
7283 #[test]
7284 fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
7285 let now = Timestamp::now();
7286 let mut reading = Reading {
7287 pid: Some(std::process::id()),
7288 updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
7289 ..Reading::default()
7290 };
7291 assert!(!reading.running(now));
7292 assert!(legacy_scheduler_running(&reading, now, 0));
7293 reading.worker_protocol = Some(1);
7294 assert!(!legacy_scheduler_running(&reading, now, 0));
7295 }
7296
7297 #[test]
7298 fn selected_public_head_overrides_historical_resume_and_pin() {
7299 let mut t = task();
7300 let mut old = run_state(RunStatus::Blocked);
7301 let selection = crate::pr_recovery::Selection {
7302 url: "url".into(),
7303 branch: format!("magi/task-{}", t.id),
7304 head: "a".repeat(40),
7305 source_head: None,
7306 source_run: None,
7307 source_proof: None,
7308 disposition: Some(crate::pr_recovery::Disposition::Review),
7309 instruction: t.instruction.clone(),
7310 approved_at: Timestamp::now(),
7311 };
7312 t.resume_override = Some(crate::queue::OperatorResume {
7313 pinned_run: Some(old.id.clone()),
7314 question_id: "choice".into(),
7315 at: Timestamp::now(),
7316 conductor_rehold: None,
7317 forced: false,
7318 });
7319 assert_eq!(
7320 selected_starter(&selection, Some(&old), Some(&old.id)),
7321 Starter::Review(selection.branch.clone())
7322 );
7323 old.pr_recovery = Some(selection.clone());
7324 assert_eq!(
7325 selected_starter(&selection, Some(&old), Some(&old.id)),
7326 Starter::Review(selection.branch.clone())
7327 );
7328 old.reviewed_commits = Some(vec!["implementation".into()]);
7329 assert_eq!(
7330 selected_starter(&selection, Some(&old), Some(&old.id)),
7331 Starter::Resume(old.id.clone())
7332 );
7333 let mut changed = selection.clone();
7334 changed.head = "b".repeat(40);
7335 assert_eq!(
7336 selected_starter(&changed, Some(&old), Some(&old.id)),
7337 Starter::Review(changed.branch)
7338 );
7339 }
7340
7341 #[test]
7342 fn candidate_transplant_failure_is_one_actionable_hold() {
7343 let dir = tempfile::tempdir().unwrap();
7344 let q = Queue::at(dir.path().join("queue"));
7345 let mut t = task();
7346 let mut state = run_state(RunStatus::Blocked);
7347 state.event("prep", "cannot apply referenced commit: conflict");
7348 state.prep_failure = Some("conflict".into());
7349 t.start(state.id.clone());
7350 finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
7351 assert_eq!(t.attempts, 1);
7352 assert_eq!(t.status, TaskStatus::Held);
7353 assert!(t.operator_held());
7354 assert!(!t.status.runnable());
7355 assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
7356 let first = t.chat_notice_key().unwrap();
7357 t.chat_notices.push(first.clone());
7358 t.release_operator("test", None);
7359 state.id = "another-unprepared-run".into();
7360 t.start(state.id.clone());
7361 finish_attempt(
7362 3,
7363 &q,
7364 &mut t,
7365 &state,
7366 &[],
7367 Err(anyhow::anyhow!("still conflicts")),
7368 );
7369 assert_eq!(
7370 t.chat_notice_key().as_ref(),
7371 Some(&first),
7372 "no work happened"
7373 );
7374 t.release_operator("test", None);
7375 state.prep_failure = None;
7376 state.status = RunStatus::Failed;
7377 state.begin_pass();
7378 t.start(state.id.clone());
7379 finish_attempt(
7380 1,
7381 &q,
7382 &mut t,
7383 &state,
7384 &[],
7385 Err(anyhow::anyhow!("new gate failure")),
7386 );
7387 let failure = t.chat_notice_key().unwrap();
7388 assert_ne!(failure, first, "approved recovery reached a real failure");
7389 t.release_operator("test", None);
7390 state.begin_pass();
7391 t.start(state.id.clone());
7392 finish_attempt(
7393 1,
7394 &q,
7395 &mut t,
7396 &state,
7397 &[],
7398 Err(anyhow::anyhow!("new failure on resume")),
7399 );
7400 assert_ne!(
7401 t.chat_notice_key().as_ref(),
7402 Some(&failure),
7403 "a new settled pass"
7404 );
7405 }
7406
7407 #[test]
7408 fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
7409 for source in ["cli", "web"] {
7410 let mut t = task();
7411 let mut run = run_state(RunStatus::Blocked);
7412 run.instruction = "Run A original criteria".into();
7413 run.task_instruction = Some(run.instruction.clone());
7414 t.start(run.id.clone());
7415 t.release_operator("choice", Some("resume-question"));
7416 t.resume_override = Some(crate::queue::OperatorResume {
7417 question_id: "resume-question".into(),
7418 at: Timestamp::now(),
7419 conductor_rehold: None,
7420 forced: true,
7421 pinned_run: Some(run.id.clone()),
7422 });
7423 t.hold_machine(Some("not enough free space to start a run".into()));
7424 let mut unchanged = t.clone();
7425 unchanged
7426 .edit("title changed".into(), unchanged.instruction.clone())
7427 .unwrap();
7428 unchanged.release_operator(source, None);
7429 assert_eq!(
7430 unchanged
7431 .resume_override
7432 .as_ref()
7433 .unwrap()
7434 .pinned_run
7435 .as_deref(),
7436 Some(run.id.as_str())
7437 );
7438 assert!(!compatible_run_instruction(&run, &unchanged));
7439 assert!(may_resume_run(&run, &unchanged));
7440
7441 t.edit(
7442 "approved recovery".into(),
7443 "Reuse measured PR head B; fix Clippy; review".into(),
7444 )
7445 .unwrap();
7446 assert!(t.resume_override.is_none());
7447 t.release_operator(source, None);
7448 let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
7449 assert!(reloaded.resume_override.is_none());
7450 assert!(!may_resume_run(&run, &reloaded));
7451 let unfinished =
7452 unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
7453 .filter(|_| may_resume_run(&run, &reloaded));
7454 assert_eq!(
7455 choose_starter(None, false, unfinished.as_deref()),
7456 Starter::Start
7457 );
7458 assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
7459 assert_eq!(
7460 reloaded.resumption_history[0].question_id.as_deref(),
7461 Some("resume-question")
7462 );
7463
7464 unchanged.instruction = "Reuse measured PR head B".into();
7467 unchanged.hold_machine(Some("disk hold".into()));
7468 unchanged.release_operator(source, None);
7469 assert!(unchanged.resume_override.is_none());
7470 assert!(!may_resume_run(&run, &unchanged));
7471 }
7472 }
7473
7474 #[test]
7475 fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
7476 let mut t = task();
7477 let mut run = run_state(RunStatus::Blocked);
7478 t.review_of = Some("approved-head".into());
7479 t.instruction =
7480 "Review the branch `approved-head` (review-only: no implementation, no judging)."
7481 .into();
7482 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();
7483 run.reviewed_commits = Some(vec!["Commit log".into()]);
7484 t.start(run.id.clone());
7485 t.hold_machine(Some("interrupted review".into()));
7486 t.release_operator("cli", None);
7487 assert!(
7488 compatible_run_instruction(&run, &t),
7489 "legacy explicit review remains resumable"
7490 );
7491 let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
7492 .filter(|_| compatible_run_instruction(&run, &t));
7493 assert_eq!(
7494 choose_starter(None, false, unfinished.as_deref()),
7495 Starter::Resume(run.id.clone())
7496 );
7497 run.task_instruction = Some(t.instruction.clone());
7498 assert!(compatible_run_instruction(&run, &t));
7499 let reloaded: RunState =
7500 serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
7501 assert!(compatible_run_instruction(&reloaded, &t));
7502 t.edit(
7503 "new approved head".into(),
7504 "Reuse measured PR head B".into(),
7505 )
7506 .unwrap();
7507 assert!(!compatible_run_instruction(&run, &t));
7508
7509 t.review_of = None;
7511 t.instruction = "Fix Clippy on approved head".into();
7512 run.task_instruction = None;
7513 run.instruction = format!(
7514 "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
7515 t.instruction
7516 );
7517 assert!(compatible_run_instruction(&run, &t));
7518 t.instruction.push('\n');
7519 assert!(
7520 compatible_run_instruction(&run, &t),
7521 "legacy generated review trimmed the original criteria"
7522 );
7523 t.hold_for_handover(Some("approved-head".into()), "refused".into());
7524 assert_eq!(review_branch_for(&t, Some(&run)), Some("approved-head"));
7525 t.edit("new plan".into(), "Reuse measured PR head B".into())
7526 .unwrap();
7527 assert!(review_branch_for(&t, Some(&run)).is_none());
7528 assert!(!compatible_run_instruction(&run, &t));
7529 t.review_branch = Some("approved-head".into());
7530 t.review_instruction = None;
7531 assert!(
7532 review_branch_for(&t, Some(&run)).is_none(),
7533 "legacy retained candidate cannot replace a revised approved head"
7534 );
7535 }
7536
7537 #[test]
7538 fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
7539 let home = crate::run::test_home();
7540 crate::run::pin_test_home();
7541 let dir = tempfile::tempdir().unwrap();
7542 let queue = Queue::at(dir.path().join("queue"));
7543 for resume in [true, false] {
7544 let state = run_state(RunStatus::Blocked);
7545 let mut t = task();
7546 t.start(state.id.clone());
7547 let action = if resume {
7548 ask::ChoiceAction::Resume {
7549 run: state.id.clone(),
7550 }
7551 } else {
7552 ask::ChoiceAction::Requeue
7553 };
7554 let mut q = action_question(&state.id, action);
7555 q.status = ask::QuestionStatus::Open;
7556 q.answer = None;
7557 q.answered_at = None;
7558 t.fail("run stopped with a question", 3);
7559 hold_if_runnable(&queue, &mut t);
7560 assert!(t.operator_decided_at.is_none());
7561 assert!(t.operator_held());
7562 q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
7563 let expected = if resume {
7564 ActionDecision::Resume(state.id.clone())
7565 } else {
7566 ActionDecision::Requeue
7567 };
7568 assert_eq!(
7569 decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
7570 expected
7571 );
7572 t.hold_manual(Some("later explicit hold".into()));
7573 assert_eq!(
7574 decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
7575 ActionDecision::Stale
7576 );
7577 }
7578 }
7579
7580 #[test]
7581 fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
7582 let mut t = task();
7583 t.answers.push(crate::queue::AnsweredQuestion {
7584 question: "Inspect the remote?".into(),
7585 answer: "Inspect then wait".into(),
7586 });
7587 let old = instruction_for(&t);
7588 assert!(compatible_instruction(&old, &t));
7589 t.instruction = "Reuse approved PR head and review".into();
7590 t.release_operator("cli", None);
7591 assert!(!compatible_instruction(&old, &t));
7592 let approved = instruction_for(&t);
7593 assert!(approved.contains("waiting premises are superseded"));
7594 assert!(compatible_instruction(&approved, &t));
7595 assert_eq!(resumed_instruction(&approved, &t), approved);
7596 t.release_operator("web", None);
7597 assert!(compatible_instruction(&approved, &t));
7598 assert_eq!(t.resumption_history.len(), 1);
7599 t.start("run".into());
7600 assert!(instruction_for(&t).contains("Explicit operator resumption"));
7601 }
7602
7603 #[test]
7607 fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
7608 let mut state = RunState::new(
7609 PathBuf::from("/repo"),
7610 "main".into(),
7611 "base".into(),
7612 "task".into(),
7613 Config::default(),
7614 );
7615 state.status = RunStatus::Landing;
7616 state.parked = true;
7617 state.pr_pushed_head = Some("head".into());
7618 state.land_unrelated = Some(
7619 serde_json::from_value(serde_json::json!({
7620 "head": "head", "question": "ci-question",
7621 "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
7622 }))
7623 .unwrap(),
7624 );
7625 let mut t = task();
7626 t.start(state.id.clone());
7627 let verdict = Verdict {
7628 status: RunStatus::Landing,
7629 left_pr: true,
7630 quota_hit: false,
7631 parked: true,
7632 no_viable_candidates: false,
7633 };
7634 settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
7635 assert_eq!(t.attempts, 0);
7636 assert_eq!(t.status, TaskStatus::Held);
7637 assert!(!t.operator_held());
7638 assert!(
7639 t.hold_reason
7640 .as_deref()
7641 .unwrap()
7642 .starts_with("[ci-unrelated]")
7643 );
7644 t.attempts = 1;
7646 settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
7647 assert_eq!(t.attempts, 1);
7648 assert_eq!(t.passes.len(), 1);
7649 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
7650 state.pr_pushed_head = Some("new-head".into());
7651 state.parked = false;
7652 state.status = RunStatus::Blocked;
7653 let stale = Verdict {
7654 status: RunStatus::Blocked,
7655 parked: false,
7656 ..verdict
7657 };
7658 settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
7659 assert_eq!(t.attempts, 1);
7660 state.begin_pass();
7662 state.begin_pass();
7663 state.status = RunStatus::Landing;
7664 state.parked = true;
7665 state.pr_pushed_head = Some("head".into());
7666 settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
7667 assert_eq!(t.attempts, 0);
7668 assert_eq!(t.passes.len(), 2);
7669 }
7670
7671 #[test]
7672 fn orphan_recovery_does_not_refund_a_previous_pass_loss() {
7673 let mut state = run_state(RunStatus::Failed);
7674 state
7675 .quota
7676 .push(loss("advisor-1", "2026-10-22T14:38:00Z", None));
7677 state.begin_pass();
7678 let mut t = task();
7679 t.start(state.id.clone());
7680 reclaim(&mut t, Some(state), 2, "en");
7681 assert_eq!(t.attempts, 1);
7682 }
7683
7684 #[test]
7685 fn an_all_seats_unauthenticated_node_refunds_and_holds_without_retry() {
7686 let mut state = run_state(RunStatus::Blocked);
7687 let losses: Vec<_> = ["alpha", "beta"]
7688 .into_iter()
7689 .enumerate()
7690 .map(|(i, agent)| {
7691 QuotaLoss::from_report(
7692 format!("advisor-{i}"),
7693 "advise",
7694 Some(&crate::agent::Quota {
7695 cause: crate::agent::QuotaCause::Authentication,
7696 agent: agent.to_owned(),
7697 reset: None,
7698 }),
7699 )
7700 })
7701 .collect();
7702 crate::graph::block_machine_outage(&mut state, "advise", &losses);
7703 state.quota = losses;
7704 let mut t = task();
7705 t.start(state.id.clone());
7706 let verdict = Verdict {
7707 status: state.status,
7708 left_pr: false,
7709 quota_hit: true,
7710 parked: false,
7711 no_viable_candidates: true,
7712 };
7713 settle_and_diagnose(&mut t, verdict, "authentication unavailable", 2, &state);
7714 assert_eq!(t.attempts, 0);
7715 assert_eq!(t.status, TaskStatus::Held);
7716 assert!(!t.operator_held());
7717 let reason = t.hold_reason.as_deref().unwrap();
7718 assert!(reason.starts_with("[authentication]"));
7719 assert!(
7720 reason.contains("alpha")
7721 && reason.contains("beta")
7722 && reason.contains("re-authenticate")
7723 );
7724 assert!(cooldown_until(&state.quota, Timestamp::now()).is_none());
7725 let mut orphan = task();
7727 orphan.start(state.id.clone());
7728 reclaim(&mut orphan, Some(state), 2, "en");
7729 assert_eq!(orphan.attempts, 0);
7730 assert_eq!(orphan.status, TaskStatus::Held);
7731 }
7732
7733 #[test]
7734 fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
7735 let mut state = RunState::new(
7736 PathBuf::from("/repo"),
7737 "main".to_owned(),
7738 "abc1234".to_owned(),
7739 "task".to_owned(),
7740 Config::default(),
7741 );
7742 state.status = RunStatus::Blocked;
7743 state.resource_block = Some(crate::run::ResourceBlock {
7744 cause: crate::run::ResourceBlockCause::Other,
7745 node: "graft".to_owned(),
7746 kind: "shared build cache".to_owned(),
7747 detail: "timed out".to_owned(),
7748 at: jiff::Timestamp::now(),
7749 });
7750 let mut t = task();
7751 t.start("20260902-000000-aaaa".to_owned());
7752 assert_eq!(t.attempts, 1);
7753 let verdict = Verdict {
7754 status: RunStatus::Blocked,
7755 left_pr: false,
7756 quota_hit: false,
7757 parked: false,
7758 no_viable_candidates: false,
7759 };
7760 settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
7761 assert_eq!(t.status, TaskStatus::Held);
7762 assert_eq!(t.attempts, 0, "the attempt is refunded");
7763 assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
7764 assert!(
7765 !t.operator_held(),
7766 "a machine hold, released without a human"
7767 );
7768
7769 let mut selected = task();
7770 selected.start("20260902-000000-cccc".into());
7771 selected.replacement = Some(crate::merge_decision::Replacement {
7772 question: "fixture".into(),
7773 run: "earlier".into(),
7774 pr: "https://example.invalid/pr/1".into(),
7775 agent: "selected".into(),
7776 context: "fixture".into(),
7777 });
7778 state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
7779 settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
7780 assert_eq!(selected.attempts, 0);
7781 assert!(
7782 !selected.operator_held(),
7783 "a selected agent also retains a machine resource hold"
7784 );
7785 assert!(
7786 selected
7787 .hold_reason
7788 .as_deref()
7789 .unwrap()
7790 .starts_with("[resource] ")
7791 );
7792
7793 let mut p = task();
7795 p.start("20260902-000000-bbbb".to_owned());
7796 settle_and_diagnose(
7797 &mut p,
7798 Verdict {
7799 parked: true,
7800 ..verdict
7801 },
7802 "parked",
7803 2,
7804 &state,
7805 );
7806 assert_eq!(p.status, TaskStatus::Parked);
7807 assert_eq!(
7808 p.attempts, 0,
7809 "parking refunds once rather than also settling the resource hold"
7810 );
7811 }
7812
7813 #[test]
7814 fn record_failure_notice_links_the_task() {
7815 let dir = tempfile::tempdir().unwrap();
7816 std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
7819 let queue = Queue::at(dir.path().join("queue"));
7820 let mut t = interrupt_task("rec-fail-1");
7821 record(&queue, &mut t);
7822
7823 let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
7824 assert_eq!(found.len(), 1);
7825 assert_eq!(found[0].key, "loop:record");
7826 assert_eq!(
7827 found[0].link,
7828 Some(Link::Task {
7829 id: "rec-fail-1".to_owned()
7830 })
7831 );
7832 }
7833
7834 fn interrupt_task(id: &str) -> Task {
7837 let mut t = task();
7838 t.id = id.to_owned();
7839 t.interrupt = true;
7840 t
7841 }
7842
7843 fn task_with_id(id: &str) -> Task {
7845 let mut t = task();
7846 t.id = id.to_owned();
7847 t
7848 }
7849
7850 fn urgent_task(id: &str) -> Task {
7852 let mut t = task();
7853 t.id = id.to_owned();
7854 t.urgent = true;
7855 t
7856 }
7857
7858 #[test]
7859 fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
7860 let dir = tempfile::tempdir().unwrap();
7861 let queue = Queue::at(dir.path().join("queue"));
7862 let mut parked = task_with_id("parked");
7863 parked.start("run".into());
7864 parked.park("upgrade");
7865 parked.record_pass_at(
7866 "run",
7867 0,
7868 Some(Timestamp::now()),
7869 1,
7870 Some(crate::run::ParkCause::Upgrade {
7871 from: "old".into(),
7872 to: None,
7873 }),
7874 );
7875 let mut fresh = task_with_id("fresh");
7876 fresh.priority = 100;
7877 let mut urgent_task = urgent_task("urgent");
7878 for t in [&mut parked, &mut fresh, &mut urgent_task] {
7879 queue.put(t).unwrap();
7880 }
7881 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7882 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7883 let candidates = runnable(&queue);
7884 assert_eq!(candidates[0].id, parked.id);
7885 let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
7886 assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_err());
7887 assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_ok());
7888 drop(first);
7889 let claimed_elsewhere = queue.claim(&parked.id).unwrap();
7890 let next = runnable(&queue)
7891 .into_iter()
7892 .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent).ok())
7893 .unwrap();
7894 assert_eq!(next.task.id, fresh.id);
7895 assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
7896 drop(claimed_elsewhere);
7897 drop(next);
7898 assert!(matches!(
7899 claim_dispatch(&queue, &parked, true, &ordinary, &urgent),
7900 Err(SkipReason::CoolingDown)
7901 ));
7902 }
7903
7904 #[test]
7905 fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
7906 let dir = tempfile::tempdir().unwrap();
7907 let queue = Queue::at(dir.path().join("queue"));
7908 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7909 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7910 let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
7911 let mut first = task();
7912 queue.put(&mut first).unwrap();
7913 let stale_plain = queue.get(&first.id).unwrap();
7914 first.set_urgent(true).unwrap();
7915 queue.put(&mut first).unwrap();
7916 let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
7917 let mut second = urgent_task("second");
7918 queue.put(&mut second).unwrap();
7919 assert!(matches!(
7920 claim_dispatch(&queue, &second, false, &ordinary, &urgent),
7921 Err(SkipReason::UrgentCapacity)
7922 ));
7923 drop(queue.claim(&second.id).unwrap());
7924 assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
7925 drop(dispatched);
7926 let stale_urgent = queue.get(&first.id).unwrap();
7927 first.set_urgent(false).unwrap();
7928 queue.put(&mut first).unwrap();
7929 assert!(matches!(
7930 claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent),
7931 Err(SkipReason::OrdinaryCapacity)
7932 ));
7933 assert_eq!(urgent.available_permits(), 1);
7934 drop(queue.claim(&first.id).unwrap());
7935 drop(occupied);
7936 }
7937
7938 #[test]
7939 fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
7940 let dir = tempfile::tempdir().unwrap();
7941 let queue = Queue::at(dir.path().join("queue"));
7942 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7943 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7944 let mut t = task();
7945 queue.put(&mut t).unwrap();
7946 for enabled in [true, false] {
7947 let stale = queue.get(&t.id).unwrap();
7948 t.set_urgent(enabled).unwrap();
7949 queue.put(&mut t).unwrap();
7950 assert_ne!(stale.urgent, enabled);
7951 let DispatchClaim {
7952 task: fresh,
7953 claim,
7954 permit,
7955 } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
7956 assert_eq!(fresh.urgent, enabled);
7957 assert_eq!(ordinary.available_permits(), usize::from(enabled));
7958 assert_eq!(urgent.available_permits(), usize::from(!enabled));
7959 assert!(queue.claim(&t.id).is_err());
7960 assert_eq!(fresh.attempts, stale.attempts);
7961 drop((claim, permit));
7962 assert_eq!(ordinary.available_permits(), 1);
7963 assert_eq!(urgent.available_permits(), 1);
7964 }
7965 t.set_urgent(true).unwrap();
7966 queue.put(&mut t).unwrap();
7967 let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
7968 assert!(matches!(
7969 claim_dispatch(&queue, &t, false, &ordinary, &urgent),
7970 Err(SkipReason::UrgentCapacity)
7971 ));
7972 assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
7973 drop(queue.claim(&t.id).unwrap());
7974 assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
7975 drop(occupied);
7976 assert!(matches!(
7977 claim_dispatch(&queue, &t, true, &ordinary, &urgent),
7978 Err(SkipReason::CoolingDown)
7979 ));
7980 drop(queue.claim(&t.id).unwrap());
7981 let held = queue.claim(&t.id).unwrap();
7982 assert!(matches!(
7983 claim_dispatch(&queue, &t, false, &ordinary, &urgent),
7984 Err(SkipReason::ClaimUnavailable)
7985 ));
7986 drop(held);
7987 t.status = TaskStatus::Held;
7988 queue.put(&mut t).unwrap();
7989 assert!(matches!(
7990 claim_dispatch(&queue, &t, false, &ordinary, &urgent),
7991 Err(SkipReason::NoLongerRunnable)
7992 ));
7993 drop(queue.claim(&t.id).unwrap());
7994 std::fs::remove_file(queue.path_of(&t.id)).unwrap();
7995 assert!(matches!(
7996 claim_dispatch(&queue, &t, false, &ordinary, &urgent),
7997 Err(SkipReason::RereadFailed)
7998 ));
7999 drop(queue.claim(&t.id).unwrap());
8000 assert_eq!(urgent.available_permits(), 1);
8001 }
8002
8003 #[test]
8008 fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
8009 assert_eq!(permit_kind(true, false), PermitKind::None);
8010 assert_eq!(permit_kind(true, true), PermitKind::None);
8011 }
8012
8013 #[test]
8018 fn permit_kind_separates_urgent_from_ordinary() {
8019 assert_eq!(permit_kind(false, true), PermitKind::Urgent);
8020 assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
8021 }
8022
8023 #[test]
8030 fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
8031 let cfg = Config::default();
8032 let repo = Path::new("/any/repo/path");
8033
8034 let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(1024))
8035 .expect("must hold below the threshold");
8036 assert!(reason.contains("1024"), "{reason}");
8037 assert!(
8038 reason.contains(&cfg.disk.min_free_bytes.to_string()),
8039 "{reason}"
8040 );
8041
8042 assert_eq!(
8043 disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(cfg.disk.min_free_bytes)),
8044 None,
8045 "exactly at the floor is open"
8046 );
8047 assert_eq!(
8048 disk_gate_with(
8049 repo,
8050 &cfg,
8051 PathBuf::new,
8052 |_| Ok(cfg.disk.min_free_bytes + 1)
8053 ),
8054 None,
8055 "comfortably above the floor is open"
8056 );
8057 }
8058
8059 #[test]
8060 fn disk_gate_with_checks_cache_and_worktree_volumes_and_measurement_errors() {
8061 let dir = tempfile::tempdir().unwrap();
8062 let repo = dir.path().join("repo");
8063 let cache = dir.path().join("cache");
8064 let worktrees = dir.path().join("worktrees");
8065 for path in [&repo, &cache, &worktrees] {
8066 std::fs::create_dir(path).unwrap();
8067 }
8068 let mut cfg = Config::default();
8069 cfg.graph.worktree_root = Some(worktrees.clone());
8070 cfg.verify.gate = vec![format!(
8071 "CARGO_TARGET_DIR='{}' cargo build",
8072 cache.display()
8073 )];
8074 for blocked in [&cache, &worktrees] {
8075 for unmeasured in [false, true] {
8076 assert!(
8077 disk_gate_with(&repo, &cfg, PathBuf::new, |path| {
8078 if path == blocked {
8079 if unmeasured {
8080 Err(anyhow::anyhow!("measurement failed"))
8081 } else {
8082 Ok(0)
8083 }
8084 } else {
8085 Ok(u64::MAX)
8086 }
8087 })
8088 .is_some(),
8089 "a blocked secondary output volume must close admission"
8090 );
8091 }
8092 }
8093 assert!(disk_gate_with(&repo, &cfg, PathBuf::new, |_| Ok(u64::MAX)).is_none());
8094 }
8095
8096 #[test]
8097 fn isolated_admission_measures_the_run_home_instead_of_the_shared_cache() {
8098 let dir = tempfile::tempdir().unwrap();
8099 let repo = dir.path().join("repo");
8100 let cache = dir.path().join("cache");
8101 let home_parent = dir.path().join("run-volume");
8102 let home = home_parent.join("new-home");
8103 for path in [&repo, &cache, &home_parent] {
8104 std::fs::create_dir(path).unwrap();
8105 }
8106 let mut cfg = Config::default();
8107 cfg.graph.worktree_root = Some(repo.clone());
8108 cfg.verify.gate = vec![format!(
8109 "CARGO_TARGET_DIR='{}' cargo build",
8110 cache.display()
8111 )];
8112 cfg.verify.build_cache = BuildCache::Isolated;
8113 let denied = |blocked: &Path| {
8114 disk_gate_with(
8115 &repo,
8116 &cfg,
8117 || home.clone(),
8118 |path| Ok(if path == blocked { 0 } else { u64::MAX }),
8119 )
8120 .is_some()
8121 };
8122 assert!(!denied(&cache));
8123 assert!(denied(&home_parent));
8124 }
8125
8126 #[test]
8127 fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
8128 let mut cfg = Config::default();
8129 cfg.disk.min_free_bytes = 0;
8130 let repo = Path::new("/any/repo/path");
8131 assert_eq!(
8132 disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(0)),
8133 None,
8134 "a zero floor never measures at all"
8135 );
8136 }
8137
8138 #[test]
8139 fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
8140 let cfg = Config::default();
8141 let repo = Path::new("/any/repo/path");
8142 let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| {
8143 Err(anyhow::anyhow!("no df on this box"))
8144 })
8145 .expect("a measurement failure must close the gate, not open it");
8146 assert!(reason.contains("could not measure"), "{reason}");
8147 }
8148
8149 #[test]
8150 fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
8151 let ordinary = task();
8152 let next = advance_interrupt(
8153 Interrupt::Idle,
8154 std::slice::from_ref(&ordinary.id),
8155 std::slice::from_ref(&ordinary),
8156 );
8157 assert_eq!(next, Interrupt::Idle);
8158 }
8159
8160 #[test]
8161 fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
8162 let marked = interrupt_task("marked");
8165 let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
8166 assert_eq!(next, Interrupt::Idle);
8167 }
8168
8169 #[test]
8170 fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
8171 let marked = interrupt_task("marked");
8172 let next = advance_interrupt(
8173 Interrupt::Idle,
8174 &["running".to_owned()],
8175 std::slice::from_ref(&marked),
8176 );
8177 assert_eq!(
8178 next,
8179 Interrupt::Parking {
8180 parked: vec!["running".to_owned()],
8181 interrupt_task: "marked".to_owned(),
8182 }
8183 );
8184 }
8185
8186 #[test]
8195 fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
8196 let marked = interrupt_task("marked");
8197
8198 let two = advance_interrupt(
8199 Interrupt::Idle,
8200 &["a".to_owned(), "b".to_owned()],
8201 std::slice::from_ref(&marked),
8202 );
8203 assert_eq!(two, Interrupt::Idle);
8204
8205 let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
8206 assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
8207 }
8208
8209 #[test]
8210 fn parking_holds_until_every_parked_id_has_actually_left_flight() {
8211 let state = Interrupt::Parking {
8212 parked: vec!["running".to_owned()],
8213 interrupt_task: "marked".to_owned(),
8214 };
8215 let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
8217 assert_eq!(still_going, state);
8218
8219 let stopped_but_not_yet_dispatched =
8223 advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
8224 assert_eq!(stopped_but_not_yet_dispatched, state);
8225
8226 let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
8228 assert_eq!(
8229 dispatched,
8230 Interrupt::Running {
8231 parked: vec!["running".to_owned()],
8232 interrupt_task: "marked".to_owned(),
8233 }
8234 );
8235 }
8236
8237 #[test]
8238 fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
8239 let state = Interrupt::Running {
8240 parked: vec!["running".to_owned()],
8241 interrupt_task: "marked".to_owned(),
8242 };
8243 let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
8244 assert_eq!(still_running, state);
8245
8246 let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
8253 assert_eq!(
8254 ended,
8255 Interrupt::Resuming {
8256 parked: vec!["running".to_owned()]
8257 }
8258 );
8259 }
8260
8261 #[test]
8262 fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
8263 let state = Interrupt::Resuming {
8264 parked: vec!["running".to_owned()],
8265 };
8266 let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
8267 assert_eq!(still_waiting, state);
8268
8269 let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
8270 assert_eq!(dispatched, Interrupt::Idle);
8271 }
8272
8273 #[test]
8279 fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
8280 {
8281 let state = Interrupt::Parking {
8282 parked: vec!["running".to_owned()],
8283 interrupt_task: "marked".to_owned(),
8284 };
8285 let next = advance_interrupt(state, &[], &[]);
8288 assert_eq!(
8289 next,
8290 Interrupt::Resuming {
8291 parked: vec!["running".to_owned()]
8292 },
8293 "abandoning the interrupt must not abandon the resume it owes"
8294 );
8295 }
8296
8297 #[test]
8300 fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
8301 let state = Interrupt::Resuming {
8302 parked: vec!["running".to_owned()],
8303 };
8304 let next = advance_interrupt(state, &[], &[]);
8305 assert_eq!(
8306 next,
8307 Interrupt::Idle,
8308 "nothing is left to wait for; the loop must not stay wedged"
8309 );
8310 }
8311
8312 #[test]
8313 fn disabled_by_config_the_sequence_can_never_leave_idle() {
8314 let marked = interrupt_task("marked");
8315 let next = advance_interrupt_tick(
8316 false,
8317 Interrupt::Idle,
8318 &["running".to_owned()],
8319 std::slice::from_ref(&marked),
8320 );
8321 assert_eq!(
8322 next,
8323 Interrupt::Idle,
8324 "an unmarked, unconfigured daemon must behave exactly as before"
8325 );
8326 }
8327
8328 #[test]
8329 fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
8330 let state = Interrupt::Parking {
8331 parked: vec!["running".to_owned()],
8332 interrupt_task: "marked".to_owned(),
8333 };
8334 let candidates = vec![interrupt_task("marked"), task()];
8335 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
8336 assert!(
8337 allowed.is_empty(),
8338 "nothing may dispatch - not even the interrupt task itself - \
8339 until the parked run has actually stopped"
8340 );
8341 }
8342
8343 #[test]
8357 fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
8358 for state in [
8359 Interrupt::Parking {
8360 parked: vec!["running".to_owned()],
8361 interrupt_task: "marked".to_owned(),
8362 },
8363 Interrupt::Running {
8364 parked: vec!["running".to_owned()],
8365 interrupt_task: "marked".to_owned(),
8366 },
8367 Interrupt::Resuming {
8368 parked: vec!["running".to_owned()],
8369 },
8370 ] {
8371 let candidates = vec![
8372 interrupt_task("marked"),
8373 urgent_task("hot"),
8374 task_with_id("ordinary"),
8375 ];
8376 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
8377 assert!(
8378 !allowed.iter().any(|t| t.id == "hot"),
8379 "an urgent candidate must wait out the same gate as anything \
8380 else while the run it would run alongside has not actually \
8381 left flight, for state {state:?}: {allowed:?}"
8382 );
8383 }
8384 }
8385
8386 #[test]
8392 fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
8393 let state = Interrupt::Resuming {
8394 parked: vec!["hot".to_owned()],
8395 };
8396 let candidates = vec![urgent_task("hot"), task()];
8397 let allowed = interrupt_gate(&state, &[], candidates);
8398 assert_eq!(
8399 allowed.iter().filter(|t| t.id == "hot").count(),
8400 1,
8401 "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
8402 );
8403 }
8404
8405 #[test]
8406 fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
8407 let state = Interrupt::Parking {
8408 parked: vec!["running".to_owned()],
8409 interrupt_task: "marked".to_owned(),
8410 };
8411 let other = task();
8412 let candidates = vec![interrupt_task("marked"), other.clone()];
8413 let allowed = interrupt_gate(&state, &[], candidates);
8414 assert_eq!(allowed.len(), 1);
8415 assert_eq!(allowed[0].id, "marked");
8416 }
8417
8418 #[test]
8419 fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
8420 let state = Interrupt::Running {
8421 parked: vec!["running".to_owned()],
8422 interrupt_task: "marked".to_owned(),
8423 };
8424 let candidates = vec![task(), task()];
8425 let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
8426 assert!(allowed.is_empty());
8427 }
8428
8429 #[test]
8436 fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
8437 let state = Interrupt::Resuming {
8438 parked: vec!["a".to_owned(), "c".to_owned()],
8439 };
8440 let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
8441 let allowed = interrupt_gate(&state, &[], candidates);
8442 assert_eq!(
8443 allowed.len(),
8444 1,
8445 "at most one candidate may be offered while resuming: {allowed:?}"
8446 );
8447 assert_eq!(allowed[0].id, "a");
8448 }
8449
8450 #[test]
8451 fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
8452 let state = Interrupt::Resuming {
8453 parked: vec!["a".to_owned()],
8454 };
8455 let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
8456 assert!(allowed.is_empty());
8457 }
8458
8459 #[test]
8465 fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
8466 let running = task(); let marked = interrupt_task("marked");
8468
8469 let mut state = Interrupt::Idle;
8470 let in_flight = vec![running.id.clone()];
8472 state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
8473 let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
8474 assert!(gated.is_empty(), "still waiting on `running` to park");
8475
8476 state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
8478 let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
8479 assert_eq!(
8480 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8481 vec!["marked"],
8482 "only the interrupt task may be offered to the dispatcher now"
8483 );
8484
8485 state = advance_interrupt_tick(
8487 true,
8488 state,
8489 &["marked".to_owned()],
8490 std::slice::from_ref(&running),
8491 );
8492 let gated = interrupt_gate(
8493 &state,
8494 &["marked".to_owned()],
8495 vec![marked.clone(), running.clone()],
8496 );
8497 assert!(
8498 gated.is_empty(),
8499 "the parked run must not be offered back while the interrupt \
8500 task is still running"
8501 );
8502
8503 let other = task_with_id("other");
8507 state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
8508 assert_eq!(
8509 state,
8510 Interrupt::Resuming {
8511 parked: vec![running.id.clone()]
8512 }
8513 );
8514 let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
8515 assert_eq!(
8516 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8517 vec![running.id.as_str()],
8518 "exactly the parked run resumes - not the unrelated task, even \
8519 though it was offered first"
8520 );
8521
8522 state = advance_interrupt_tick(
8526 true,
8527 state,
8528 std::slice::from_ref(&running.id),
8529 std::slice::from_ref(&other),
8530 );
8531 assert_eq!(state, Interrupt::Idle);
8532 let gated = interrupt_gate(
8533 &state,
8534 std::slice::from_ref(&running.id),
8535 vec![other.clone()],
8536 );
8537 assert_eq!(
8538 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8539 vec![other.id.as_str()],
8540 "ordinary dispatch is unrestricted again"
8541 );
8542 }
8543
8544 #[test]
8545 fn every_run_status_settles_the_task_it_came_from() {
8546 let table = [
8548 (RunStatus::Merged, TaskStatus::Done, 1),
8549 (RunStatus::Ready, TaskStatus::Done, 1),
8550 (RunStatus::Stalled, TaskStatus::Failed, 0),
8551 (RunStatus::Blocked, TaskStatus::Failed, 1),
8552 (RunStatus::Failed, TaskStatus::Failed, 1),
8553 (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
8554 (RunStatus::Prep, TaskStatus::Failed, 1),
8555 (RunStatus::Implementing, TaskStatus::Failed, 1),
8556 (RunStatus::Judging, TaskStatus::Failed, 1),
8557 (RunStatus::Deliberating, TaskStatus::Failed, 1),
8558 (RunStatus::Voting, TaskStatus::Failed, 1),
8559 (RunStatus::Reviewing, TaskStatus::Failed, 1),
8560 (RunStatus::Gating, TaskStatus::Failed, 1),
8561 ];
8562 for (run, want, attempts) in table {
8563 let mut t = task();
8564 t.start("20260902-000000-aaaa".to_owned());
8565 settle(
8566 &mut t,
8567 Verdict {
8568 status: run,
8569 left_pr: false,
8570 parked: false,
8571 quota_hit: matches!(run, RunStatus::Stalled),
8572 no_viable_candidates: false,
8573 },
8574 "why",
8575 2,
8576 );
8577 assert_eq!(t.status, want, "task status after {}", label(run));
8578 assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
8579 }
8580 }
8581
8582 #[test]
8583 fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
8584 let mut stalled = task();
8585 stalled.start("20260902-000000-aaaa".to_owned());
8586 settle(
8587 &mut stalled,
8588 Verdict {
8589 status: RunStatus::Stalled,
8590 left_pr: false,
8591 parked: false,
8592 quota_hit: true,
8593 no_viable_candidates: false,
8594 },
8595 "quota",
8596 1,
8597 );
8598 assert_eq!(stalled.attempts, 0);
8599 assert!(
8600 stalled.status.runnable(),
8601 "a machine problem must leave the task in line"
8602 );
8603
8604 let mut blocked = task();
8605 blocked.start("20260902-000000-aaaa".to_owned());
8606 settle(
8607 &mut blocked,
8608 Verdict {
8609 status: RunStatus::Blocked,
8610 left_pr: false,
8611 parked: false,
8612 quota_hit: false,
8613 no_viable_candidates: false,
8614 },
8615 "findings open",
8616 1,
8617 );
8618 assert_eq!(blocked.attempts, 1);
8619 assert_eq!(
8620 blocked.status,
8621 TaskStatus::Held,
8622 "the last attempt hands the task to a human"
8623 );
8624 }
8625
8626 #[test]
8627 fn a_run_that_opened_a_pull_request_is_never_re_competed() {
8628 let mut delivered = task();
8631 delivered.start("20260903-080619-01c2".to_owned());
8632 settle(
8633 &mut delivered,
8634 Verdict {
8635 status: RunStatus::Blocked,
8636 left_pr: true,
8637 parked: false,
8638 quota_hit: false,
8639 no_viable_candidates: false,
8640 },
8641 "no check status",
8642 4,
8643 );
8644 assert_eq!(
8645 delivered.status,
8646 TaskStatus::Held,
8647 "a pull request waiting on CI or a person is not a retryable failure"
8648 );
8649 assert!(
8650 !delivered.status.runnable(),
8651 "the loop must not pick this task up again"
8652 );
8653 assert_eq!(
8654 delivered.last_error.as_deref(),
8655 Some("no check status"),
8656 "the operator needs to be told what the gate was waiting for"
8657 );
8658
8659 let mut empty_handed = task();
8662 empty_handed.start("20260903-080619-01c2".to_owned());
8663 settle(
8664 &mut empty_handed,
8665 Verdict {
8666 status: RunStatus::Blocked,
8667 left_pr: false,
8668 parked: false,
8669 quota_hit: false,
8670 no_viable_candidates: false,
8671 },
8672 "findings open",
8673 4,
8674 );
8675 assert_eq!(empty_handed.status, TaskStatus::Failed);
8676 assert!(empty_handed.status.runnable());
8677 }
8678
8679 #[test]
8680 fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
8681 let mut noop = task();
8687 noop.start("20260912-131304-391f".to_owned());
8688 settle(
8689 &mut noop,
8690 Verdict {
8691 status: RunStatus::VerifiedNoop,
8692 left_pr: false,
8693 parked: false,
8694 quota_hit: false,
8695 no_viable_candidates: true,
8696 },
8697 "candidate A: already fixed by b32cfc4, on main",
8698 4,
8699 );
8700 assert_eq!(
8701 noop.status,
8702 TaskStatus::Held,
8703 "an unverified claim is a request for a human, not a failure"
8704 );
8705 assert!(
8706 !noop.status.runnable(),
8707 "the loop must not requeue this on the same unverified claim"
8708 );
8709 assert_eq!(noop.attempts, 1);
8714 }
8715
8716 #[test]
8717 fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
8718 let mut parked = task();
8723 parked.start("20260903-183634-2d98".to_owned());
8724 settle(
8725 &mut parked,
8726 Verdict {
8727 status: RunStatus::Implementing,
8728 left_pr: false,
8729 quota_hit: false,
8730 parked: true,
8731 no_viable_candidates: false,
8732 },
8733 "parked after `implementing`",
8734 2,
8735 );
8736 assert_eq!(parked.attempts, 0, "a park is refunded");
8737 assert!(
8738 parked.status.runnable(),
8739 "and the task stays in line so the next loop resumes its run"
8740 );
8741 assert_eq!(parked.status, TaskStatus::Parked);
8742 assert_eq!(
8743 parked.park_reason.as_deref(),
8744 Some("parked after `implementing`"),
8745 "the card says where it stopped"
8746 );
8747 assert_eq!(parked.last_error, None, "nothing failed");
8748
8749 let mut broken = task();
8753 broken.start("20260903-183634-2d98".to_owned());
8754 settle(
8755 &mut broken,
8756 Verdict {
8757 status: RunStatus::Implementing,
8758 left_pr: false,
8759 quota_hit: false,
8760 parked: false,
8761 no_viable_candidates: false,
8762 },
8763 "returned mid-flight",
8764 2,
8765 );
8766 assert_eq!(broken.attempts, 1);
8767 }
8768
8769 #[test]
8770 fn only_a_rate_limit_buys_the_task_its_attempt_back() {
8771 let mut flaky = task();
8776 flaky.start("20260903-123023-e633".to_owned());
8777 settle(
8778 &mut flaky,
8779 Verdict {
8780 status: RunStatus::Stalled,
8781 left_pr: false,
8782 parked: false,
8783 quota_hit: false,
8784 no_viable_candidates: false,
8785 },
8786 "verdict rests on 1 of 3 judges",
8787 2,
8788 );
8789 assert_eq!(
8790 flaky.attempts, 1,
8791 "flakiness spends an attempt, so `max_attempts` still bounds it"
8792 );
8793 assert!(flaky.status.runnable(), "and it is still worth retrying");
8794
8795 let mut limited = task();
8797 limited.start("20260903-123023-e633".to_owned());
8798 settle(
8799 &mut limited,
8800 Verdict {
8801 status: RunStatus::Stalled,
8802 left_pr: false,
8803 parked: false,
8804 quota_hit: true,
8805 no_viable_candidates: false,
8806 },
8807 "judge-2, judge-3 out of quota",
8808 2,
8809 );
8810 assert_eq!(limited.attempts, 0, "a quota window is refunded");
8811 assert!(limited.status.runnable());
8812
8813 let mut worn = task();
8816 for _ in 0..2 {
8817 worn.release();
8818 }
8819 worn.start("20260903-123023-e633".to_owned());
8820 worn.attempts = 2;
8821 settle(
8822 &mut worn,
8823 Verdict {
8824 status: RunStatus::Stalled,
8825 left_pr: false,
8826 parked: false,
8827 quota_hit: false,
8828 no_viable_candidates: false,
8829 },
8830 "no quorum again",
8831 2,
8832 );
8833 assert_eq!(worn.status, TaskStatus::Held);
8834 assert!(!worn.status.runnable());
8835 }
8836
8837 #[test]
8838 fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
8839 let mut wiped_out = task();
8846 wiped_out.start("20260907-025000-a1b2".to_owned());
8847 settle(
8848 &mut wiped_out,
8849 Verdict {
8850 status: RunStatus::Failed,
8851 left_pr: false,
8852 parked: false,
8853 quota_hit: true,
8854 no_viable_candidates: true,
8855 },
8856 "no candidate produced a change; nothing to judge",
8857 2,
8858 );
8859 assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
8860 assert!(
8861 wiped_out.status.runnable(),
8862 "a machine problem must leave the task in line"
8863 );
8864
8865 let mut partial_progress = task();
8871 partial_progress.start("20260907-025500-c3d4".to_owned());
8872 settle(
8873 &mut partial_progress,
8874 Verdict {
8875 status: RunStatus::Failed,
8876 left_pr: false,
8877 parked: false,
8878 quota_hit: true,
8879 no_viable_candidates: false,
8880 },
8881 "gate failed on the winning candidate",
8882 2,
8883 );
8884 assert_eq!(
8885 partial_progress.attempts, 1,
8886 "a candidate that actually produced a change spends the attempt \
8887 even though some other seat hit its quota"
8888 );
8889 assert!(partial_progress.status.runnable());
8890 }
8891
8892 #[test]
8893 fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
8894 let mut t = task();
8900 t.start("20260907-025000-a1b2".to_owned());
8901 let mut state = run_state(RunStatus::Failed);
8902 state.quota.push(QuotaLoss {
8903 cause: crate::agent::QuotaCause::UsageLimit,
8904 agent: String::new(),
8905 seat: "cand-a".to_owned(),
8906 node: "implement".to_owned(),
8907 at: Timestamp::now(),
8908 reset: None,
8909 });
8910 assert!(
8911 state.viable().is_empty(),
8912 "no candidate was added, so nothing is viable"
8913 );
8914 reclaim(&mut t, Some(state), 2, "en");
8915 assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
8916 assert!(t.status.runnable());
8917 }
8918
8919 #[test]
8920 fn a_held_task_is_never_offered_to_the_loop() {
8921 let dir = tempfile::tempdir().unwrap();
8922 let queue = Queue::at(dir.path().to_path_buf());
8923 for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
8924 let mut t = task();
8925 t.id = format!("2026090{n}-000000-000{n}");
8926 t.priority = priority;
8927 queue.put(&mut t).unwrap();
8928 }
8929 let mut held = task();
8930 held.id = "20260909-000000-9999".to_owned();
8931 held.priority = 99;
8932 held.hold_machine(None);
8933 queue.put(&mut held).unwrap();
8934
8935 let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
8936 assert_eq!(order.len(), 3);
8937 assert!(!order.contains(&held.id));
8938 assert_eq!(
8939 order.first().cloned(),
8940 queue.next_runnable().map(|t| t.id),
8941 "the loop's first candidate is exactly what the queue offers"
8942 );
8943 assert_eq!(
8944 order,
8945 vec![
8946 "20260902-000000-0002".to_owned(),
8947 "20260903-000000-0003".to_owned(),
8948 "20260901-000000-0001".to_owned(),
8949 ],
8950 "priority first, then oldest, so nothing starves"
8951 );
8952 }
8953
8954 #[test]
8955 fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
8956 let dir = tempfile::tempdir().unwrap();
8957 let queue = Queue::at(dir.path().to_path_buf());
8958 let mut old = task();
8959 old.id = "20260101-000000-old0".to_owned();
8960 queue.put(&mut old).unwrap();
8961 let mut fresh = task();
8962 fresh.id = "20260101-000000-new0".to_owned();
8963 queue.put(&mut fresh).unwrap();
8964
8965 std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
8969 std::thread::sleep(Duration::from_millis(60));
8970 let live = queue.claim(&fresh.id).unwrap();
8971
8972 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8973 assert_eq!(swept, vec![old.id.clone()]);
8974 assert!(
8975 queue.claim(&old.id).is_ok(),
8976 "an unparseable lock older than the threshold is swept"
8977 );
8978 assert!(
8979 queue.claim(&fresh.id).is_err(),
8980 "a live pid protects its lock regardless of age"
8981 );
8982 drop(live);
8983 }
8984
8985 #[test]
8986 fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
8987 let dir = tempfile::tempdir().unwrap();
8990 let queue = Queue::at(dir.path().to_path_buf());
8991 let mut t = task();
8992 t.id = "20260101-000000-live".to_owned();
8993 queue.put(&mut t).unwrap();
8994
8995 let claim = queue.claim(&t.id).unwrap();
8996 std::thread::sleep(Duration::from_millis(60));
8997
8998 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8999 assert!(
9000 swept.is_empty(),
9001 "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
9002 );
9003 assert!(
9004 queue.claim(&t.id).is_err(),
9005 "the lock still protects its task"
9006 );
9007 drop(claim);
9008 }
9009
9010 fn injected_dead_pid() -> u32 {
9013 std::process::id().checked_add(1).unwrap_or(1)
9014 }
9015
9016 #[test]
9017 fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
9018 let dir = tempfile::tempdir().unwrap();
9019 let queue = Queue::at(dir.path().to_path_buf());
9020 let mut t = task();
9021 t.id = "20260101-000000-dead".to_owned();
9022 queue.put(&mut t).unwrap();
9023 let dead_pid = injected_dead_pid();
9024
9025 std::fs::write(
9030 dir.path().join(format!("{}.lock", t.id)),
9031 dead_pid.to_string(),
9032 )
9033 .unwrap();
9034
9035 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
9036 pid != dead_pid
9037 });
9038 assert_eq!(
9039 swept,
9040 vec![t.id.clone()],
9041 "a dead owner is reclaimed immediately, not after STALE_CLAIM"
9042 );
9043 assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
9044 }
9045
9046 #[test]
9047 fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
9048 let dir = tempfile::tempdir().unwrap();
9049 let queue = Queue::at(dir.path().to_path_buf());
9050 let mut t = task();
9051 t.id = "20260101-000000-late".to_owned();
9052 queue.put(&mut t).unwrap();
9053 let dead_pid = injected_dead_pid();
9054
9055 assert!(
9058 sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
9059 "nothing has claimed the task yet"
9060 );
9061
9062 std::fs::write(
9065 dir.path().join(format!("{}.lock", t.id)),
9066 dead_pid.to_string(),
9067 )
9068 .unwrap();
9069
9070 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
9074 pid != dead_pid
9075 });
9076 assert_eq!(swept, vec![t.id.clone()]);
9077 }
9078
9079 #[test]
9080 fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
9081 crate::run::pin_test_home();
9086 let dir = tempfile::tempdir().unwrap();
9087 let queue = Queue::at(dir.path().to_path_buf());
9088 let mut t = task();
9089 t.id = "20260101-000000-crsh".to_owned();
9090 t.status = TaskStatus::Running;
9091 t.attempts = 1;
9092 t.runs.push("20260904-000000-4043".to_owned());
9096 queue.put(&mut t).unwrap();
9097 let dead_pid = injected_dead_pid();
9098
9099 std::fs::write(
9102 dir.path().join(format!("{}.lock", t.id)),
9103 dead_pid.to_string(),
9104 )
9105 .unwrap();
9106
9107 assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
9113 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
9114
9115 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
9116 pid != dead_pid
9117 });
9118 assert_eq!(swept, vec![t.id.clone()]);
9119
9120 let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
9121 assert_eq!(reclaimed, vec![t.id.clone()]);
9122 let after = queue.get(&t.id).unwrap();
9123 assert_eq!(
9124 after.status,
9125 TaskStatus::Held,
9126 "no run.json to recover from, so a human is asked"
9127 );
9128 assert_eq!(
9129 after.runs,
9130 vec!["20260904-000000-4043".to_owned()],
9131 "the crashed run's id is kept as evidence, not discarded"
9132 );
9133 }
9134
9135 #[test]
9136 fn a_lock_is_kept_when_the_process_query_is_unavailable() {
9137 let dir = tempfile::tempdir().unwrap();
9138 let queue = Queue::at(dir.path().to_path_buf());
9139 let mut t = task();
9140 t.id = "20260101-000000-unknown".to_owned();
9141 queue.put(&mut t).unwrap();
9142 let dead_pid = injected_dead_pid();
9143 std::fs::write(
9144 dir.path().join(format!("{}.lock", t.id)),
9145 dead_pid.to_string(),
9146 )
9147 .unwrap();
9148
9149 let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
9150 assert!(swept.is_empty(), "an unknown pid must keep its lock");
9151 assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
9152 }
9153
9154 fn run_state_in(status: RunStatus, language: &str) -> RunState {
9155 let mut s = run_state(status);
9156 s.config.graph.language = language.to_owned();
9157 s
9158 }
9159
9160 fn unstarted_verdict(status: RunStatus) -> Verdict {
9161 Verdict {
9162 status,
9163 left_pr: false,
9164 quota_hit: false,
9165 parked: false,
9166 no_viable_candidates: false,
9167 }
9168 }
9169
9170 #[test]
9171 fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
9172 let mut t = task();
9173 t.attempts = 1;
9174 settle_in(
9175 &mut t,
9176 unstarted_verdict(RunStatus::AlreadyInBase),
9177 "already in main",
9178 1,
9179 phrases("en"),
9180 );
9181 assert_eq!(t.status, TaskStatus::Done);
9182 assert_eq!(t.attempts, 0);
9183 }
9184
9185 #[test]
9186 fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
9187 let reason = |language: &str| {
9188 let mut t = task();
9189 settle_in(
9190 &mut t,
9191 unstarted_verdict(RunStatus::Judging),
9192 "boom",
9193 1,
9194 phrases(language),
9195 );
9196 t.last_error.or(t.hold_reason).unwrap_or_default()
9197 };
9198 assert!(
9199 reason("en").starts_with("the graph stopped at `"),
9200 "{}",
9201 reason("en")
9202 );
9203 assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
9204 assert!(reason("日本語").contains("boom"));
9205 assert_eq!(reason("fr"), reason("en"));
9206 }
9207
9208 #[test]
9209 fn describe_follows_the_run_language_and_keeps_the_run_id() {
9210 let en = describe(&run_state_in(RunStatus::Stalled, "en"));
9211 assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
9212 let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
9213 assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
9214 assert!(ja.contains("[run "), "{ja}");
9215 let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
9216 assert!(ended.starts_with("run 終了: "), "{ended}");
9217 let mut de = run_state_in(RunStatus::Failed, "de");
9218 let mut en = run_state_in(RunStatus::Failed, "en");
9219 de.id = "same".to_owned();
9220 en.id = "same".to_owned();
9221 assert_eq!(describe(&de), describe(&en));
9222 }
9223
9224 #[test]
9225 fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
9226 use crate::handover::Refused;
9227 let cases = [
9228 Refused::Foreign {
9229 branch: "b".into(),
9230 path: "/w/x".into(),
9231 why: "made by hand".into(),
9232 },
9233 Refused::Unsafe {
9234 branch: "b".into(),
9235 path: "/w/x".into(),
9236 why: "its worktree has uncommitted changes (a.rs)".into(),
9237 },
9238 Refused::ReleaseFailed {
9239 branch: "b".into(),
9240 path: "/w/x".into(),
9241 run: "ab12".into(),
9242 },
9243 ];
9244 for r in &cases {
9245 let en = (phrases("en").handover_refused)(r);
9246 assert_eq!(en, r.to_string());
9247 let ja = (phrases("ja").handover_refused)(r);
9248 assert!(
9249 !ja.contains("is checked out") && !ja.contains("try again"),
9250 "{ja}"
9251 );
9252 assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
9253 if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
9254 assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
9255 }
9256 }
9257 assert!(phrases("en").handover_hint.contains("release the task"));
9258 assert!(phrases("ja").handover_hint.contains("解放"));
9259 }
9260
9261 #[test]
9262 fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
9263 let build = |lang: &str| {
9264 let mut s = run_state_in(RunStatus::Blocked, lang);
9265 s.id = "same".to_owned();
9266 s.config.graph.review_rounds = 3;
9267 let mut r = review_round(3);
9268 r.expected = 3;
9269 r.answered = 1;
9270 s.reviews.push(r);
9271 s.event(
9272 "review",
9273 "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
9274 );
9275 s
9276 };
9277 let en = describe(&build("en"));
9278 assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
9279 let ja = describe(&build("ja"));
9280 assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
9281 assert!(!ja.contains("never answered"), "{ja}");
9282 assert!(ja.contains("[run "), "{ja}");
9283
9284 let mut failed = build("ja");
9287 failed.reviews[0].e2e.push(crate::run::CommandOutcome {
9288 command: "cargo test".to_owned(),
9289 code: Some(1),
9290 output_tail: String::new(),
9291 duration_ms: 0,
9292 resource_blocked: false,
9293 });
9294 failed.event("review", "stopped; e2e failed: cargo test");
9295 let ja = describe(&failed);
9296 assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
9297 assert!(!ja.contains("席のレビュアー"), "{ja}");
9298 }
9299
9300 #[test]
9301 fn refusals_and_recovery_prose_follow_the_language() {
9302 let home = crate::run::test_home();
9303 let t = held_task_with("r1");
9304 let q = action_question(
9305 "r1",
9306 ask::ChoiceAction::Resume {
9307 run: "r1".to_owned(),
9308 },
9309 );
9310 let refuse = |p: &Phrases| match decide_action(&home, &t, &q, p, |_: &str| bail!("gone")) {
9311 ActionDecision::Refuse(s) => s,
9312 other => panic!("{other:?}"),
9313 };
9314 assert!(refuse(phrases("en")).contains("could not be read: gone"));
9315 assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
9316 assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
9317
9318 let mut held = task();
9319 reclaim(&mut held, None, 2, "ja");
9320 assert!(held.hold_reason.unwrap().contains("保留にしました"));
9321 let mut held = task();
9322 reclaim(&mut held, None, 2, "xx");
9323 assert!(held.hold_reason.unwrap().contains("held for a human"));
9324 }
9325
9326 fn run_state(status: RunStatus) -> RunState {
9327 let mut state = RunState::new(
9328 PathBuf::from("/repo"),
9329 "main".to_owned(),
9330 "abc1234def".to_owned(),
9331 "add retries".to_owned(),
9332 Config::default(),
9333 );
9334 state.status = status;
9335 state
9336 }
9337
9338 fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
9339 Candidate {
9340 index: 0,
9341 label,
9342 agent: "claude".to_owned(),
9343 branch: format!("magi/x/{label}"),
9344 worktree: PathBuf::from("/repo"),
9345 summary: summary.to_owned(),
9346 stat: String::new(),
9347 files: 0,
9348 commits: usize::from(!empty),
9349 empty,
9350 failed: failed.map(str::to_owned),
9351 verified_noop: None,
9352 duration_ms: 0,
9353 folded: false,
9354 }
9355 }
9356
9357 #[test]
9358 fn diagnostic_names_the_failing_gate_checks_and_their_output() {
9359 let mut state = run_state(RunStatus::Blocked);
9360 state.gate = vec![
9361 CommandOutcome {
9362 command: "cargo make check".to_owned(),
9363 code: Some(0),
9364 output_tail: "ok".to_owned(),
9365 duration_ms: 0,
9366 resource_blocked: false,
9367 },
9368 CommandOutcome {
9369 command: "cargo test".to_owned(),
9370 code: Some(101),
9371 output_tail: "thread 'x' panicked: assertion failed".to_owned(),
9372 duration_ms: 0,
9373 resource_blocked: false,
9374 },
9375 ];
9376 let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
9377 assert!(d.contains("cargo test"), "{d}");
9378 assert!(
9379 !d.contains("cargo make check"),
9380 "a passing check is not a diagnostic: {d}"
9381 );
9382 assert!(d.contains("assertion failed"), "{d}");
9383 }
9384
9385 #[test]
9386 fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
9387 let mut state = run_state(RunStatus::Blocked);
9388 state.event(
9389 "land",
9390 "stopped: the fixer produced no commit while 2 check(s) were failing \
9391 (build, lint); stopping instead of looping on an unchanged tree",
9392 );
9393 let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
9394 assert!(d.contains("build"), "{d}");
9395 assert!(d.contains("lint"), "{d}");
9396 assert!(d.contains("fixer produced no commit"), "{d}");
9397 }
9398
9399 #[test]
9400 fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
9401 let state = run_state(RunStatus::VerifiedNoop);
9406 let d = describe(&state);
9407 assert!(
9408 d.contains("agent-verified no-op"),
9409 "expected the display label, not the wire spelling: {d}"
9410 );
9411 assert!(!d.contains("verified_noop"), "{d}");
9412 }
9413
9414 #[test]
9415 fn diagnostic_keeps_gate_panic_before_large_backtrace() {
9416 let mut state = run_state(RunStatus::Failed);
9417 state.gate.push(crate::run::CommandOutcome {
9418 command: "cargo test".into(),
9419 code: Some(101),
9420 output_tail: format!(
9421 "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
9422 " 41: 0x1234 - backtrace frame\n".repeat(10000)
9423 ),
9424 duration_ms: 1,
9425 resource_blocked: false,
9426 });
9427 let d = diagnostic(&state).unwrap();
9428 assert!(d.contains("panicked at widget.rs:12"), "{d}");
9429 assert!(d.contains("assertion failed: widget missing"));
9430 assert!(d.contains("widget log"));
9431 }
9432
9433 #[test]
9434 fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
9435 let mut state = run_state(RunStatus::Failed);
9441 state.candidates = vec![candidate(
9442 'A',
9443 "opened pull request #42, merged it, tagged v1.2.3 and published the release",
9444 true,
9445 None,
9446 )];
9447 let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
9448 assert!(d.contains("candidate A"), "{d}");
9449 assert!(d.contains("tagged v1.2.3"), "{d}");
9450 }
9451
9452 #[test]
9453 fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
9454 let mut state = run_state(RunStatus::Failed);
9455 state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
9456 let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
9457 assert!(d.contains("candidate A"), "{d}");
9458 assert!(d.contains("agent timed out"), "{d}");
9459 }
9460
9461 #[test]
9462 fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
9463 let mut state = run_state(RunStatus::Failed);
9466 state.candidates = vec![candidate('A', "did the work", false, None)];
9467 assert!(diagnostic(&state).is_none());
9468 }
9469
9470 #[test]
9471 fn diagnostic_is_bounded_however_much_a_run_printed() {
9472 let mut state = run_state(RunStatus::Blocked);
9473 state.gate = vec![
9474 CommandOutcome {
9475 command: "cargo test".to_owned(),
9476 code: Some(101),
9477 output_tail: "x".repeat(50_000),
9478 duration_ms: 0,
9479 resource_blocked: false,
9480 },
9481 CommandOutcome {
9482 command: "cargo clippy".to_owned(),
9483 code: Some(1),
9484 output_tail: "y".repeat(50_000),
9485 duration_ms: 0,
9486 resource_blocked: false,
9487 },
9488 ];
9489 state.candidates = vec![
9490 candidate('A', &"z".repeat(50_000), true, None),
9491 candidate('B', &"w".repeat(50_000), true, None),
9492 ];
9493 let d = diagnostic(&state).expect("plenty here to diagnose");
9494 assert!(
9495 d.len() <= DIAGNOSTIC_MAX,
9496 "diagnostic grew to {} bytes, unbounded",
9497 d.len()
9498 );
9499 }
9500
9501 #[test]
9502 fn selected_delivery_guards_survive_recovery_failure_accounting() {
9503 for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
9504 let mut t = task();
9505 let mut state = run_state(status);
9506 t.pr_recovery = Some(crate::pr_recovery::Selection {
9507 url: "url".into(),
9508 branch: format!("magi/task-{}", t.id),
9509 head: "a".repeat(40),
9510 source_head: None,
9511 source_run: None,
9512 source_proof: None,
9513 disposition: Some(crate::pr_recovery::Disposition::Land),
9514 instruction: t.instruction.clone(),
9515 approved_at: Timestamp::now(),
9516 });
9517 state.pr_recovery = t.pr_recovery.clone();
9518 t.start(state.id.clone());
9519 settle_and_diagnose(
9520 &mut t,
9521 Verdict {
9522 status,
9523 left_pr: false,
9524 quota_hit: false,
9525 parked: false,
9526 no_viable_candidates: false,
9527 },
9528 "delivery stopped",
9529 5,
9530 &state,
9531 );
9532 assert_eq!(t.status, TaskStatus::Held);
9533 let reason = t.hold_reason.as_deref().unwrap();
9534 if status == RunStatus::Ready {
9535 assert!(reason.contains("Selected PR delivery is incomplete"));
9536 assert!(t.recovery_budget.is_none());
9537 } else {
9538 assert!(reason.contains("Selected recovery stopped"));
9539 assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
9540 }
9541 assert!(t.pr_recovery.is_some());
9542 }
9543 }
9544
9545 #[test]
9546 fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
9547 let mut state = run_state(RunStatus::Voting);
9548 state.base_sync = Some(crate::run::BaseSync {
9549 tip: "base-tip".into(),
9550 behind: 3,
9551 attempts: 4,
9552 conflict: Some("base stopped".into()),
9553 already_in: None,
9554 });
9555 state.record_base_sync_stop("candidate-head");
9556 let mut t = task();
9557 t.start(state.id.clone());
9558 let verdict = Verdict {
9559 status: RunStatus::Blocked,
9560 left_pr: false,
9561 quota_hit: false,
9562 parked: false,
9563 no_viable_candidates: false,
9564 };
9565 settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
9566 assert_eq!(
9567 t.status,
9568 TaskStatus::Held,
9569 "unspent task attempts cannot start another competition"
9570 );
9571 let at = t.held_at;
9572 let cause = t.hold_notice_cause.clone();
9573 state.begin_pass();
9574 t.release_operator("test-resume", None);
9575 t.start(state.id.clone());
9576 settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
9577 assert_eq!(t.status, TaskStatus::Held);
9578 assert_eq!(t.held_at, at);
9579 assert_eq!(t.hold_notice_cause, cause);
9580 }
9581
9582 #[test]
9583 fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
9584 let mut state = run_state(RunStatus::Blocked);
9585 state.gate = vec![CommandOutcome {
9586 command: "cargo test".to_owned(),
9587 code: Some(101),
9588 output_tail: "assertion failed".to_owned(),
9589 duration_ms: 0,
9590 resource_blocked: false,
9591 }];
9592 let verdict = Verdict {
9593 status: RunStatus::Blocked,
9594 left_pr: false,
9595 quota_hit: false,
9596 parked: false,
9597 no_viable_candidates: false,
9598 };
9599
9600 let mut t = task();
9603 t.start("run-1".to_owned());
9604 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
9605 assert_eq!(t.status, TaskStatus::Failed);
9606 assert!(t.diagnostic.is_none());
9607
9608 t.start("run-2".to_owned());
9611 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
9612 assert_eq!(t.status, TaskStatus::Held);
9613 let d = t.diagnostic.expect("a held task must carry its diagnostic");
9614 assert!(d.contains("cargo test"), "{d}");
9615 }
9616
9617 #[test]
9618 fn a_held_task_names_the_open_question_it_is_waiting_on() {
9619 crate::run::pin_test_home();
9624 let home = crate::run::home();
9625 let state = run_state(RunStatus::VerifiedNoop);
9626 let mut q = ask::Question::new(
9627 state.id.clone(),
9628 "implement".to_owned(),
9629 "impl-A".to_owned(),
9630 "is this really a no-op?".to_owned(),
9631 String::new(),
9632 Vec::new(),
9633 );
9634 Questions::at(home.join("questions")).put(&mut q).unwrap();
9635
9636 let verdict = Verdict {
9637 status: RunStatus::VerifiedNoop,
9638 left_pr: false,
9639 quota_hit: false,
9640 parked: false,
9641 no_viable_candidates: false,
9642 };
9643 let mut t = task();
9644 t.start(state.id.clone());
9645 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
9646
9647 assert_eq!(t.status, TaskStatus::Held);
9648 let reason = t.hold_reason.expect("a held task must record why");
9649 assert!(
9650 reason.starts_with("run ended agent-verified no-op"),
9651 "the original settle reason must survive unchanged: {reason}"
9652 );
9653 assert!(
9654 reason.contains(q.short()),
9655 "the open question's id must be named so the notice is actionable: {reason}"
9656 );
9657 }
9658
9659 #[test]
9660 fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
9661 crate::run::pin_test_home();
9662 let state = run_state(RunStatus::VerifiedNoop);
9663
9664 let verdict = Verdict {
9665 status: RunStatus::VerifiedNoop,
9666 left_pr: false,
9667 quota_hit: false,
9668 parked: false,
9669 no_viable_candidates: false,
9670 };
9671 let mut t = task();
9672 t.start(state.id.clone());
9673 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
9674
9675 assert_eq!(t.status, TaskStatus::Held);
9676 assert_eq!(
9677 t.hold_reason.as_deref(),
9678 Some("run ended agent-verified no-op"),
9679 "nothing to append when the question was already answered or never asked"
9680 );
9681 }
9682
9683 #[test]
9684 fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
9685 crate::run::pin_test_home();
9686 let mut first = run_state(RunStatus::Blocked);
9687 first.id = "20260101-000000-sup1".to_owned();
9688 first.save().unwrap();
9689 let mut second = run_state(RunStatus::Merged);
9690 second.id = "20260101-000000-sup2".to_owned();
9691 second.save().unwrap();
9692
9693 let mut t = task();
9694 t.runs = vec![first.id.clone(), second.id.clone()];
9695 t.status = TaskStatus::Done;
9696
9697 supersede_prior_runs(&t, &crate::run::home());
9698
9699 assert_eq!(
9700 RunState::load(&first.id).unwrap().status,
9701 RunStatus::Superseded,
9702 "the first attempt's Blocked no longer needs anyone's attention"
9703 );
9704 assert_eq!(
9705 RunState::load(&second.id).unwrap().status,
9706 RunStatus::Merged,
9707 "the run that actually succeeded is left exactly as it was"
9708 );
9709 }
9710
9711 #[test]
9712 fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
9713 crate::run::pin_test_home();
9719 let mut first = run_state(RunStatus::Blocked);
9720 first.id = "20260101-000000-sup9".to_owned();
9721 first.driver_pid = Some(std::process::id());
9724 first.driver_started_at = Some(
9725 crate::proc::process_started_at(std::process::id())
9726 .expect("this test process's own start time must be queryable"),
9727 );
9728 first.save().unwrap();
9729 let mut second = run_state(RunStatus::Merged);
9730 second.id = "20260101-000000-supa".to_owned();
9731 second.save().unwrap();
9732
9733 let mut t = task();
9734 t.runs = vec![first.id.clone(), second.id.clone()];
9735 t.status = TaskStatus::Done;
9736
9737 supersede_prior_runs(&t, &crate::run::home());
9738
9739 assert_eq!(
9740 RunState::load(&first.id).unwrap().status,
9741 RunStatus::Blocked,
9742 "a live driver_pid means something is still actually working this run, \
9743 even though no daemon claims it - rewriting under it would just be \
9744 undone the next time that process saves"
9745 );
9746 }
9747
9748 #[test]
9749 fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
9750 let dir = tempfile::tempdir().unwrap();
9756 let home = dir.path().to_path_buf();
9757 let queue = Queue::at(dir.path().join("queue"));
9758
9759 let mut first = run_state(RunStatus::Blocked);
9760 first.id = "20260101-000000-supd".to_owned();
9761 first.driver_pid = Some(std::process::id());
9762 first.driver_started_at = Some(
9763 crate::proc::process_started_at(std::process::id())
9764 .expect("this test process's own start time must be queryable"),
9765 );
9766 first.save_under(&home).unwrap();
9767 let mut second = run_state(RunStatus::Merged);
9768 second.id = "20260101-000000-supe".to_owned();
9769 second.save_under(&home).unwrap();
9770
9771 let mut t = task();
9772 t.runs = vec![first.id.clone(), second.id.clone()];
9773 t.status = TaskStatus::Done;
9774 queue.put(&mut t).unwrap();
9775
9776 resweep_superseded_attempts(&queue, &home);
9777 assert_eq!(
9778 RunState::load_under(&first.id, &home).unwrap().status,
9779 RunStatus::Blocked,
9780 "still live on the first pass, so still untouched"
9781 );
9782
9783 let mut stale = RunState::load_under(&first.id, &home).unwrap();
9789 stale.driver_started_at = Some("1".to_owned());
9790 stale.save_under(&home).unwrap();
9791
9792 resweep_superseded_attempts(&queue, &home);
9793 assert_eq!(
9794 RunState::load_under(&first.id, &home).unwrap().status,
9795 RunStatus::Superseded,
9796 "the second pass catches up what the first one correctly skipped"
9797 );
9798 }
9799
9800 #[test]
9801 fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
9802 crate::run::pin_test_home();
9803 let mut first = run_state(RunStatus::Blocked);
9804 first.id = "20260101-000000-sup3".to_owned();
9805 first.save().unwrap();
9806 let mut second = run_state(RunStatus::Blocked);
9807 second.id = "20260101-000000-sup4".to_owned();
9808 second.save().unwrap();
9809
9810 let mut t = task();
9811 t.runs = vec![first.id.clone(), second.id.clone()];
9812 t.status = TaskStatus::Failed;
9816
9817 supersede_prior_runs(&t, &crate::run::home());
9818
9819 assert_eq!(
9820 RunState::load(&first.id).unwrap().status,
9821 RunStatus::Blocked
9822 );
9823 assert_eq!(
9824 RunState::load(&second.id).unwrap().status,
9825 RunStatus::Blocked
9826 );
9827 }
9828
9829 #[test]
9830 fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
9831 crate::run::pin_test_home();
9835 let mut first = run_state(RunStatus::Blocked);
9836 first.id = "20260101-000000-sup5".to_owned();
9837 first.save().unwrap();
9838
9839 let mut t = task();
9840 t.runs = vec![first.id.clone()];
9841 t.status = TaskStatus::Done;
9842
9843 supersede_prior_runs(&t, &crate::run::home());
9844
9845 assert_eq!(
9846 RunState::load(&first.id).unwrap().status,
9847 RunStatus::Blocked,
9848 "a single-attempt task has no earlier run to supersede"
9849 );
9850 }
9851
9852 #[test]
9853 fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
9854 crate::run::pin_test_home();
9861 let mut first = run_state(RunStatus::Blocked);
9862 first.id = "20260101-000000-supb".to_owned();
9863 first.save().unwrap();
9864 let mut second = run_state(RunStatus::Failed);
9865 second.id = "20260101-000000-supc".to_owned();
9866 second.save().unwrap();
9867
9868 let mut t = task();
9869 t.runs = vec![first.id.clone(), second.id.clone()];
9870 t.status = TaskStatus::Done;
9871
9872 supersede_prior_runs(&t, &crate::run::home());
9873
9874 assert_eq!(
9875 RunState::load(&first.id).unwrap().status,
9876 RunStatus::Blocked,
9877 "the task's last attempt never landed, so there is nothing here \
9878 actually superseding it"
9879 );
9880 }
9881
9882 #[test]
9883 fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
9884 crate::run::pin_test_home();
9888 let mut failed = run_state(RunStatus::Failed);
9889 failed.id = "20260101-000000-sup6".to_owned();
9890 failed.save().unwrap();
9891 let mut noop = run_state(RunStatus::VerifiedNoop);
9892 noop.id = "20260101-000000-sup7".to_owned();
9893 noop.save().unwrap();
9894 let mut winner = run_state(RunStatus::Ready);
9895 winner.id = "20260101-000000-sup8".to_owned();
9896 winner.save().unwrap();
9897
9898 let mut t = task();
9899 t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
9900 t.status = TaskStatus::Done;
9901
9902 supersede_prior_runs(&t, &crate::run::home());
9903
9904 assert_eq!(
9905 RunState::load(&failed.id).unwrap().status,
9906 RunStatus::Failed
9907 );
9908 assert_eq!(
9909 RunState::load(&noop.id).unwrap().status,
9910 RunStatus::VerifiedNoop
9911 );
9912 }
9913
9914 fn approval_question(run: &str) -> ask::Question {
9915 ask::Question::new(
9916 run.to_owned(),
9917 land::APPROVAL_NODE.to_owned(),
9918 "land".to_owned(),
9919 "merge?".to_owned(),
9920 String::new(),
9921 vec!["merge".to_owned(), "hold".to_owned()],
9922 )
9923 }
9924
9925 #[test]
9926 fn land_resume_state_leaves_a_fresh_open_question_waiting() {
9927 crate::run::pin_test_home();
9928 let mut state = run_state(RunStatus::Landing);
9929 state.id = "20260101-000000-fre1".to_owned();
9930 state.parked = true;
9931 state.save().unwrap();
9932 ask::Questions::open()
9933 .put(&mut approval_question(&state.id))
9934 .unwrap();
9935
9936 let mut t = task();
9937 t.runs.push(state.id.clone());
9938 assert_eq!(
9939 land_resume_state(&t),
9940 LandResume::StillWaiting,
9941 "nobody has answered and the timeout has not passed"
9942 );
9943 }
9944
9945 #[test]
9946 fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
9947 crate::run::pin_test_home();
9948 let mut state = run_state(RunStatus::Gating);
9949 state.id = "20260101-000000-gt01".to_owned();
9950 state.parked = true;
9951 state.config.graph.answer_timeout = 60;
9952 state.github_text = Some(crate::run::GithubTextAsk {
9953 rewrite: None,
9954 fingerprint: "f".into(),
9955 title: true,
9956 body: false,
9957 categories: vec!["title-language".into()],
9958 question: None,
9959 asks: 1,
9960 resolved: false,
9961 chosen_title: None,
9962 choice: None,
9963 publication: None,
9964 });
9965 state.save().unwrap();
9966 let store = ask::Questions::open();
9967 let mut q = ask::Question::new(
9968 state.id.clone(),
9969 crate::github_text::ASK_NODE.to_owned(),
9970 crate::github_text::ASK_SEAT.to_owned(),
9971 "s".into(),
9972 String::new(),
9973 vec!["use fallback".into()],
9974 );
9975 store.put(&mut q).unwrap();
9976 let mut t = task();
9977 t.runs.push(state.id.clone());
9978 assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
9979 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9980 store.put(&mut q).unwrap();
9981 assert_eq!(land_resume_state(&t), LandResume::Ready);
9982 assert!(!store.get(&q.id).unwrap().status.open());
9983 state.github_text.as_mut().unwrap().resolved = true;
9985 state.save().unwrap();
9986 assert_eq!(land_resume_state(&t), LandResume::NotLanding);
9987 }
9988
9989 #[test]
9990 fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
9991 crate::run::pin_test_home();
9996 let mut state = run_state(RunStatus::Landing);
9997 state.id = "20260101-000000-exp1".to_owned();
9998 state.parked = true;
9999 state.config.graph.answer_timeout = 60;
10000 state.save().unwrap();
10001
10002 let store = ask::Questions::open();
10003 let mut q = approval_question(&state.id);
10004 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
10005 store.put(&mut q).unwrap();
10006
10007 let mut t = task();
10008 t.runs.push(state.id.clone());
10009 assert_eq!(
10010 land_resume_state(&t),
10011 LandResume::Ready,
10012 "an expired question must not be waited on forever"
10013 );
10014
10015 let after = store.get(&q.id).unwrap();
10016 assert!(
10017 !after.status.open(),
10018 "the question is abandoned, not silently ignored"
10019 );
10020 assert!(
10021 after.resolution().is_none(),
10022 "an abandoned question is not read as a decision"
10023 );
10024 }
10025
10026 #[test]
10027 fn reclaim_settles_a_running_task_against_its_last_run() {
10028 let mut t = task();
10029 t.start("20260904-000000-4043".to_owned());
10030 reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
10031 assert_eq!(
10032 t.status,
10033 TaskStatus::Done,
10034 "a run that actually finished must not stay `running` forever"
10035 );
10036 }
10037
10038 #[test]
10039 fn reclaim_preserves_dispatched_inquiries_until_a_committed_pass() {
10040 let dir = tempfile::tempdir().unwrap();
10041 let queue = Queue::at(dir.path().join("queue"));
10042 let mut task = task();
10043 let mut run = run_state(RunStatus::Blocked);
10044 run.reserve_under(dir.path()).unwrap();
10045 run.driver_exited = true;
10046 run.save_under(dir.path()).unwrap();
10047 queue.put(&mut task).unwrap();
10048 let stale = task.clone();
10049 task.resume_override = Some(crate::queue::OperatorResume {
10050 question_id: "pending-resume".into(),
10051 at: Timestamp::now(),
10052 conductor_rehold: None,
10053 forced: true,
10054 pinned_run: Some(run.id.clone()),
10055 });
10056 task.start(run.id.clone());
10057 queue.put(&mut task).unwrap();
10058 let mut recovered = queue.get(&task.id).unwrap();
10060 let disk = RunState::load_under(&run.id, dir.path()).unwrap();
10061 reclaim(&mut recovered, Some(disk), 2, "en");
10062 queue.put(&mut recovered).unwrap();
10063 assert!(recovered.resume_override.is_none());
10064 assert_eq!(
10065 recovered.dispatched_resumes.get("pending-resume"),
10066 Some(&run.id)
10067 );
10068 let mut stale = stale;
10069 queue.put(&mut stale).unwrap();
10070 assert_eq!(
10071 stale.dispatched_resumes, recovered.dispatched_resumes,
10072 "a stale task writer cannot erase dispatch ownership"
10073 );
10074 let mut resumed = RunState::load_under(&run.id, dir.path()).unwrap();
10075 assert!(resumed.decision_starts.is_empty());
10076 resumed.carry_dispatched_resumes(&queue.get(&task.id).unwrap());
10077 assert!(
10078 resumed.decision_starts.is_empty(),
10079 "handoff is not execution proof"
10080 );
10081 resumed.begin_pass();
10082 resumed.save_under(dir.path()).unwrap();
10083 let mut disk = RunState::load_under(&run.id, dir.path()).unwrap();
10084 assert_eq!(disk.decision_starts.get("pending-resume"), Some(&0));
10085 disk.carry_dispatched_resumes(&recovered);
10086 disk.begin_pass();
10087 assert_eq!(
10088 disk.decision_starts.get("pending-resume"),
10089 Some(&0),
10090 "later execution must preserve the original pass receipt"
10091 );
10092 }
10093
10094 #[test]
10095 fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
10096 let mut t = task();
10097 t.start("20260904-000000-4043".to_owned());
10098 t.last_error = Some("earlier trouble".to_owned());
10099 let mut state = run_state(RunStatus::Judging);
10100 state.parked = true;
10101 reclaim(&mut t, Some(state), 1, "en");
10102 assert_eq!(t.status, TaskStatus::Parked);
10103 assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
10104 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
10105 assert!(t.park_reason.is_some());
10106 assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
10107 assert!(!t.fresh_start);
10108 assert!(t.status.runnable());
10109 }
10110
10111 #[test]
10112 fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
10113 let mut t = task();
10114 t.start("20260904-000000-4043".to_owned());
10115 t.last_error = Some("earlier trouble".to_owned());
10116 settle(
10117 &mut t,
10118 Verdict {
10119 status: RunStatus::Judging,
10120 left_pr: false,
10121 quota_hit: false,
10122 parked: true,
10123 no_viable_candidates: false,
10124 },
10125 "parked after `judging`",
10126 1,
10127 );
10128 assert_eq!(t.status, TaskStatus::Parked);
10129 assert_eq!(t.attempts, 0);
10130 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
10131 assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
10132 assert_eq!(t.schema, crate::queue::SCHEMA);
10133 assert!(
10134 crate::notices::task_held(&t).is_none(),
10135 "a park is not news"
10136 );
10137 t.start("20260904-000000-4043".to_owned());
10138 assert_eq!(t.park_reason, None);
10139 }
10140
10141 #[test]
10142 fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
10143 let mut t = task();
10147 t.start("20260904-000000-4043".to_owned());
10148 reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
10149 assert_eq!(t.status, TaskStatus::Failed);
10150 assert!(t.status.runnable());
10151 }
10152
10153 #[test]
10154 fn a_settled_parked_pass_records_its_cause_and_the_refund() {
10155 let mut t = task();
10156 t.start("20260904-000000-4043".to_owned());
10157 assert_eq!(t.attempts, 1);
10158 let mut run = run_state(RunStatus::Implementing);
10159 run.id = "20260904-000000-4043".to_owned();
10160 run.begin_pass();
10161 let cause = crate::run::ParkCause::Upgrade {
10162 from: "0.121.0".to_owned(),
10163 to: Some("0.121.1".to_owned()),
10164 };
10165 run.end_pass_parked(cause.clone());
10166 run.parked = true;
10167 let verdict = Verdict {
10168 status: run.status,
10169 left_pr: false,
10170 quota_hit: false,
10171 parked: true,
10172 no_viable_candidates: false,
10173 };
10174 let mut orphan = t.clone();
10177 reclaim(&mut orphan, Some(run.clone()), 2, "en");
10178 assert_eq!(orphan.status, TaskStatus::Parked);
10179 assert_eq!(orphan.attempts, 0);
10180 assert_eq!(
10181 orphan.upgrade_resume_key(),
10182 Some((run.passes[0].started_at, orphan.id.as_str()))
10183 );
10184 settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
10185 assert_eq!(t.attempts, 0);
10186 assert_eq!(t.passes.len(), 1);
10187 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
10188 assert_eq!(t.passes[0].parked, Some(cause));
10189 assert_eq!(t.passes[0].pass_index, 0);
10190 assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
10191 assert!(t.upgrade_resume_key().is_some());
10192
10193 t.start("20260904-000000-4043".to_owned());
10196 run.begin_pass();
10197 run.status = RunStatus::Failed;
10198 let verdict = Verdict {
10199 status: RunStatus::Failed,
10200 left_pr: false,
10201 quota_hit: false,
10202 parked: false,
10203 no_viable_candidates: false,
10204 };
10205 settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
10206 assert_eq!(t.passes.len(), 2);
10207 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
10208 assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
10209 assert_eq!(t.passes[1].pass_index, 1);
10210 assert_eq!(t.attempts, 1);
10211 }
10212
10213 #[test]
10214 fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
10215 let mut t = task();
10216 t.start("20260904-000000-4043".to_owned());
10217 reclaim(&mut t, None, 2, "en");
10218 assert_eq!(t.status, TaskStatus::Held);
10219 assert!(
10220 t.last_error
10221 .as_deref()
10222 .is_some_and(|e| e.contains("running")),
10223 "the operator needs to know why this task was held"
10224 );
10225 }
10226
10227 #[test]
10228 fn sync_base_only_orphan_holds_without_replay_or_attempt_change() {
10229 let dir = tempfile::tempdir().unwrap();
10230 let queue = Queue::at(dir.path().to_path_buf());
10231 let mut task = task();
10232 let run = "20261124-000000-dead";
10233 task.link_run(run);
10234 task.attempts = 2;
10235 task.status = TaskStatus::Running;
10236 task.sync_only = Some(crate::base_sync_only::Request {
10237 run: run.into(),
10238 at: Timestamp::now(),
10239 });
10240 queue.put(&mut task).unwrap();
10241 assert_eq!(
10242 reclaim_orphaned_running(&queue, 3, &Default::default()),
10243 vec![task.id.clone()]
10244 );
10245 let saved = queue.get(&task.id).unwrap();
10246 assert_eq!(saved.status, TaskStatus::Held);
10247 assert_eq!(saved.attempts, 2);
10248 assert_eq!(saved.execution_runs(), [run]);
10249 assert!(
10250 saved
10251 .last_error
10252 .unwrap()
10253 .contains("verification was not allowed")
10254 );
10255 assert!(reclaim_orphaned_running(&queue, 3, &Default::default()).is_empty());
10256 }
10257
10258 #[test]
10259 fn sync_base_only_completed_orphan_holds_without_charging_or_double_refunding() {
10260 use crate::base_sync_only::{Outcome, Pass, Request};
10261
10262 let mut state = run_state(RunStatus::Blocked);
10263 let mut task = task();
10264 let request = Request {
10265 run: state.id.clone(),
10266 at: Timestamp::now(),
10267 };
10268 task.start(state.id.clone());
10269 task.sync_only = Some(request.clone());
10270 task.attempts = 2;
10272 let mut pass = Pass::new(request, &state);
10273 pass.result = Outcome::AlreadyCurrent;
10274 state.sync_only_passes.push(pass);
10275 state.begin_pass();
10276
10277 reclaim(&mut task, Some(state), 3, "en");
10278
10279 assert_eq!(task.status, TaskStatus::Held);
10280 assert_eq!(task.attempts, 2);
10281 assert!(task.sync_only.is_none());
10282 let detail = task.hold_reason.unwrap();
10283 assert!(detail.contains("HEAD already contains the base"));
10284 assert!(detail.contains("verification was not allowed"));
10285 }
10286
10287 #[test]
10288 fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
10289 let dir = tempfile::tempdir().unwrap();
10290 let queue = Queue::at(dir.path().to_path_buf());
10291
10292 let mut orphaned = task();
10294 orphaned.id = "20260904-000000-orph".to_owned();
10295 orphaned.status = TaskStatus::Running;
10296 orphaned.attempts = 1;
10297 queue.put(&mut orphaned).unwrap();
10298
10299 let mut alive = task();
10300 alive.id = "20260904-000000-live".to_owned();
10301 alive.status = TaskStatus::Running;
10302 alive.attempts = 1;
10303 queue.put(&mut alive).unwrap();
10304 let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
10305
10306 let mut queued = task();
10307 queued.id = "20260904-000000-wait".to_owned();
10308 queue.put(&mut queued).unwrap();
10309
10310 let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
10311 assert_eq!(reclaimed, vec![orphaned.id.clone()]);
10312
10313 assert_eq!(
10314 queue.get(&orphaned.id).unwrap().status,
10315 TaskStatus::Held,
10316 "nothing was driving it and there was no run to recover"
10317 );
10318 assert_eq!(
10319 queue.get(&alive.id).unwrap().status,
10320 TaskStatus::Running,
10321 "a live claim must protect the task it belongs to"
10322 );
10323 assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
10324 }
10325
10326 fn read_run_under(home: &Path, id: &str) -> RunState {
10332 let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
10333 serde_json::from_str(&body).unwrap()
10334 }
10335
10336 #[test]
10337 fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
10338 let dir = tempfile::tempdir().unwrap();
10339 let home = dir.path().to_path_buf();
10340 let now = Timestamp::now();
10341 let overrun_seat = || crate::run::ActiveSeat {
10342 node: "implement".to_owned(),
10343 started_at: now - jiff::SignedDuration::new(21_000, 0),
10344 timeout_secs: 3_600,
10345 attempt: 0,
10346 task: None,
10347 command: None,
10348 index: None,
10349 total: None,
10350 };
10351
10352 let mut dead = run_state(RunStatus::Implementing);
10353 dead.id = "20260101-000000-dead".to_owned();
10354 dead.active.insert("impl-A".to_owned(), overrun_seat());
10355 dead.driver_pid = Some(4242);
10358 dead.save_under(&home).unwrap();
10359
10360 let mut alive = run_state(RunStatus::Implementing);
10363 alive.id = "20260101-000000-aliv".to_owned();
10364 alive.active.insert("impl-A".to_owned(), overrun_seat());
10365 alive.save_under(&home).unwrap();
10366 let mut status = Status::new();
10367 status.current = vec![Current {
10368 worker: None,
10369 task: "20260101-000000-task".to_owned(),
10370 run: alive.id.clone(),
10371 }];
10372 write_status_to(&home.join("daemon.json"), &status).unwrap();
10373
10374 let questions = Questions::at(home.join("questions"));
10378 let mut q = ask::Question::new(
10379 dead.id.clone(),
10380 "implement".to_owned(),
10381 "impl-A".to_owned(),
10382 "Which storage backend?".to_owned(),
10383 String::new(),
10384 vec!["SQLite".to_owned(), "Redis".to_owned()],
10385 );
10386 questions.put(&mut q).unwrap();
10387
10388 let abandoned = reclaim_abandoned_runs_with(
10389 &home,
10390 now,
10391 |pid| if pid == 4242 { Some(false) } else { None },
10392 |_| panic!("a query answering Dead outright needs no identity corroboration"),
10393 );
10394 assert_eq!(abandoned, vec![dead.id.clone()]);
10395
10396 let reloaded = read_run_under(&home, &dead.id);
10397 assert_eq!(reloaded.status, RunStatus::Failed);
10398 assert!(reloaded.active.is_empty());
10399 assert!(
10400 !questions.get(&q.id).unwrap().status.open(),
10401 "the failed run's own open question must be settled in the same pass"
10402 );
10403
10404 let still_alive = read_run_under(&home, &alive.id);
10405 assert_eq!(
10406 still_alive.status,
10407 RunStatus::Implementing,
10408 "a live daemon's claim protects it"
10409 );
10410 assert!(!still_alive.active.is_empty());
10411 }
10412
10413 #[test]
10423 fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
10424 let dir = tempfile::tempdir().unwrap();
10425 let home = dir.path().to_path_buf();
10426 let now = Timestamp::now();
10427
10428 let mut manual = run_state(RunStatus::Reviewing);
10429 manual.id = "20260101-000000-manl".to_owned();
10430 manual.active.insert(
10431 "review-1".to_owned(),
10432 crate::run::ActiveSeat {
10433 node: "review".to_owned(),
10434 started_at: now - jiff::SignedDuration::new(21_000, 0),
10435 timeout_secs: 3_600,
10436 attempt: 0,
10437 task: None,
10438 command: None,
10439 index: None,
10440 total: None,
10441 },
10442 );
10443 manual.driver_pid = Some(4242);
10447 manual.driver_started_at = Some("1790000000".to_owned());
10448 manual.save_under(&home).unwrap();
10449
10450 let abandoned = reclaim_abandoned_runs_with(
10451 &home,
10452 now,
10453 |pid| if pid == 4242 { Some(true) } else { None },
10454 |pid| {
10455 if pid == 4242 {
10456 Some("1790000000".to_owned())
10457 } else {
10458 None
10459 }
10460 },
10461 );
10462 assert!(
10463 abandoned.is_empty(),
10464 "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
10465 );
10466
10467 let reloaded = read_run_under(&home, &manual.id);
10468 assert_eq!(reloaded.status, RunStatus::Reviewing);
10469 assert!(!reloaded.active.is_empty());
10470 }
10471
10472 #[test]
10473 fn an_already_claimed_task_is_skipped_rather_than_failed() {
10474 let dir = tempfile::tempdir().unwrap();
10475 let queue = Queue::at(dir.path().to_path_buf());
10476 let mut only = task();
10477 queue.put(&mut only).unwrap();
10478
10479 let _elsewhere = queue.claim(&only.id).unwrap();
10480 let candidates = runnable(&queue);
10481 assert_eq!(candidates.len(), 1, "the task is still runnable");
10482 assert!(
10483 queue.claim(&candidates[0].id).is_err(),
10484 "the loop cannot take a claim somebody else holds"
10485 );
10486
10487 let after = queue.get(&only.id).unwrap();
10488 assert_eq!(after.status, TaskStatus::Queued);
10489 assert_eq!(
10490 after.attempts, 0,
10491 "losing the race is not an attempt at the task"
10492 );
10493 assert_eq!(after.last_error, None);
10494 }
10495
10496 #[test]
10497 fn the_status_file_round_trips_and_its_heartbeat_advances() {
10498 let dir = tempfile::tempdir().unwrap();
10499 let path = dir.path().join("daemon.json");
10500
10501 let mut status = Status::new();
10502 status.idle = false;
10503 status.completed = 7;
10504 status.current = vec![Current {
10505 worker: None,
10506 task: "20260902-000000-t111".to_owned(),
10507 run: "20260902-000001-r111".to_owned(),
10508 }];
10509 write_status_to(&path, &status).unwrap();
10510 let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
10511 assert_eq!(first.schema, SCHEMA);
10512 assert_eq!(first.pid, std::process::id());
10513 assert!(!first.idle);
10514 assert_eq!(first.completed, 7);
10515 assert_eq!(first.current, status.current);
10516 assert!(
10517 !path.with_extension("json.tmp").exists(),
10518 "the temp file is renamed, not left behind"
10519 );
10520
10521 std::thread::sleep(Duration::from_millis(5));
10522 status.updated_at = Timestamp::now();
10523 status.polls = 3;
10524 write_status_to(&path, &status).unwrap();
10525 let second: Status =
10526 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
10527 assert!(
10528 second.updated_at > first.updated_at,
10529 "a reader can only detect staleness if the heartbeat moves"
10530 );
10531 assert_eq!(
10532 second.started_at, first.started_at,
10533 "the start time is not a heartbeat"
10534 );
10535 assert_eq!(second.polls, 3);
10536 }
10537
10538 #[test]
10539 fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
10540 let dir = tempfile::tempdir().unwrap();
10541
10542 assert!(read_status(dir.path()).is_none(), "no file, no daemon");
10543
10544 let mut status = Status::new();
10545 status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
10546 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10547 let stale = read_status(dir.path()).unwrap();
10548 assert!(
10549 !stale.running(Timestamp::now()),
10550 "a minute without a heartbeat is a dead daemon, not a busy one"
10551 );
10552 assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
10553
10554 status.updated_at = Timestamp::now();
10555 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10556 let fresh = read_status(dir.path()).unwrap();
10557 assert!(fresh.running(Timestamp::now()));
10558 }
10559
10560 #[test]
10561 fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
10562 let dir = tempfile::tempdir().unwrap();
10563 let now = Timestamp::now();
10564 let mine = "20260903-080619-01c2";
10565
10566 assert!(
10567 !is_working_on(dir.path(), mine, now),
10568 "no status file means nobody is working on anything"
10569 );
10570
10571 let mut status = Status::new();
10572 status.current = vec![Current {
10573 worker: None,
10574 task: "20260903-080340-0167".to_owned(),
10575 run: mine.to_owned(),
10576 }];
10577 status.updated_at = now;
10578 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10579 assert!(is_working_on(dir.path(), mine, now));
10580 assert!(
10581 !is_working_on(dir.path(), "20260903-105039-3cbf", now),
10582 "a daemon busy with one run is not working on another"
10583 );
10584
10585 status.updated_at = now - jiff::SignedDuration::from_secs(600);
10588 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10589 assert!(
10590 !is_working_on(dir.path(), mine, now),
10591 "a stale heartbeat is a dead daemon, so its run is a leftover"
10592 );
10593 }
10594
10595 #[test]
10596 fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
10597 let dir = tempfile::tempdir().unwrap();
10598 let now = Timestamp::now();
10599
10600 assert!(
10601 !is_working_on_short(dir.path(), "01c2", now),
10602 "no status file means nobody is working on anything"
10603 );
10604
10605 let mut status = Status::new();
10606 status.current = vec![Current {
10607 worker: None,
10608 task: "20260903-080340-0167".to_owned(),
10609 run: "20260903-080619-01c2".to_owned(),
10610 }];
10611 status.updated_at = now;
10612 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10613 assert!(
10614 is_working_on_short(dir.path(), "01c2", now),
10615 "the run's short id is the last block of its full id"
10616 );
10617 assert!(
10618 !is_working_on_short(dir.path(), "3cbf", now),
10619 "a daemon busy with one worktree bay is not working on another"
10620 );
10621 }
10622
10623 #[test]
10624 fn a_newer_status_file_still_yields_a_reading() {
10625 let dir = tempfile::tempdir().unwrap();
10626 std::fs::write(
10629 dir.path().join("daemon.json"),
10630 serde_json::json!({
10631 "schema": 2,
10632 "updated_at": Timestamp::now().to_string(),
10633 "idle": true,
10634 "surprise": { "nested": [1, 2, 3] },
10635 })
10636 .to_string(),
10637 )
10638 .unwrap();
10639
10640 let reading = read_status(dir.path()).expect("a forward-compatible read");
10641 assert!(reading.running(Timestamp::now()));
10642 assert!(reading.idle);
10643 assert!(reading.current.is_empty());
10644 }
10645
10646 #[test]
10647 fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
10648 let dir = tempfile::tempdir().unwrap();
10654 std::fs::write(
10655 dir.path().join("daemon.json"),
10656 serde_json::json!({
10657 "schema": 1,
10658 "pid": 4242,
10659 "updated_at": Timestamp::now().to_string(),
10660 "idle": false,
10661 "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
10662 "completed": 3,
10663 "polls": 9,
10664 })
10665 .to_string(),
10666 )
10667 .unwrap();
10668
10669 let reading = read_status(dir.path()).expect("an older shape must still parse");
10670 assert!(reading.running(Timestamp::now()));
10671 assert_eq!(
10672 reading.current,
10673 vec![Current {
10674 worker: None,
10675 task: "20260902-140501-aaaa".to_owned(),
10676 run: "20260902-140502-bbbb".to_owned(),
10677 }]
10678 );
10679 }
10680
10681 #[test]
10682 fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
10683 let dir = tempfile::tempdir().unwrap();
10684 std::fs::write(
10685 dir.path().join("daemon.json"),
10686 serde_json::json!({
10687 "schema": 1,
10688 "updated_at": Timestamp::now().to_string(),
10689 "idle": true,
10690 "current": null,
10691 })
10692 .to_string(),
10693 )
10694 .unwrap();
10695 let with_null = read_status(dir.path()).expect("null must still parse");
10696 assert!(with_null.current.is_empty());
10697
10698 std::fs::write(
10699 dir.path().join("daemon.json"),
10700 serde_json::json!({
10701 "schema": 1,
10702 "updated_at": Timestamp::now().to_string(),
10703 "idle": true,
10704 })
10705 .to_string(),
10706 )
10707 .unwrap();
10708 let absent = read_status(dir.path()).expect("a missing field must still parse");
10709 assert!(absent.current.is_empty());
10710 }
10711
10712 #[test]
10713 fn a_task_without_a_repository_runs_in_the_daemons_default() {
10714 let fallback = Path::new("/default");
10715 let mut blank = task();
10716 blank.repo = PathBuf::new();
10717 assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
10718 let mut dot = task();
10719 dot.repo = PathBuf::from(".");
10720 assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
10721 assert_eq!(
10722 repo_for(&task(), fallback),
10723 PathBuf::from("/repo"),
10724 "a task that names a repository keeps it"
10725 );
10726 }
10727
10728 #[test]
10729 fn new_tasks_inherit_the_daemon_build_cache_but_historical_tasks_remain_shared() {
10730 let dir = tempfile::tempdir().unwrap();
10731 let repo = dir.path();
10732 let path = repo.join("explicit.toml");
10733 std::fs::write(
10734 &path,
10735 "[verify]\nbuild_cache = 'isolated'\n[graph]\njudges = 1\n",
10736 )
10737 .unwrap();
10738 let opts = Opts {
10739 config: Some(path),
10740 ..Opts::default()
10741 };
10742 let queue = Queue::at(repo.join("queue"));
10743 let mut new = task();
10744 queue.put(&mut new).unwrap();
10745 let resolved = |task: &Task| prepare_for(repo, &opts, task).unwrap();
10746 assert_eq!(
10747 resolved(&queue.get(&new.id).unwrap()).verify.build_cache,
10748 BuildCache::Isolated
10749 );
10750
10751 let mut old = task();
10752 old.schema = 22;
10753 queue.put(&mut old).unwrap();
10754 let mut old = queue.get(&old.id).unwrap();
10755 let config = resolved(&old);
10756 assert_eq!(config.verify.build_cache, BuildCache::Shared);
10757 assert_eq!(config.graph.judges, 1, "preserve daemon config inheritance");
10758 old.hold_manual(Some("wait".into()));
10759 queue.put(&mut old).unwrap();
10760
10761 let mut saved = queue.get(&old.id).unwrap();
10762 assert_eq!(resolved(&saved).verify.build_cache, BuildCache::Shared);
10763 saved
10764 .overrides
10765 .as_mut()
10766 .unwrap()
10767 .merge_over(&crate::queue::RunOverrides {
10768 build_cache: Some(BuildCache::Isolated),
10769 ..Default::default()
10770 });
10771 queue.put(&mut saved).unwrap();
10772 assert_eq!(
10773 resolved(&queue.get(&saved.id).unwrap()).verify.build_cache,
10774 BuildCache::Isolated
10775 );
10776 }
10777
10778 #[test]
10779 fn urgent_build_cache_precedes_config_but_not_an_explicit_choice() {
10780 let dir = tempfile::tempdir().unwrap();
10781 let path = dir.path().join("explicit.toml");
10782 let write = |verify: &str| {
10783 std::fs::write(&path, format!("[verify]\nbuild_cache = 'shared'\n{verify}")).unwrap();
10784 };
10785 write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test\"]\n");
10786 let opts = Opts {
10787 config: Some(path.clone()),
10788 ..Opts::default()
10789 };
10790 let mut task = task();
10791 task.set_urgent(true).unwrap();
10792 let resolved = |task: &Task| {
10793 prepare_for(dir.path(), &opts, task)
10794 .unwrap()
10795 .verify
10796 .build_cache
10797 };
10798 assert_eq!(resolved(&task), BuildCache::Isolated);
10799 task.change_build_cache(Some(BuildCache::Shared)).unwrap();
10800 assert_eq!(resolved(&task), BuildCache::Shared);
10801 task.change_build_cache(None).unwrap();
10802 assert_eq!(resolved(&task), BuildCache::Isolated);
10803 task.set_urgent(false).unwrap();
10804 assert_eq!(resolved(&task), BuildCache::Shared);
10805
10806 task.set_urgent(true).unwrap();
10810 write("e2e = [\"npm test\"]\n");
10811 assert_eq!(resolved(&task), BuildCache::Shared);
10812 write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test | tee log\"]\n");
10813 assert_eq!(resolved(&task), BuildCache::Shared);
10814 task.change_build_cache(Some(BuildCache::Isolated)).unwrap();
10816 assert_eq!(resolved(&task), BuildCache::Isolated);
10817 }
10818
10819 #[test]
10820 fn task_implementers_edit_inherits_daemon_config_and_merge() {
10821 let dir = tempfile::tempdir().unwrap();
10822 let path = dir.path().join("explicit.toml");
10823 std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
10824 let opts = Opts {
10825 config: Some(path),
10826 merge: Some("none".into()),
10827 ..Default::default()
10828 };
10829 let mut t = task();
10830 t.set_implementers(
10831 2,
10832 &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10833 .unwrap(),
10834 )
10835 .unwrap();
10836 let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
10837 assert_eq!(cfg.graph.implementers, 2);
10838 assert_eq!(cfg.graph.judges, 1);
10839 assert_eq!(cfg.merge.mode, MergeMode::None);
10840 t.set_implementers(1, &cfg).unwrap();
10841 let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
10842 apply_task_implementers(&mut cfg, &t);
10843 assert_eq!(cfg.graph.implementers, 1);
10844 assert_eq!(cfg.graph.judges, 1);
10845 assert_eq!(cfg.merge.mode, MergeMode::None);
10846 }
10847
10848 #[test]
10849 fn task_implementers_direct_overrides_stay_isolated_after_edits() {
10850 let dir = tempfile::tempdir().unwrap();
10851 let repo = dir.path().join("repo");
10852 std::fs::create_dir(&repo).unwrap();
10853 std::fs::write(
10854 repo.join("magi.toml"),
10855 "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
10856 )
10857 .unwrap();
10858 let daemon_config = dir.path().join("daemon.toml");
10859 std::fs::write(
10860 &daemon_config,
10861 "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
10862 )
10863 .unwrap();
10864 let opts = Opts {
10865 config: Some(daemon_config),
10866 merge: Some("pr".into()),
10867 ..Default::default()
10868 };
10869 let q = Queue::at(dir.path().join("queue"));
10870 let validation: Config =
10871 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10872 .unwrap();
10873 for record in ["{}", r#"{"candidates":2}"#] {
10875 let overrides = serde_json::from_str(record).unwrap();
10876 let filing = crate::direct::Filing {
10877 instruction: "work".into(),
10878 title: "direct".into(),
10879 repo: repo.clone(),
10880 source: crate::queue::Source::Human,
10881 solo: false,
10882 overrides,
10883 review_of: None,
10884 sources: Default::default(),
10885 };
10886 let filed =
10887 crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
10888 let crate::direct::Filed::Standalone {
10889 mut task,
10890 claim: _claim,
10891 } = filed
10892 else {
10893 panic!("local filing")
10894 };
10895 let before = prepare_for(&repo, &opts, &task).unwrap();
10896 assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
10897 assert_eq!(
10898 before.merge.mode,
10899 MergeMode::None,
10900 "daemon --merge must not leak"
10901 );
10902 for n in [2, 1, 2] {
10903 task.set_implementers(n, &validation).unwrap();
10904 q.put(&mut task).unwrap();
10905 task = q.get(&task.id).unwrap();
10906 assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
10907 let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
10908 apply_task_implementers(&mut cfg, &task);
10909 assert_eq!(cfg.graph.implementers, usize::from(n));
10910 assert_eq!(cfg.graph.judges, 2);
10911 assert_eq!(cfg.merge.mode, MergeMode::None);
10912 }
10913 }
10914 }
10915
10916 #[test]
10917 fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
10918 let cfg: Config =
10919 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10920 .unwrap();
10921 let mut t = task();
10922 t.review_of = Some("review-target".into());
10923 t.hold_manual(Some("retry".into()));
10924 let mut previous = RunState::new(
10925 PathBuf::from("/repo"),
10926 "main".into(),
10927 "abc1234".into(),
10928 "review".into(),
10929 cfg.clone(),
10930 );
10931 previous.config.graph.implementers = 2;
10932 for count in [1, 3] {
10933 t.set_implementers(count, &cfg).unwrap();
10934 t.release();
10935 assert_eq!(t.review_of.as_deref(), Some("review-target"));
10936 for proposed in [
10937 Starter::Resume(previous.id.clone()),
10938 Starter::Review("recovery-target".into()),
10939 ] {
10940 assert_eq!(
10941 starter_with_implementers(&t, Some(&previous), proposed),
10942 Starter::Review("review-target".into())
10943 );
10944 }
10945 let mut configured = cfg.clone();
10946 apply_task_implementers(&mut configured, &t);
10947 assert_eq!(configured.graph.implementers, usize::from(count));
10948 assert_eq!(previous.config.graph.implementers, 2);
10949 }
10950 }
10951
10952 #[test]
10953 fn task_implementers_dispatch_and_resume_agree() {
10954 let mut t = task();
10955 let cfg: crate::config::Config =
10956 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10957 .unwrap();
10958 let mut run = RunState::new(
10959 PathBuf::from("/repo"),
10960 "main".into(),
10961 "abc1234".into(),
10962 "work".into(),
10963 cfg.clone(),
10964 );
10965 run.config.graph.implementers = 2;
10966 for n in [2, 1, 3, 2] {
10967 t.set_implementers(n, &cfg).unwrap();
10968 let mut dispatched = cfg.clone();
10969 apply_task_implementers(&mut dispatched, &t);
10970 assert_eq!(dispatched.graph.implementers, usize::from(n));
10971 assert_eq!(implementers_match(&t, &run), n == 2);
10972 for proposed in [
10973 Starter::Resume(run.id.clone()),
10974 Starter::Review("old-branch".into()),
10975 ] {
10976 let expected = if n == 2 {
10977 proposed.clone()
10978 } else {
10979 Starter::Start
10980 };
10981 assert_eq!(
10982 starter_with_implementers(&t, Some(&run), proposed),
10983 expected
10984 );
10985 }
10986 assert_eq!(
10987 run.config.graph.implementers, 2,
10988 "history must not be rewritten"
10989 );
10990 }
10991 t.solo = false;
10992 t.overrides = None;
10993 assert!(implementers_match(&t, &run));
10994 }
10995
10996 #[test]
10997 fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
10998 let mut solo_cfg = Config::default();
11004 solo_cfg.graph.implementers = 3;
11005 let mut solo_task = task();
11006 solo_task.solo = true;
11007 apply_task_implementers(&mut solo_cfg, &solo_task);
11008 assert_eq!(solo_cfg.graph.implementers, 1);
11009
11010 let mut plain_cfg = Config::default();
11011 plain_cfg.graph.implementers = 3;
11012 let plain_task = task();
11013 assert!(!plain_task.solo);
11014 apply_task_implementers(&mut plain_cfg, &plain_task);
11015 assert_eq!(
11016 plain_cfg.graph.implementers, 3,
11017 "a task that did not ask to run alone keeps the config's candidates"
11018 );
11019 }
11020
11021 fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
11022 QuotaLoss {
11023 cause: crate::agent::QuotaCause::UsageLimit,
11024 agent: String::new(),
11025 seat: seat.into(),
11026 node: "judge".into(),
11027 at: at.parse().unwrap(),
11028 reset: reset.map(str::to_string),
11029 }
11030 }
11031
11032 #[test]
11033 fn authentication_losses_never_arm_a_cooldown_even_with_reset_hints() {
11034 let now = Timestamp::now();
11035 for reset in [None, Some("in 1h")] {
11036 let auth = crate::agent::Quota {
11037 cause: crate::agent::QuotaCause::Authentication,
11038 agent: "alpha".into(),
11039 reset: reset.map(str::to_owned),
11040 };
11041 let loss = QuotaLoss::from_report("advisor-1".into(), "advise", Some(&auth));
11042 assert_eq!(cooldown_until(&[loss], now), None);
11043 }
11044 }
11045
11046 #[test]
11047 fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
11048 let old: Vec<QuotaLoss> = (1..=4)
11049 .map(|i| {
11050 loss(
11051 &format!("judge-{i}"),
11052 "2026-09-23T05:23:00Z",
11053 Some("2:40pm (Asia/Tokyo)"),
11054 )
11055 })
11056 .collect();
11057 let fresh = losses_this_attempt(&old, &old);
11058 assert!(fresh.is_empty());
11059 assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
11060 }
11062
11063 #[test]
11064 fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
11065 let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
11066 let now = Timestamp::now();
11067 let mut after = old.clone();
11068 after.push(loss("judge-2", &now.to_string(), None));
11069 let fresh = losses_this_attempt(&old, &after);
11070 assert_eq!(fresh, vec![after[1].clone()]);
11071 let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
11072 assert_eq!(
11073 until,
11074 now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
11075 );
11076 }
11077
11078 #[test]
11079 fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
11080 let before = vec![
11083 loss("judge-1", "2026-09-23T05:23:00Z", None),
11084 loss("judge-2", "2026-09-23T05:24:00Z", None),
11085 ];
11086 let after = vec![
11087 loss("judge-2", "2026-09-23T05:24:00Z", None),
11088 loss("judge-1", "2026-09-24T01:00:00Z", None),
11089 ];
11090 assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
11091 }
11092
11093 #[test]
11094 fn merge_overrides_are_parsed_or_refused() {
11095 assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
11096 assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
11097 assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
11098 assert!(merge_mode("squash").is_err());
11099 }
11100
11101 #[test]
11102 fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
11103 let now = Timestamp::now();
11104 let fallback = Duration::from_secs(300);
11105 let cap = Duration::from_secs(1800);
11106
11107 assert_eq!(quota_wait(None, now, fallback, cap), fallback);
11109
11110 let soon = now + jiff::SignedDuration::from_secs(600);
11112 assert_eq!(
11113 quota_wait(Some(soon), now, fallback, cap),
11114 Duration::from_secs(600)
11115 );
11116
11117 let past = now - jiff::SignedDuration::from_secs(60);
11120 assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
11121
11122 let far = now + jiff::SignedDuration::from_secs(3 * 3600);
11125 assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
11126 }
11127
11128 #[test]
11129 fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
11130 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
11131
11132 let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
11133 assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
11134
11135 let already_past =
11139 parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
11140 assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
11141
11142 assert!(
11143 parse_reset_hint("session limit reached", now, now).is_none(),
11144 "free text with no recognised shape is not guessed at"
11145 );
11146 assert!(
11147 parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
11148 "an unresolvable zone name is not guessed at either"
11149 );
11150 }
11151
11152 #[test]
11153 fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
11154 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
11155
11156 let at = parse_reset_hint(
11157 "You've hit your usage limit. Visit \
11158 https://chatgpt.com/codex/settings/usage to purchase more \
11159 credits or try again at Sep 19th, 2026 5:10 PM.",
11160 now,
11161 now,
11162 )
11163 .expect("the codex reset wording is a recognised shape");
11164 assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
11165
11166 let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
11171 .expect("an explicit year needs no rollover");
11172 assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
11173
11174 assert!(
11175 parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
11176 "a two-digit year is not the documented shape and is not guessed at"
11177 );
11178 assert!(
11179 parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
11180 "a four-letter month name is not the documented three-letter abbreviation"
11181 );
11182 assert!(
11183 parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
11184 "an explicit zone on the dated shape is a format nobody has \
11185 documented, and is refused rather than guessed at as UTC"
11186 );
11187 }
11188
11189 #[test]
11190 fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
11191 let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
11192 let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
11193
11194 let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
11195 assert_eq!(at.as_second() - recorded.as_second(), 3769);
11196
11197 let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
11198 assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
11199
11200 for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
11201 assert!(
11202 parse_reset_hint(bad, now, recorded).is_none(),
11203 "{bad:?} must not be guessed at"
11204 );
11205 }
11206 }
11207
11208 fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
11212 let config = dir.join("magi.toml");
11213 std::fs::write(
11214 &config,
11215 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
11216 )
11217 .unwrap();
11218 let opts = Opts {
11219 poll: Duration::from_secs(30),
11220 config: Some(config),
11221 repo: dir.join("repo"),
11225 ..Opts::default()
11226 };
11227 let home = dir.join("home");
11236 let stamps = home.join("service-ticks");
11239 std::fs::create_dir_all(&stamps).unwrap();
11240 for service in ["waiter", "deputies", "release-watch"] {
11241 std::fs::write(
11242 stamps.join(service),
11243 Timestamp::now().as_second().to_string(),
11244 )
11245 .unwrap();
11246 }
11247 for operation in [
11248 "conductor",
11249 "maintenance",
11250 "housekeeping",
11251 "disk-pressure",
11252 "cache",
11253 "fetch",
11254 "chat-goals",
11255 ] {
11256 std::fs::write(
11257 stamps.join(format!("daemon-{operation}")),
11258 serde_json::to_vec(&Timestamp::now()).unwrap(),
11259 )
11260 .unwrap();
11261 }
11262 let worktrees = dir.join("wt");
11263 (
11264 opts,
11265 Queue::at(dir.join("queue")),
11266 home.join("daemon.json"),
11267 home,
11268 worktrees,
11269 )
11270 }
11271
11272 #[tokio::test]
11273 async fn disk_wait_maintenance_recovers_while_another_task_is_running() {
11274 let dir = tempfile::tempdir().unwrap();
11275 let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
11276 let mut waiting = task();
11277 waiting.repo = opts.repo.clone();
11278 waiting.hold_machine(crate::disk::gate(1, 100));
11279 waiting.mark_disk_capacity();
11280 waiting.attempts = 2;
11281 queue.put(&mut waiting).unwrap();
11282 let mut busy = task();
11283 busy.status = TaskStatus::Running;
11284 queue.put(&mut busy).unwrap();
11285 let payload = serde_json::to_value(ServiceWorker {
11286 opts,
11287 queue: queue.root().to_owned(),
11288 worktrees_root: worktrees,
11289 operation: "maintenance".into(),
11290 })
11291 .unwrap();
11292 run_service_worker(&home, payload.clone()).await.unwrap();
11293 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Queued);
11294 assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
11295 assert_eq!(queue.get(&busy.id).unwrap().status, TaskStatus::Running);
11296 run_service_worker(&home, payload).await.unwrap();
11297 assert!(
11298 crate::worker::active(&home).unwrap().is_empty(),
11299 "monitoring only queues; normal dispatch owns launches"
11300 );
11301 assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
11302 }
11303
11304 #[tokio::test]
11305 async fn source_eviction_service_receipts_explain_idle_and_active_skips() {
11306 let dir = tempfile::tempdir().unwrap();
11307 let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
11308 let cfg = Config::default();
11309 start_service(
11310 &home,
11311 &opts,
11312 &queue,
11313 &worktrees,
11314 "housekeeping",
11315 Some(&cfg),
11316 true,
11317 )
11318 .await
11319 .unwrap();
11320 let receipt = home.join("source-eviction-housekeeping-dispatch.json");
11321 let read = |path: &Path| -> serde_json::Value {
11322 serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap()
11323 };
11324 assert_eq!(read(&receipt)["detail"], "cadence not due");
11325 std::fs::remove_file(home.join("service-ticks/daemon-housekeeping")).unwrap();
11326 start_service(
11327 &home,
11328 &opts,
11329 &queue,
11330 &worktrees,
11331 "housekeeping",
11332 Some(&cfg),
11333 true,
11334 )
11335 .await
11336 .unwrap();
11337 assert_eq!(
11338 read(&receipt)["detail"],
11339 "active work or runnable task queue"
11340 );
11341 assert_eq!(read(&receipt)["version"], env!("CARGO_PKG_VERSION"));
11342 assert_eq!(read(&receipt)["auto_fold"], cfg.disk.auto_fold);
11343 std::fs::remove_file(home.join("service-ticks/daemon-disk-pressure")).unwrap();
11344 start_service(
11345 &home,
11346 &opts,
11347 &queue,
11348 &worktrees,
11349 "disk-pressure",
11350 Some(&cfg),
11351 false,
11352 )
11353 .await
11354 .unwrap();
11355 assert_eq!(
11356 read(&home.join("source-eviction-disk-pressure-dispatch.json"))["detail"],
11357 "no active work; idle housekeeping owns scan"
11358 );
11359 assert!(crate::worker::active(&home).unwrap().is_empty());
11360 }
11361
11362 #[tokio::test]
11363 async fn goal_observation_service_does_not_block_scheduler_decisions() {
11364 let dir = tempfile::tempdir().unwrap();
11365 let (opts, _, _, home, worktrees) = idle_loop(dir.path());
11366 let queue = Queue::at(home.join("queue"));
11367 let mut task = task();
11368 task.repo = opts.repo.clone();
11369 task.chat = Some("decision-chat".into());
11370 task.hold_machine(Some("waiting for a decision".into()));
11371 queue.put(&mut task).unwrap();
11372 let questions = Questions::at(home.join("questions"));
11373 let mut question = action_question(&task.id, ask::ChoiceAction::Done);
11374 question.node = crate::conduct::NODE.into();
11375 question.status = ask::QuestionStatus::Open;
11376 question.answer = None;
11377 question.answered_at = None;
11378 questions.put(&mut question).unwrap();
11379 questions
11380 .update(&question.id, |q| {
11381 q.answer(ask::Answer::Choice("resume で続行する".into()))
11382 })
11383 .unwrap();
11384
11385 let talks = crate::talk::Talks::at(home.join("talks"));
11386 let mut decision_chat = crate::talk::seeded_for_test("decision-chat", opts.repo.clone());
11387 decision_chat.pending = "Keep this unsent status question".into();
11388 talks.put(&mut decision_chat).unwrap();
11389 let mut talk = crate::talk::seeded_for_test("observing-chat", opts.repo.clone());
11390 talk.goals.push(serde_json::from_value(serde_json::json!({
11391 "id":"goal","purpose":"follow the retained job","scope":"one task",
11392 "condition":{"description":"land the result","kind":"runs_merged"},
11393 "state":"runnable","step":"reading the forge","source_turn":0,"owner_input":"land this job",
11394 "tasks":[],"runs":[],"watches":[],"evidence":"","wake":1,"handled":0,
11395 "started":1,"wakes":1,"last_checked":null,"fingerprint":""
11396 })).unwrap());
11397 talks.put(&mut talk).unwrap();
11398
11399 let directory = home.join("workers/jobs/abcdef");
11402 std::fs::create_dir_all(&directory).unwrap();
11403 let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
11404 crate::pr_head::try_lock_file(&lease).unwrap();
11405 let mut job = crate::worker::Job {
11406 id: "abcdef".into(),
11407 sequence: 1,
11408 kind: "daemon-service".into(),
11409 key: "service:daemon-chat-goals".into(),
11410 payload: serde_json::Value::Null,
11411 generation: "fixture".into(),
11412 version: None,
11413 status: crate::worker::Status::Running,
11414 result: None,
11415 pid: Some(std::process::id()),
11416 created_at: Timestamp::now().as_second() as u64,
11417 finished_at: None,
11418 };
11419 let record = directory.join("job.json");
11420 std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11421 let status = Arc::new(Mutex::new(Status::new()));
11422 let stop = Stop::new();
11423 let mut dispatch = Box::pin(poll(
11424 &opts,
11425 &queue,
11426 &status,
11427 &home,
11428 &worktrees,
11429 &stop,
11430 DispatchLimits {
11431 max_concurrent: 1,
11432 pause_for_interrupts: false,
11433 recovery_cfg: None,
11434 },
11435 ));
11436 std::future::poll_fn(|cx| {
11437 assert!(dispatch.as_mut().poll(cx).is_pending());
11438 std::task::Poll::Ready(())
11439 })
11440 .await;
11441 assert!(lock(&status).polls > 0);
11442 let saved = queue.get(&task.id).unwrap();
11443 assert_eq!(saved.status, TaskStatus::Done);
11444 assert!(saved.action_applied(&question.id));
11445 assert!(
11446 talks
11447 .get("decision-chat")
11448 .unwrap()
11449 .pending
11450 .contains("Keep this unsent status question")
11451 );
11452 let goal = talks.get(&talk.id).unwrap().goals.remove(0);
11453 assert_eq!(goal.state, crate::chat_goal::State::Runnable);
11454 assert_eq!(
11455 goal.started,
11456 Some(1),
11457 "only the observation worker may reconcile its goal"
11458 );
11459 assert_eq!(crate::worker::active(&home).unwrap()[0].id, job.id);
11460
11461 stop.stop();
11462 dispatch.await.unwrap();
11463 job.status = crate::worker::Status::Finished;
11464 std::fs::write(record, serde_json::to_vec(&job).unwrap()).unwrap();
11465 drop(lease);
11466 }
11467
11468 #[test]
11469 fn a_stop_is_idempotent_and_once_set_stays_set() {
11470 let stop = Stop::new();
11471 assert!(!stop.stopped());
11472
11473 stop.stop();
11474 assert!(stop.stopped());
11475 stop.stop();
11476 assert!(stop.stopped(), "a second stop is not a toggle");
11477
11478 let shared = stop.clone();
11479 assert!(
11480 shared.stopped(),
11481 "a clone is the same stop; that is how the loop and its caller share one"
11482 );
11483 }
11484
11485 #[tokio::test]
11486 async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
11487 for operation in ["conductor", "maintenance", "housekeeping"] {
11488 let dir = tempfile::tempdir().unwrap();
11489 let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
11490 opts.once = true;
11491 opts.poll = Duration::from_millis(1);
11492 let mut task = task();
11493 task.runs.push("fixture-run".into());
11494 queue.put(&mut task).unwrap();
11495 let claim = queue.claim(&task.id).unwrap();
11496
11497 let directory = home.join("workers/jobs/abcdef");
11500 std::fs::create_dir_all(&directory).unwrap();
11501 let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
11502 crate::pr_head::try_lock_file(&lease).unwrap();
11503 let mut job = crate::worker::Job {
11504 id: "abcdef".into(),
11505 sequence: 1,
11506 kind: "daemon-service".into(),
11507 key: format!("service:daemon-{operation}"),
11508 payload: serde_json::Value::Null,
11509 generation: "fixture".into(),
11510 version: None,
11511 status: crate::worker::Status::Running,
11512 result: None,
11513 pid: Some(std::process::id()),
11514 created_at: Timestamp::now().as_second() as u64,
11515 finished_at: None,
11516 };
11517 let record = directory.join("job.json");
11518 std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11519
11520 let status = Arc::new(Mutex::new(Status::new()));
11521 let stop = Stop::new();
11522 let mut drain = Box::pin(poll(
11523 &opts,
11524 &queue,
11525 &status,
11526 &home,
11527 &worktrees,
11528 &stop,
11529 DispatchLimits {
11530 max_concurrent: 1,
11531 pause_for_interrupts: false,
11532 recovery_cfg: None,
11533 },
11534 ));
11535 std::future::poll_fn(|cx| {
11536 use std::future::Future;
11537 assert!(
11538 drain.as_mut().poll(cx).is_pending(),
11539 "--once must wait for {operation} to release its queue claim"
11540 );
11541 std::task::Poll::Ready(())
11542 })
11543 .await;
11544 assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
11545
11546 let questions = Questions::at(home.join("questions"));
11549 let mut q = action_question("fixture-run", ask::ChoiceAction::Done);
11550 questions.put(&mut q).unwrap();
11551 drop(claim);
11552 let expired =
11556 serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
11557 for service in [operation, "housekeeping"] {
11558 std::fs::write(
11559 home.join("service-ticks").join(format!("daemon-{service}")),
11560 &expired,
11561 )
11562 .unwrap();
11563 }
11564 job.status = crate::worker::Status::Finished;
11565 std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11566 drop(lease);
11567 tokio::time::timeout(Duration::from_secs(2), drain)
11568 .await
11569 .expect("the settled service must allow the drain to finish")
11570 .unwrap();
11571 let after = queue.get(&task.id).unwrap();
11572 assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
11573 assert!(after.action_applied(&q.id));
11574 for service in [operation, "housekeeping"] {
11575 assert_eq!(
11576 std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
11577 .unwrap(),
11578 expired,
11579 "the final once rescan must not restart {service}"
11580 );
11581 }
11582 }
11583 }
11584
11585 #[test]
11586 fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
11587 let stop = Stop::new();
11588 stop.busy.store(1, Ordering::SeqCst);
11589 assert!(
11590 !stop.finishing(),
11591 "a busy loop nobody has asked to stop is just running"
11592 );
11593
11594 stop.stop();
11595 assert!(
11596 stop.finishing(),
11597 "a stop asked for mid-run has not landed until the run is settled"
11598 );
11599
11600 stop.busy.store(0, Ordering::SeqCst);
11601 assert!(
11602 !stop.finishing(),
11603 "once the run is settled the stop has landed and there is nothing to finish"
11604 );
11605 }
11606
11607 #[test]
11608 fn finishing_stays_true_until_the_last_of_several_runs_exits() {
11609 let stop = Stop::new();
11610 stop.busy.store(2, Ordering::SeqCst);
11611 stop.stop();
11612 assert!(stop.finishing(), "two runs still in flight");
11613
11614 stop.busy.store(1, Ordering::SeqCst);
11615 assert!(
11616 stop.finishing(),
11617 "one run finished, but a sibling is still working"
11618 );
11619
11620 stop.busy.store(0, Ordering::SeqCst);
11621 assert!(
11622 !stop.finishing(),
11623 "the last run out is what actually lands the stop"
11624 );
11625 }
11626
11627 #[tokio::test]
11628 async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
11629 let dir = tempfile::tempdir().unwrap();
11630 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
11631 let stop = Stop::new();
11632 stop.stop();
11633
11634 let began = std::time::Instant::now();
11635 tokio::time::timeout(
11636 Duration::from_secs(2),
11637 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
11638 )
11639 .await
11640 .expect("a stopped loop must return, not sit out its poll interval")
11641 .expect("the loop's own setup and teardown must not fail");
11642 assert!(
11643 began.elapsed() < opts.poll,
11644 "returned only after {:?}, which is a poll interval, not a stop",
11645 began.elapsed()
11646 );
11647 }
11648
11649 #[tokio::test]
11650 async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
11651 let dir = tempfile::tempdir().unwrap();
11652 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
11653 let stop = Stop::new();
11654
11655 let asker = {
11658 let stop = stop.clone();
11659 tokio::spawn(async move {
11660 tokio::time::sleep(Duration::from_millis(20)).await;
11661 stop.stop();
11662 })
11663 };
11664
11665 let began = std::time::Instant::now();
11666 tokio::time::timeout(
11667 Duration::from_secs(2),
11668 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
11669 )
11670 .await
11671 .expect("a stop asked for while idle must wake the wait")
11672 .expect("the loop's own setup and teardown must not fail");
11673 asker.await.unwrap();
11674 assert!(
11675 began.elapsed() < opts.poll,
11676 "returned only after {:?}, so the stop waited on the sleep",
11677 began.elapsed()
11678 );
11679 }
11680
11681 #[tokio::test]
11682 async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
11683 let dir = tempfile::tempdir().unwrap();
11684 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
11685 let stop = Stop::new();
11686 stop.stop();
11687
11688 tokio::time::timeout(
11689 Duration::from_secs(2),
11690 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
11691 )
11692 .await
11693 .expect("a stopped loop must return")
11694 .expect("the loop's own setup and teardown must not fail");
11695
11696 assert!(
11697 home.is_dir(),
11698 "the loop did publish a status file, so its removal is the teardown and not an absence"
11699 );
11700 assert!(
11701 !status_file.exists(),
11702 "a stopped loop clears its status file"
11703 );
11704 assert!(
11705 read_status(&home).is_none(),
11706 "a reader must see no daemon at all, not a heartbeat that merely stopped"
11707 );
11708 }
11709
11710 #[tokio::test]
11711 async fn housekeeping_worker_settles_questions_without_a_scheduler() {
11712 let dir = tempfile::tempdir().unwrap();
11713 let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
11714
11715 let mut settled = RunState::new(
11716 dir.path().join("repo"),
11717 "main".to_owned(),
11718 "abc1234".to_owned(),
11719 "fixture".to_owned(),
11720 Config::default(),
11721 );
11722 settled.status = RunStatus::Ready;
11723 let run_dir = home.join("runs").join(&settled.id);
11724 std::fs::create_dir_all(&run_dir).unwrap();
11725 std::fs::write(
11726 run_dir.join("run.json"),
11727 serde_json::to_string_pretty(&settled).unwrap(),
11728 )
11729 .unwrap();
11730 let questions = Questions::at(home.join("questions"));
11731 let mut question = ask::Question::new(
11732 settled.id.clone(),
11733 "review".to_owned(),
11734 "reviewer-1".to_owned(),
11735 "Continue?".to_owned(),
11736 String::new(),
11737 Vec::new(),
11738 );
11739 questions.put(&mut question).unwrap();
11740
11741 run_service_worker(
11742 &home,
11743 serde_json::to_value(ServiceWorker {
11744 opts,
11745 queue: queue.root().to_path_buf(),
11746 worktrees_root: worktrees,
11747 operation: "housekeeping".to_owned(),
11748 })
11749 .unwrap(),
11750 )
11751 .await
11752 .unwrap();
11753
11754 assert_eq!(
11755 questions.get(&question.id).unwrap().status,
11756 ask::QuestionStatus::Abandoned,
11757 "the independent housekeeping worker settles ended-run questions"
11758 );
11759 }
11760
11761 #[test]
11762 fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
11763 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
11764
11765 assert!(
11766 cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
11767 "never checked before: due at once"
11768 );
11769
11770 let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
11771 assert!(
11772 !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
11773 "well inside the interval: not due yet"
11774 );
11775
11776 let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
11777 assert!(
11778 !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
11779 "exactly at the edge: not yet due, same convention as `clean::due`"
11780 );
11781
11782 let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
11783 assert!(
11784 cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
11785 "past the interval: due again"
11786 );
11787 }
11788
11789 fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
11794 let config = dir.join("magi.toml");
11795 std::fs::write(
11801 &config,
11802 format!(
11803 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
11804 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
11805 cache_dir.display()
11806 ),
11807 )
11808 .unwrap();
11809 Opts {
11810 config: Some(config),
11811 repo: dir.join("repo"),
11812 ..Opts::default()
11813 }
11814 }
11815
11816 #[tokio::test]
11817 async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
11818 let dir = tempfile::tempdir().unwrap();
11819 let home = dir.path().join("home");
11820 let cache_dir = dir.path().join("cache");
11821 std::fs::create_dir_all(&cache_dir).unwrap();
11822 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
11823 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
11824
11825 let running = Stop::new();
11828 let mut last_checked = None;
11829 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
11830 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
11831 .await;
11832 assert_eq!(
11833 crate::disk::dir_size(&cache_dir),
11834 0,
11835 "over the cap on the first check ever: pruned at once, no idle queue required"
11836 );
11837 assert_eq!(last_checked, Some(t0));
11838
11839 std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
11841 let too_soon = t0 + jiff::SignedDuration::from_secs(1);
11842 maybe_prune_cache_between_runs(
11843 &opts.repo,
11844 &opts,
11845 &home,
11846 &running,
11847 &mut last_checked,
11848 too_soon,
11849 )
11850 .await;
11851 assert_eq!(
11852 crate::disk::dir_size(&cache_dir),
11853 10,
11854 "too soon since the last check: left alone rather than rescanned every call"
11855 );
11856 assert_eq!(
11857 last_checked,
11858 Some(t0),
11859 "an idle check does not reset the clock"
11860 );
11861
11862 let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
11864 maybe_prune_cache_between_runs(
11865 &opts.repo,
11866 &opts,
11867 &home,
11868 &running,
11869 &mut last_checked,
11870 due_again,
11871 )
11872 .await;
11873 assert_eq!(
11874 crate::disk::dir_size(&cache_dir),
11875 0,
11876 "due again: pruned back under the cap"
11877 );
11878 }
11879
11880 #[tokio::test]
11888 async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
11889 let dir = tempfile::tempdir().unwrap();
11890 let home = dir.path().join("home");
11891 let cache_dir = dir.path().join("cache");
11892 std::fs::create_dir_all(&cache_dir).unwrap();
11893 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
11894 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
11895
11896 let stop = Stop::new();
11897 stop.stop();
11898 assert!(
11899 !stop.finishing(),
11900 "no run is in flight at a between-runs boundary, so nothing else \
11901 would tell the operator this stop had not taken effect yet"
11902 );
11903
11904 let mut last_checked = None;
11905 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
11906 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
11907 .await;
11908 assert_eq!(
11909 crate::disk::dir_size(&cache_dir),
11910 10,
11911 "over its cap, and due for the first check ever, but a stop outranks \
11912 it: the cap is a standing policy the next start measures again"
11913 );
11914 assert_eq!(
11915 last_checked, None,
11916 "a check that never happened must not claim the interval"
11917 );
11918 }
11919
11920 #[tokio::test]
11923 async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
11924 let dir = tempfile::tempdir().unwrap();
11925 let cache_dir = dir.path().join("cache");
11926 std::fs::create_dir_all(&cache_dir).unwrap();
11927 std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
11928
11929 let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
11930 opts.poll = Duration::from_millis(20);
11931 opts.max_attempts = 1_000;
11932
11933 let queue = Queue::at(dir.path().join("queue"));
11934 for i in 0..128 {
11935 let mut task = Task::new(
11936 format!("queued work {i}"),
11937 format!("queued work {i}"),
11938 opts.repo.clone(),
11939 Source::Human,
11940 );
11941 queue.put(&mut task).unwrap();
11942 }
11943
11944 let home = dir.path().join("home");
11945 let worktrees = dir.path().join("wt");
11946 run_service_worker(
11947 &home,
11948 serde_json::to_value(ServiceWorker {
11949 opts,
11950 queue: queue.root().to_path_buf(),
11951 worktrees_root: worktrees,
11952 operation: "cache".to_owned(),
11953 })
11954 .unwrap(),
11955 )
11956 .await
11957 .unwrap();
11958 let after = queue.list();
11959 assert_eq!(after.len(), 128);
11960 assert!(
11961 after
11962 .iter()
11963 .all(|task| task.status.runnable() && task.attempts == 0)
11964 );
11965
11966 assert_eq!(
11967 crate::disk::dir_size(&cache_dir),
11968 0,
11969 "an oversized cache must not be left to grow unboundedly just because the \
11970 queue kept the loop busy the whole time"
11971 );
11972 }
11973
11974 #[test]
11975 fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
11976 let dir = tempfile::tempdir().unwrap();
11977 let queue = Queue::at(dir.path().join("queue"));
11978 let questions = Questions::at(dir.path().join("questions"));
11979 let mut task = task();
11980 queue.put(&mut task).unwrap();
11981
11982 let mut task_question = ask::Question::new(
11983 task.id.clone(),
11984 crate::conduct::NODE.to_owned(),
11985 "conduct".to_owned(),
11986 "Which backend?".to_owned(),
11987 String::new(),
11988 Vec::new(),
11989 );
11990 questions.put(&mut task_question).unwrap();
11991 task.block(vec![task_question.id.clone()], None);
11992 queue.put(&mut task).unwrap();
11993
11994 let mut run_question = ask::Question::new(
11995 "20260101-000000-run1".to_owned(),
11996 "review".to_owned(),
11997 "reviewer-1".to_owned(),
11998 "Run question".to_owned(),
11999 String::new(),
12000 Vec::new(),
12001 );
12002 questions.put(&mut run_question).unwrap();
12003
12004 let mut coincidental = ask::Question::new(
12009 task.id.clone(),
12010 "review".to_owned(),
12011 "reviewer-1".to_owned(),
12012 "Unrelated review question".to_owned(),
12013 String::new(),
12014 Vec::new(),
12015 );
12016 questions.put(&mut coincidental).unwrap();
12017
12018 reconcile_task_questions(&queue, &questions);
12019 assert!(questions.get(&task_question.id).unwrap().status.open());
12020 assert!(questions.get(&run_question.id).unwrap().status.open());
12021 assert!(questions.get(&coincidental.id).unwrap().status.open());
12022
12023 task.release();
12024 queue.put(&mut task).unwrap();
12025 reconcile_task_questions(&queue, &questions);
12026 assert_eq!(
12027 questions.get(&task_question.id).unwrap().status,
12028 ask::QuestionStatus::Abandoned
12029 );
12030 assert!(
12031 questions.get(&run_question.id).unwrap().status.open(),
12032 "run questions remain the run janitor's responsibility"
12033 );
12034 assert!(
12035 questions.get(&coincidental.id).unwrap().status.open(),
12036 "a non-conductor question must not be abandoned just because its \
12037 run id coincides with a task id"
12038 );
12039 }
12040
12041 #[test]
12042 fn a_freshly_started_running_task_is_never_stalled() {
12043 let dir = tempfile::tempdir().unwrap();
12044 let mut t = task();
12045 t.start("run-1".to_owned());
12046 assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
12049 }
12050
12051 #[test]
12052 fn a_long_running_task_with_no_live_daemon_is_stalled() {
12053 let dir = tempfile::tempdir().unwrap();
12054 let mut t = task();
12055 t.start("run-1".to_owned());
12056 t.updated_at = Timestamp::now()
12057 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
12058 assert!(is_stalled(&t, dir.path(), Timestamp::now()));
12059 assert_eq!(
12060 stalled_tasks(
12061 &Queue::at(dir.path().join("q")),
12062 dir.path(),
12063 Timestamp::now()
12064 )
12065 .len(),
12066 0,
12067 "the task was never written to this queue"
12068 );
12069 }
12070
12071 #[test]
12072 fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
12073 let dir = tempfile::tempdir().unwrap();
12074 let mut t = task();
12075 t.id = "20260903-080340-0167".to_owned();
12076 t.start("20260903-080619-01c2".to_owned());
12077 t.updated_at = Timestamp::now()
12078 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
12079
12080 let mut status = Status::new();
12081 status.current = vec![Current {
12082 worker: None,
12083 task: t.id.clone(),
12084 run: "20260903-080619-01c2".to_owned(),
12085 }];
12086 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12087
12088 assert!(
12089 !is_stalled(&t, dir.path(), Timestamp::now()),
12090 "a live daemon's own heartbeat rules out stalled, however long the task has run"
12091 );
12092 }
12093
12094 fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
12098 let path = queue.path_of(id);
12099 let body = std::fs::read_to_string(&path).unwrap();
12100 let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
12101 let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
12102 v["updated_at"] = serde_json::Value::String(old.to_string());
12103 std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
12104 }
12105
12106 #[test]
12107 fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
12108 let dir = tempfile::tempdir().unwrap();
12121 let queue = Queue::at(dir.path().join("queue"));
12122 let home = dir.path().join("home");
12123
12124 let mut t = task();
12125 t.id = "20260101-000001-lock".to_owned();
12126 t.start("run-1".to_owned());
12127 queue.put(&mut t).unwrap();
12128 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
12129 std::fs::write(
12130 dir.path().join("queue").join(format!("{}.lock", t.id)),
12131 "not a pid",
12132 )
12133 .unwrap();
12134
12135 let now = Timestamp::now();
12136 assert!(
12137 reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
12138 "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
12139 and reclaim must leave the task alone"
12140 );
12141 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
12142
12143 let stalled = stalled_tasks(&queue, &home, now);
12144 assert_eq!(
12145 stalled.len(),
12146 1,
12147 "reclaim's inability to claim it yet must not hide it from the conductor"
12148 );
12149 assert_eq!(stalled[0].id, t.id);
12150 }
12151
12152 #[test]
12153 fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
12154 let dir = tempfile::tempdir().unwrap();
12155 crate::run::set_home(dir.path().join("run-home"));
12156 let queue = Queue::at(dir.path().join("queue"));
12157 let home = dir.path().join("home");
12158 let questions = Questions::at(dir.path().join("questions"));
12159
12160 let mut t = task();
12161 t.id = "20260101-000003-dead".to_owned();
12162 t.start("missing-run".to_owned());
12163 queue.put(&mut t).unwrap();
12164 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
12165
12166 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
12169 assert_eq!(
12170 stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
12171 [&t.id]
12172 );
12173 assert_eq!(
12174 reclaim_orphaned_running(&queue, 2, &Default::default()),
12175 [t.id.clone()]
12176 );
12177 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12178
12179 crate::conduct::apply(
12182 &queue,
12183 &questions,
12184 &crate::conduct::Verdict {
12185 decisions: vec![crate::conduct::Decision {
12186 id: t.id.clone(),
12187 recovery: Some(crate::conduct::Recovery::Requeue),
12188 ..crate::conduct::Decision::default()
12189 }],
12190 },
12191 )
12192 .unwrap();
12193 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
12194 }
12195
12196 #[test]
12197 fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
12198 let dir = tempfile::tempdir().unwrap();
12199 let queue = Queue::at(dir.path().join("queue"));
12200 let home = dir.path().join("home");
12201
12202 let mut fresh = task();
12203 fresh.id = "20260101-000001-aaaa".to_owned();
12204 fresh.start("run-1".to_owned());
12205 queue.put(&mut fresh).unwrap();
12206
12207 let mut old = task();
12208 old.id = "20260101-000002-bbbb".to_owned();
12209 old.start("run-2".to_owned());
12210 queue.put(&mut old).unwrap();
12211 backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
12212
12213 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
12214 assert_eq!(stalled.len(), 1);
12215 assert_eq!(stalled[0].id, old.id);
12216 }
12217
12218 #[test]
12219 fn queued_and_finished_task_views_partition_by_status() {
12220 let dir = tempfile::tempdir().unwrap();
12221 let queue = Queue::at(dir.path().join("queue"));
12222
12223 let mut queued = task();
12224 queued.id = "20260101-000001-aaaa".to_owned();
12225 queue.put(&mut queued).unwrap();
12226
12227 let mut failed = task();
12228 failed.id = "20260101-000002-bbbb".to_owned();
12229 failed.start("run-1".to_owned());
12230 failed.fail("gate red", 5);
12231 queue.put(&mut failed).unwrap();
12232
12233 let mut held = task();
12234 held.id = "20260101-000003-cccc".to_owned();
12235 held.hold_machine(None);
12236 queue.put(&mut held).unwrap();
12237
12238 let mut running = task();
12239 running.id = "20260101-000004-dddd".to_owned();
12240 running.start("run-2".to_owned());
12241 queue.put(&mut running).unwrap();
12242
12243 let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
12244 assert_eq!(queued_ids, [queued.id.clone()]);
12245
12246 let mut finished_ids: Vec<String> =
12247 finished_tasks(&queue).into_iter().map(|t| t.id).collect();
12248 finished_ids.sort_unstable();
12249 let mut want = vec![failed.id.clone(), held.id.clone()];
12250 want.sort_unstable();
12251 assert_eq!(finished_ids, want);
12252 }
12253
12254 #[test]
12255 fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
12256 for short in [false, true] {
12257 let dir = tempfile::tempdir().unwrap();
12258 let queue = Queue::at(dir.path().join("queue"));
12259 let questions = ask::Questions::at(dir.path().join("questions"));
12260 let mut running = task();
12261 running.id = "20261013-192213-feb2".into();
12262 running.start("existing-run".into());
12263 queue.put(&mut running).unwrap();
12264 let mut middle = task();
12265 middle.id = "20261013-193611-ca5b".into();
12266 middle.block(
12267 vec![if short {
12268 "feb2".into()
12269 } else {
12270 running.id.clone()
12271 }],
12272 None,
12273 );
12274 queue.put(&mut middle).unwrap();
12275 let mut waiting = task();
12276 waiting.id = "20261013-202849-ee37".into();
12277 waiting.block(
12278 vec![if short {
12279 "ca5b".into()
12280 } else {
12281 middle.id.clone()
12282 }],
12283 Some("wait for implementation".into()),
12284 );
12285 queue.put(&mut waiting).unwrap();
12286 assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
12287 let inv = crate::blockers::Inventory::load(&queue, &questions);
12288 assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
12289 assert!(inv.stuck().is_empty());
12290 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12291 assert!(report.quarantined.is_empty());
12292 assert!(report.asked.is_empty());
12293 resolve_blockers(&queue, &questions);
12294 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12295 assert!(questions.list().is_empty());
12296 running.succeed();
12299 queue.put(&mut running).unwrap();
12300 resolve_blockers(&queue, &questions);
12301 assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
12302 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12303 middle = queue.get(&middle.id).unwrap();
12304 middle.succeed();
12305 queue.put(&mut middle).unwrap();
12306 resolve_blockers(&queue, &questions);
12307 let after = queue.get(&waiting.id).unwrap();
12308 assert_eq!(after.status, TaskStatus::Queued);
12309 assert!(after.blocked_by.is_empty());
12310 assert_eq!(after.instruction, waiting.instruction);
12311 }
12312 }
12313
12314 #[test]
12315 fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
12316 for future_schema in [false, true] {
12317 let name = "20261013-193611-ca5b";
12318 let mut future = task();
12319 future.id = name.into();
12320 future.schema = crate::queue::SCHEMA + 1;
12321 let contents = if future_schema {
12322 serde_json::to_string(&future).unwrap()
12323 } else {
12324 "corrupt".into()
12325 };
12326 let dir = tempfile::tempdir().unwrap();
12327 let queue = Queue::at(dir.path().join("queue"));
12328 let questions = ask::Questions::at(dir.path().join("questions"));
12329 let mut waiting = task();
12330 waiting.id = "20261013-202849-ee37".into();
12331 waiting.block(vec!["ca5b".into()], None);
12332 queue.put(&mut waiting).unwrap();
12333 std::fs::write(queue.path_of(name), contents).unwrap();
12334 assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
12335 assert!(
12336 crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
12337 );
12338 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12339 assert!(report.asked.is_empty());
12340 resolve_blockers(&queue, &questions);
12341 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12342 assert!(questions.list().is_empty());
12343 }
12344 let dir = tempfile::tempdir().unwrap();
12345 let queue = Queue::at(dir.path().join("queue"));
12346 let questions = ask::Questions::at(dir.path().join("questions"));
12347 let mut waiting = task();
12348 waiting.id = "20261013-202849-ee37".into();
12349 waiting.block(vec!["ca5b".into()], None);
12350 queue.put(&mut waiting).unwrap();
12351 let mut done = task();
12352 done.id = "20261013-193611-ca5b".into();
12353 done.succeed();
12354 queue.put(&mut done).unwrap();
12355 std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
12358 assert!(queue.get("ca5b").is_err());
12359 assert_eq!(
12360 crate::queue::dependency(&queue, &questions, "ca5b"),
12361 crate::queue::Dependency::Ambiguous
12362 );
12363 resolve_blockers(&queue, &questions);
12364 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12365 assert!(report.asked.is_empty());
12366 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12367 assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
12368 }
12369
12370 #[test]
12371 fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
12372 for held in [false, true] {
12373 for question in [false, true] {
12374 for reference in ["ca5b", "20261013-193611-ca5b"] {
12375 let dir = tempfile::tempdir().unwrap();
12376 let queue = Queue::at(dir.path().join("queue"));
12377 let questions = ask::Questions::at(dir.path().join("questions"));
12378 let mut prerequisite = task();
12379 prerequisite.id = "20261013-193611-ca5b".into();
12380 prerequisite.start("existing-run".into());
12381 queue.put(&mut prerequisite).unwrap();
12382 let mut waiting = task();
12383 waiting.id = "20261013-202849-ee37".into();
12384 if held {
12385 waiting.hold_machine(Some("waiting for separate consent".into()));
12386 }
12387 queue.put(&mut waiting).unwrap();
12388 let reason = "Deleting saved data requires separate owner consent";
12389 crate::conduct::apply(
12390 &queue,
12391 &questions,
12392 &crate::conduct::Verdict {
12393 decisions: vec![crate::conduct::Decision {
12394 id: waiting.id.clone(),
12395 blocked_by: vec![reference.into()],
12396 question: question.then(|| "May the saved data be deleted?".into()),
12397 recovery: (!question).then_some(crate::conduct::Recovery::Hold),
12398 reason: Some(reason.into()),
12399 ..crate::conduct::Decision::default()
12400 }],
12401 },
12402 )
12403 .unwrap();
12404 let before = queue.get(&waiting.id).unwrap();
12405 if question {
12406 assert_eq!(before.status, TaskStatus::Blocked);
12407 let q = questions.get(&before.blocked_by[0]).unwrap();
12408 assert_eq!(q.summary, "May the saved data be deleted?");
12409 assert!(q.status.open());
12410 } else {
12411 assert_eq!(before.status, TaskStatus::Held);
12412 let recorded_reason = before.hold_reason.as_deref().unwrap();
12413 assert!(recorded_reason.starts_with(reason));
12414 if held {
12415 assert!(recorded_reason.contains("waiting for separate consent"));
12416 }
12417 }
12418 prerequisite.succeed();
12419 queue.put(&mut prerequisite).unwrap();
12420 resolve_blockers(&queue, &questions);
12421 let after = queue.get(&waiting.id).unwrap();
12422 assert_eq!(after.status, before.status);
12423 assert_eq!(after.blocked_by, before.blocked_by);
12424 assert_eq!(after.hold_reason, before.hold_reason);
12425 assert_eq!(after.instruction, waiting.instruction);
12426 if question {
12427 assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
12428 }
12429 assert!(
12430 queue.next_runnable().is_none(),
12431 "dependency completion is not consent"
12432 );
12433 }
12434 }
12435 }
12436 }
12437
12438 #[test]
12439 fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
12440 let dir = tempfile::tempdir().unwrap();
12441 let queue = Queue::at(dir.path().join("queue"));
12442 let questions = ask::Questions::at(dir.path().join("questions"));
12443
12444 let mut dep = task();
12445 dep.id = "20260101-000001-dep0".to_owned();
12446 dep.succeed();
12447 queue.put(&mut dep).unwrap();
12448
12449 let mut still_going = task();
12450 still_going.id = "20260101-000002-dep1".to_owned();
12451 queue.put(&mut still_going).unwrap();
12452
12453 let mut blocked = task();
12454 blocked.id = "20260101-000003-main".to_owned();
12455 blocked.block(
12456 vec![dep.id.clone(), still_going.id.clone()],
12457 Some("waits on both".to_owned()),
12458 );
12459 queue.put(&mut blocked).unwrap();
12460
12461 resolve_blockers(&queue, &questions);
12462
12463 let after = queue.get(&blocked.id).unwrap();
12464 assert_eq!(
12465 after.status,
12466 TaskStatus::Blocked,
12467 "one dependency is still outstanding"
12468 );
12469 assert_eq!(after.blocked_by, [still_going.id.clone()]);
12470 }
12471
12472 #[test]
12473 fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
12474 let dir = tempfile::tempdir().unwrap();
12475 let queue = Queue::at(dir.path().join("queue"));
12476 let questions = ask::Questions::at(dir.path().join("questions"));
12477
12478 let mut q = crate::ask::Question::new(
12479 "20260101-000001-main".to_owned(),
12480 crate::conduct::NODE.to_owned(),
12481 "conduct".to_owned(),
12482 "Which backend?".to_owned(),
12483 String::new(),
12484 Vec::new(),
12485 );
12486 questions.put(&mut q).unwrap();
12487 q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
12488 .unwrap();
12489 questions.put(&mut q).unwrap();
12490
12491 let mut blocked = task();
12492 blocked.id = "20260101-000001-main".to_owned();
12493 blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
12494 queue.put(&mut blocked).unwrap();
12495
12496 resolve_blockers(&queue, &questions);
12497
12498 let after = queue.get(&blocked.id).unwrap();
12499 assert_eq!(
12500 after.status,
12501 TaskStatus::Queued,
12502 "the only blocker resolved"
12503 );
12504 assert_eq!(after.answers.len(), 1);
12505 assert_eq!(after.answers[0].question, "Which backend?");
12506 assert_eq!(after.answers[0].answer, "SQLite");
12507
12508 let instruction = instruction_for(&after);
12510 assert!(instruction.contains("Which backend?"));
12511 assert!(instruction.contains("SQLite"));
12512 }
12513
12514 #[test]
12515 fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
12516 let dir = tempfile::tempdir().unwrap();
12517 let queue = Queue::at(dir.path().join("queue"));
12518 let questions = ask::Questions::at(dir.path().join("questions"));
12519
12520 let mut q = crate::ask::Question::new(
12521 "20260101-000001-main".to_owned(),
12522 crate::conduct::NODE.to_owned(),
12523 "conduct".to_owned(),
12524 "Is the setup done?".to_owned(),
12525 String::new(),
12526 Vec::new(),
12527 );
12528 q.abandon("no answer within 60s of asking");
12529 questions.put(&mut q).unwrap();
12530
12531 let mut blocked = task();
12532 blocked.id = "20260101-000001-main".to_owned();
12533 blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
12534 queue.put(&mut blocked).unwrap();
12535
12536 resolve_blockers(&queue, &questions);
12537
12538 let after = queue.get(&blocked.id).unwrap();
12539 assert_eq!(
12540 after.status,
12541 TaskStatus::Held,
12542 "never left blocked on nothing"
12543 );
12544 assert!(!after.operator_held(), "a machine hold, for triage");
12545 assert!(
12546 after
12547 .hold_reason
12548 .as_deref()
12549 .unwrap_or_default()
12550 .contains("went unanswered")
12551 );
12552 }
12553
12554 #[test]
12555 fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
12556 let dir = tempfile::tempdir().unwrap();
12562 let queue = Queue::at(dir.path().join("queue"));
12563 let questions = ask::Questions::at(dir.path().join("questions"));
12564
12565 let mut q = crate::ask::Question::new(
12566 "20260101-000001-main".to_owned(),
12567 crate::conduct::NODE.to_owned(),
12568 "conduct".to_owned(),
12569 "How should this be handled?".to_owned(),
12570 String::new(),
12571 Vec::new(),
12572 );
12573 questions.put(&mut q).unwrap();
12574 q.answer(crate::ask::Answer::Text(
12575 "leave it held, a human will look at it later".to_owned(),
12576 ))
12577 .unwrap();
12578 questions.put(&mut q).unwrap();
12579
12580 let mut held = task();
12581 held.id = "20260101-000001-main".to_owned();
12582 held.hold_machine(Some("out of attempts".to_owned()));
12583 held.block(vec![q.id.clone()], Some("what now?".to_owned()));
12584 queue.put(&mut held).unwrap();
12585
12586 resolve_blockers(&queue, &questions);
12587
12588 let after = queue.get(&held.id).unwrap();
12589 assert_eq!(after.status, TaskStatus::Held);
12590 assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
12591 assert_eq!(
12592 after.answers[0].answer,
12593 "leave it held, a human will look at it later"
12594 );
12595 }
12596
12597 #[test]
12598 fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
12599 let dir = tempfile::tempdir().unwrap();
12600 let queue = Queue::at(dir.path().join("queue"));
12601 let questions = ask::Questions::at(dir.path().join("questions"));
12602 let mut dep = task();
12603 dep.id = "20260101-000001-gone".to_owned();
12604 queue.put(&mut dep).unwrap();
12605 let mut blocked = task();
12606 blocked.id = "20260101-000003-main".to_owned();
12607 blocked.block(vec![dep.id.clone()], None);
12608 queue.put(&mut blocked).unwrap();
12609
12610 let claim = queue.claim(&blocked.id).unwrap();
12612 queue.remove(&dep.id, false, &questions).unwrap();
12613 drop(claim);
12614 resolve_blockers(&queue, &questions);
12615
12616 let after = queue.get(&blocked.id).unwrap();
12617 assert_eq!(after.status, TaskStatus::Queued);
12618 assert!(after.blocked_by.is_empty());
12619 }
12620
12621 #[test]
12622 fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
12623 let dir = tempfile::tempdir().unwrap();
12629 let queue = Queue::at(dir.path().join("queue"));
12630 let questions = ask::Questions::at(dir.path().join("questions"));
12631
12632 let mut still_going = task();
12633 still_going.id = "20260101-000002-dep1".to_owned();
12634 queue.put(&mut still_going).unwrap();
12635
12636 let mut blocked = task();
12637 blocked.id = "20260101-000003-main".to_owned();
12638 blocked.block(
12639 vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
12640 Some("waits on both".to_owned()),
12641 );
12642 queue.put(&mut blocked).unwrap();
12643
12644 resolve_blockers(&queue, &questions);
12645
12646 let after = queue.get(&blocked.id).unwrap();
12647 assert_eq!(
12648 after.status,
12649 TaskStatus::Held,
12650 "a missing dependency must not leave the task blocked forever"
12651 );
12652 assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
12653 assert!(after.blocked_by.is_empty());
12654 let reason = after.hold_reason.as_deref().unwrap_or_default();
12655 assert!(
12656 reason.contains("20260101-000001-gone"),
12657 "the missing id must be named so an operator can tell what happened: {reason}"
12658 );
12659 assert!(
12660 reason.contains(&still_going.id),
12661 "the still-valid dependency must not silently vanish from the record: {reason}"
12662 );
12663 }
12664
12665 #[test]
12666 fn instruction_for_is_unchanged_without_any_answers() {
12667 let t = task();
12668 assert_eq!(instruction_for(&t), t.instruction);
12669 }
12670
12671 #[test]
12672 fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
12673 let dir = tempfile::tempdir().unwrap();
12674 let q = Queue::at(dir.path().join("queue"));
12675 let src = dir.path().join("shot.png");
12676 std::fs::write(&src, "x").unwrap();
12677 let mut t = task();
12678 q.attach(&mut t, &[src]).unwrap();
12679 let paths = task_attachments(&q, &t).unwrap();
12680 assert_eq!(paths.len(), 1);
12681 assert!(paths[0].is_absolute() && paths[0].is_file());
12682 std::fs::remove_file(&paths[0]).unwrap();
12683 let err = task_attachments(&q, &t).unwrap_err().to_string();
12684 assert!(err.contains("shot.png"), "{err}");
12685 }
12686
12687 #[tokio::test]
12688 async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
12689 let dir = tempfile::tempdir().unwrap();
12690 let queue_path = dir.path().join("queue");
12691 let queue = Queue::at(queue_path.clone());
12692 let mut t = task();
12693 t.source = Source::Agent {
12694 run: "originating-chat".into(),
12695 node: crate::queue::CHAT_NODE.into(),
12696 };
12697 let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
12698 stage: "config-fetch",
12699 target: "origin/main".into(),
12700 });
12701 record_config_failure(&mut t, &fetch);
12702 t.hold_machine(Some(format!("{fetch:#}")));
12703 let fetch_key = t.chat_notice_due().unwrap();
12704 t.chat_notices.push(fetch_key.clone());
12705 queue.put(&mut t).unwrap();
12706
12707 let queue = Queue::at(queue_path);
12708 let mut t = queue.get(&t.id).unwrap();
12709 let a = dir.path().join("a.toml");
12710 let b = dir.path().join("b.toml");
12711 for (path, text, new_cause) in [
12712 (&a, "[graph", true),
12713 (&a, "[verify", false),
12714 (&a, "[graph]\nimplementers = 'invalid-type'", true),
12715 (&b, "[graph]\nimplementers = 'invalid-type'", true),
12716 ] {
12717 t.release_operator("test", None);
12718 std::fs::write(path, text).unwrap();
12719 let error = Config::discover_fetched(dir.path(), Some(path))
12720 .await
12721 .unwrap_err();
12722 record_config_failure(&mut t, &error);
12723 t.hold_machine(Some(format!("{error:#}")));
12724 let due = t.chat_notice_due();
12725 assert_eq!(due.is_some(), new_cause, "{error:#}");
12726 if let Some(key) = due {
12727 assert_ne!(key, fetch_key);
12728 t.chat_notices.push(key);
12729 }
12730 }
12731 t.succeed();
12732 assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
12733 }
12734
12735 #[test]
12736 fn different_missing_attachments_have_distinct_persisted_notice_causes() {
12737 let dir = tempfile::tempdir().unwrap();
12738 let queue_path = dir.path().join("queue");
12739 let queue = Queue::at(queue_path.clone());
12740 let mut t = task();
12741 t.source = crate::queue::Source::Agent {
12742 run: "originating-chat".into(),
12743 node: crate::queue::CHAT_NODE.into(),
12744 };
12745 let a = dir.path().join("a.png");
12746 let b = dir.path().join("b.png");
12747 std::fs::write(&a, "a").unwrap();
12748 std::fs::write(&b, "b").unwrap();
12749 queue.attach(&mut t, &[a, b]).unwrap();
12750 let paths = task_attachments(&queue, &t).unwrap();
12751 for path in &paths {
12752 std::fs::remove_file(path).unwrap();
12753 }
12754 let missing = task_attachments(&queue, &t).unwrap_err();
12755 t.attempts += 1;
12756 let reason = missing.to_string();
12757 t.fail_startup_target("startup-attachments", missing.name, reason, 1);
12758 let first = t.chat_notice_due().expect("first attachment notice");
12759 t.chat_notices.push(first.clone());
12760 queue.put(&mut t).unwrap();
12761
12762 let queue = Queue::at(queue_path.clone());
12763 let mut t = queue.get(&t.id).unwrap();
12764 assert!(t.chat_notice_due().is_none(), "restart does not replay");
12765 t.release_operator("test", None);
12766 t.attempts += 1;
12767 let missing = task_attachments(&queue, &t).unwrap_err();
12768 t.fail_startup_target(
12769 "startup-attachments",
12770 missing.name,
12771 "same missing attachment with regenerated wording",
12772 1,
12773 );
12774 assert!(t.chat_notice_due().is_none(), "same object stays quiet");
12775
12776 std::fs::write(&paths[0], "restored").unwrap();
12777 t.release_operator("test", None);
12778 t.attempts += 1;
12779 let missing = task_attachments(&queue, &t).unwrap_err();
12780 let reason = missing.to_string();
12781 t.fail_startup_target("startup-attachments", missing.name, reason, 1);
12782 let second = t
12783 .chat_notice_due()
12784 .expect("different attachment must notify");
12785 assert_ne!(first, second);
12786 assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
12787 }
12788
12789 #[test]
12790 fn resumed_instruction_is_unchanged_without_any_answers() {
12791 let t = task();
12792 assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
12793 }
12794
12795 #[test]
12796 fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
12797 let mut t = task();
12798 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
12799 let old = t.instruction.clone();
12803
12804 let refreshed = resumed_instruction(&old, &t);
12805 assert!(refreshed.starts_with(&old), "the original text is kept");
12806 assert!(refreshed.contains("Which backend?"));
12807 assert!(refreshed.contains("SQLite"));
12808 }
12809
12810 #[test]
12811 fn resumed_instruction_keeps_an_original_answers_heading() {
12812 let mut t = task();
12813 t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
12814 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
12815
12816 let refreshed = resumed_instruction(&t.instruction, &t);
12817
12818 assert!(
12819 refreshed.starts_with(&t.instruction),
12820 "an answers heading in the original instruction is not the appended block"
12821 );
12822 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
12823 assert!(refreshed.contains("Which backend?"));
12824 assert!(refreshed.contains("SQLite"));
12825
12826 let repeated = resumed_instruction(&refreshed, &t);
12827 assert_eq!(
12828 repeated, refreshed,
12829 "only the final appended block is refreshed"
12830 );
12831 }
12832
12833 #[test]
12834 fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
12835 let mut t = task();
12836 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
12837
12838 let once = resumed_instruction(&t.instruction, &t);
12842 let twice = resumed_instruction(&once, &t);
12843 assert_eq!(once, twice);
12844 assert_eq!(once.matches("Which backend?").count(), 1);
12845
12846 t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
12848 let refreshed = resumed_instruction(&once, &t);
12849 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
12850 assert!(refreshed.contains("Which backend?"));
12851 assert!(refreshed.contains("Which cache?"));
12852 }
12853
12854 #[test]
12855 fn prepare_instruction_covers_all_three_starters() {
12856 let mut t = task();
12857 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
12858
12859 assert_eq!(
12862 prepare_instruction(&Starter::Start, None, &t),
12863 Some(instruction_for(&t))
12864 );
12865
12866 let old = t.instruction.clone();
12869 assert_eq!(
12870 prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
12871 Some(resumed_instruction(&old, &t))
12872 );
12873
12874 assert_eq!(
12878 prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
12879 None
12880 );
12881 }
12882
12883 #[test]
12884 fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
12885 assert_eq!(
12886 choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
12887 Starter::Review("magi/eba2/A".to_owned())
12888 );
12889 }
12890
12891 #[test]
12892 fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
12893 assert_eq!(
12894 choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
12895 Starter::Start,
12896 "a vanished review branch must not fall back to resuming the old run either"
12897 );
12898 }
12899
12900 #[test]
12901 fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
12902 let mut t = task();
12903 t.start("old-run".to_owned());
12904 t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
12905 t.release();
12906 let branch = t.review_branch.take();
12907 assert_eq!(
12908 choose_starter(branch.as_deref(), true, Some("old-run")),
12909 Starter::Review("magi/eba2/A".to_owned()),
12910 "a review wins over resuming the old run"
12911 );
12912 }
12913
12914 #[test]
12915 fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
12916 assert_eq!(
12917 choose_starter(None, false, Some("some-run")),
12918 Starter::Resume("some-run".to_owned())
12919 );
12920 assert_eq!(choose_starter(None, false, None), Starter::Start);
12921 }
12922
12923 #[test]
12924 fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
12925 let mut released = task();
12926 released.start("stalled-run".to_owned());
12927 released.requeue();
12928 let unfinished = (!released.fresh_start)
12929 .then(|| Some("stalled-run".to_owned()))
12930 .flatten();
12931 assert_eq!(
12932 choose_starter(None, false, unfinished.as_deref()),
12933 Starter::Start,
12934 "release keeps run history but must not resume it"
12935 );
12936 assert_eq!(released.runs, ["stalled-run"]);
12937 }
12938
12939 #[test]
12940 fn landing_hold_receipt_survives_release_retry_and_checkpoint_removal() {
12941 let dir = tempfile::tempdir().unwrap();
12942 let queue = Queue::at(dir.path().join("queue"));
12943 let mut state = run_state(RunStatus::Blocked);
12944 state.merge_decision = Some(crate::merge_decision::Decision {
12945 question: "hold-inquiry".into(),
12946 target: crate::merge_decision::Target {
12947 pr: "https://example.test/pull/1".into(),
12948 head: "reviewed-head".into(),
12949 language: "en".into(),
12950 },
12951 choice: land::HOLD.into(),
12952 closed: false,
12953 replacement_run: None,
12954 replacement_pr: None,
12955 });
12956 let mut t = task();
12957 t.start(state.id.clone());
12958 settle_and_diagnose(
12959 &mut t,
12960 Verdict {
12961 status: RunStatus::Blocked,
12962 left_pr: true,
12963 quota_hit: false,
12964 parked: false,
12965 no_viable_candidates: false,
12966 },
12967 "held",
12968 2,
12969 &state,
12970 );
12971 queue.put(&mut t).unwrap();
12972 t.release_operator("chat", None);
12973 t.edit("revised".into(), "revised instruction".into())
12974 .unwrap();
12975 queue.put(&mut t).unwrap();
12976 drop(state);
12977 assert_eq!(
12978 queue
12979 .get(&t.id)
12980 .unwrap()
12981 .decision_effects
12982 .get("hold-inquiry"),
12983 Some(&format!("decision: {}", land::HOLD))
12984 );
12985 }
12986
12987 fn stopped_public_run(status: RunStatus) -> RunState {
12988 let mut state = run_state(status);
12989 state.driver_exited = true;
12990 state.config.graph.land = true;
12991 state.config.graph.review_rounds = 1;
12992 state.reviews = vec![review_round(1)];
12993 state.merge = Some(crate::run::MergeOutcome {
12994 mode: MergeMode::Pr,
12995 ok: false,
12996 detail: "landing stopped".into(),
12997 empty: false,
12998 });
12999 state.pr = Some(crate::run::PrRecord {
13000 url: "https://example.test/pull/1".into(),
13001 number: 1,
13002 state: "open".into(),
13003 checks: "red".into(),
13004 round: 1,
13005 rounds: 1,
13006 red_at_merge: Vec::new(),
13007 });
13008 state
13009 }
13010
13011 #[test]
13012 fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
13013 for status in [RunStatus::Blocked, RunStatus::Gating] {
13014 let home = tempfile::tempdir().unwrap();
13015 let mut state = stopped_public_run(status);
13016 state.save_under(home.path()).unwrap();
13017 assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
13018 assert!(!exhausted_review_budget(&state));
13019 let mut task = held_task_with(&state.id);
13020 task.release();
13021 let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
13022 assert_eq!(
13023 choose_starter(None, false, unfinished.as_deref()),
13024 Starter::Resume(state.id.clone())
13025 );
13026 let question = action_question(&state.id, resume_action(&state.id));
13027 assert_eq!(
13028 decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
13029 state.clone()
13030 )),
13031 ActionDecision::Resume(state.id.clone())
13032 );
13033 assert_eq!(
13035 crate::resume::validate(home.path(), &state.id).unwrap().id,
13036 state.id
13037 );
13038 let queue = Queue::at(home.path().join("queue"));
13039 let mut controlled = Task::new(
13040 "resume land".into(),
13041 state.instruction.clone(),
13042 state.repo.clone(),
13043 Source::Agent {
13044 run: "talk".into(),
13045 node: crate::queue::CHAT_NODE.into(),
13046 },
13047 );
13048 controlled.runs.push(state.id.clone());
13049 controlled.hold_machine(Some("land stopped".into()));
13050 queue.put(&mut controlled).unwrap();
13051 let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
13052 assert_eq!(resumed.status, TaskStatus::Queued);
13053 assert_eq!(
13054 resumed.resume_override.unwrap().pinned_run,
13055 Some(state.id.clone())
13056 );
13057 assert_eq!(resumed.attempts, 0);
13058 }
13059 }
13060
13061 #[test]
13062 fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
13063 for review_rounds in [0, 1] {
13064 let home = tempfile::tempdir().unwrap();
13065 let mut state = run_state(RunStatus::Blocked);
13066 state.config.graph.review_rounds = review_rounds;
13067 if review_rounds > 0 {
13068 let mut review = review_round(1);
13069 review.clean = true;
13070 state.reviews = vec![review];
13071 }
13072 state.gate_ran = true;
13073 state.gate = vec![crate::run::CommandOutcome {
13074 command: "verify".into(),
13075 code: Some(1),
13076 output_tail: "gate failed after repair budget exhausted".into(),
13077 duration_ms: 0,
13078 resource_blocked: false,
13079 }];
13080 state.save_under(home.path()).unwrap();
13081 assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
13082 assert!(exhausted_review_budget(&state));
13083 let mut task = held_task_with(&state.id);
13084 task.release();
13085 assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
13086 let question = action_question(&state.id, resume_action(&state.id));
13087 assert_ne!(
13088 decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
13089 state.clone()
13090 )),
13091 ActionDecision::Resume(state.id.clone())
13092 );
13093 let error = crate::resume::validate(home.path(), &state.id)
13094 .unwrap_err()
13095 .to_string();
13096 assert!(!error.contains("review budget exhausted"), "{error}");
13097 assert!(
13098 error.contains(if review_rounds == 0 {
13099 "review is disabled"
13100 } else {
13101 "gate already ran"
13102 }),
13103 "{error}"
13104 );
13105
13106 state.gate_ran = false;
13108 state.gate.clear();
13109 assert!(!exhausted_review_budget(&state));
13110 assert_eq!(
13111 unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
13112 Some(state.id)
13113 );
13114 }
13115 }
13116
13117 #[test]
13118 fn resource_blocked_verification_resumes_the_same_run() {
13119 for (kind, stage) in [
13120 ("cache", "clean"),
13121 ("coordination", "clean"),
13122 ("cache", "review-e2e"),
13123 ("coordination", "no-reviews"),
13124 ("coordination", "handoff"),
13125 ] {
13126 let home = tempfile::tempdir().unwrap();
13127 let mut state = run_state(RunStatus::Blocked);
13128 state.config.graph.review_rounds = 1;
13129 let mut review = review_round(1);
13130 review.clean = true;
13131 state.reviews = vec![review];
13132 if stage == "review-e2e" {
13133 let review = &mut state.reviews[0];
13134 review.clean = false;
13135 review.blocking = 1;
13136 review.e2e = vec![crate::run::CommandOutcome {
13137 command: "verify".into(),
13138 code: None,
13139 output_tail: "resource wait expired".into(),
13140 duration_ms: 0,
13141 resource_blocked: true,
13142 }];
13143 } else if stage == "no-reviews" {
13144 state.config.graph.review_rounds = 0;
13145 state.reviews.clear();
13146 } else if stage == "handoff" {
13147 let review = &mut state.reviews[0];
13150 review.clean = false;
13151 review.blocking = 1;
13152 review.e2e = vec![crate::run::CommandOutcome {
13153 command: "verify".into(),
13154 code: Some(0),
13155 output_tail: String::new(),
13156 duration_ms: 0,
13157 resource_blocked: false,
13158 }];
13159 }
13160 state.gate_ran = false;
13161 state.resource_block = Some(crate::run::ResourceBlock {
13162 cause: crate::run::ResourceBlockCause::Other,
13163 node: if stage == "review-e2e" {
13164 "review"
13165 } else {
13166 "gate"
13167 }
13168 .into(),
13169 kind: kind.into(),
13170 detail: "resource wait expired".into(),
13171 at: jiff::Timestamp::now(),
13172 });
13173 state.save_under(home.path()).unwrap();
13174 assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
13175 assert!(!exhausted_review_budget(&state));
13176 let mut task = held_task_with(&state.id);
13177 task.release();
13178 let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
13179 assert_eq!(
13180 choose_starter(None, false, unfinished.as_deref()),
13181 Starter::Resume(state.id.clone())
13182 );
13183 let question = action_question(&state.id, resume_action(&state.id));
13184 assert_eq!(
13185 decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
13186 state.clone()
13187 )),
13188 ActionDecision::Resume(state.id.clone())
13189 );
13190 assert_eq!(
13191 crate::resume::validate(home.path(), &state.id).unwrap().id,
13192 state.id
13193 );
13194 let queue = Queue::at(home.path().join("queue"));
13195 let mut controlled = Task::new(
13196 "resume verification".into(),
13197 state.instruction.clone(),
13198 state.repo.clone(),
13199 Source::Agent {
13200 run: "talk".into(),
13201 node: crate::queue::CHAT_NODE.into(),
13202 },
13203 );
13204 controlled.runs.push(state.id.clone());
13205 controlled.hold_machine(Some("verification resource unavailable".into()));
13206 queue.put(&mut controlled).unwrap();
13207 let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
13208 assert_eq!(resumed.status, TaskStatus::Queued);
13209 assert_eq!(
13210 resumed.resume_override.unwrap().pinned_run,
13211 Some(state.id.clone())
13212 );
13213 assert_eq!(resumed.attempts, 0);
13214
13215 state.config.graph.review_rounds = 1;
13217 let mut unresolved = review_round(1);
13218 unresolved.blocking = 1;
13219 state.reviews = vec![unresolved];
13220 state.resource_block = None;
13221 state.save_under(home.path()).unwrap();
13222 assert!(exhausted_review_budget(&state));
13223 assert!(crate::resume::validate(home.path(), &state.id).is_err());
13224 }
13225 }
13226
13227 #[tokio::test]
13228 async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
13229 if !crate::standalone_test(
13230 "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
13231 ) {
13232 return;
13233 }
13234 let home = tempfile::tempdir().unwrap();
13235 let mut owner = stopped_public_run(RunStatus::Blocked);
13236 owner.save_under(home.path()).unwrap();
13237 let history = vec![owner.id.clone()];
13238 let repo = owner.repo.clone();
13239 let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
13240 let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
13241 let initial =
13242 std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
13243 assert!(
13244 initial.is_pending(),
13245 "a busy record must not hold or resume the task"
13246 );
13247 owner.retired_to = Some("20260101-000001-bbbb".into());
13248 owner.save_under(home.path()).unwrap();
13249 drop(lock);
13250 let result = tokio::time::timeout(Duration::from_secs(10), lookup)
13251 .await
13252 .expect("ownership lock released")
13253 .expect("read settled owner");
13254 assert!(
13255 result.is_none(),
13256 "the retired owner must not be resumed from a stale read"
13257 );
13258 }
13259
13260 #[tokio::test]
13261 async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
13262 if !crate::standalone_test(
13263 "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
13264 ) {
13265 return;
13266 }
13267 let home = tempfile::tempdir().unwrap();
13268 let mut owner = stopped_public_run(RunStatus::Blocked);
13269 let repo = tempfile::tempdir().unwrap();
13270 crate::git::git(repo.path(), &["init"]).await.unwrap();
13271 owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
13272 owner.id = "20260101-000000-aaaa".into();
13273 owner.save_under(home.path()).unwrap();
13274 let mut successor = run_state(RunStatus::Blocked);
13275 successor.id = "20260101-000001-bbbb".into();
13276 successor.save_under(home.path()).unwrap();
13277 let runs = vec![owner.id.clone(), successor.id.clone()];
13278 assert_eq!(
13279 public_resume_owner(home.path(), &runs, &owner.repo)
13280 .await
13281 .unwrap()
13282 .unwrap()
13283 .id,
13284 owner.id
13285 );
13286 let subdir = owner.repo.join("nested");
13287 std::fs::create_dir(&subdir).unwrap();
13288 assert_eq!(
13289 public_resume_owner(home.path(), &runs, &subdir)
13290 .await
13291 .unwrap()
13292 .unwrap()
13293 .id,
13294 owner.id
13295 );
13296 #[cfg(unix)]
13297 {
13298 let alias = home.path().join("repo-alias");
13299 std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
13300 assert_eq!(
13301 public_resume_owner(home.path(), &runs, &alias.join("nested"))
13302 .await
13303 .unwrap()
13304 .unwrap()
13305 .id,
13306 owner.id
13307 );
13308 }
13309 let different = tempfile::tempdir().unwrap();
13310 crate::git::git(different.path(), &["init"]).await.unwrap();
13311 assert!(
13312 public_resume_owner(home.path(), &runs, different.path())
13313 .await
13314 .is_err()
13315 );
13316 std::fs::remove_file(
13317 home.path()
13318 .join("runs")
13319 .join(&successor.id)
13320 .join("run.json"),
13321 )
13322 .unwrap();
13323 assert!(
13324 public_resume_owner(home.path(), &runs, &owner.repo)
13325 .await
13326 .is_err()
13327 );
13328 }
13329
13330 #[test]
13331 fn an_ordinary_release_keeps_a_resumable_run_available() {
13332 let mut released = task();
13333 released.start("stalled-run".to_owned());
13334 released.release();
13335 let unfinished = (!released.fresh_start)
13336 .then(|| Some("stalled-run".to_owned()))
13337 .flatten();
13338 assert_eq!(
13339 choose_starter(None, false, unfinished.as_deref()),
13340 Starter::Resume("stalled-run".to_owned()),
13341 "manual release must preserve the normal resume path"
13342 );
13343 }
13344
13345 #[test]
13346 fn resume_refusals_explain_admission_without_changing_task_or_run() {
13347 use crate::handover::{ResumeRefusal, resume_refusal_under};
13348 let home = tempfile::tempdir().unwrap();
13349 let mut exhausted = run_state(RunStatus::Blocked);
13350 exhausted.driver_exited = true;
13351 exhausted.config.graph.review_rounds = 3;
13352 exhausted.reviews = (1..=3).map(review_round).collect();
13353 for refusal in [
13354 ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
13355 ResumeRefusal::Status(RunStatus::Ready),
13356 ResumeRefusal::Released("20261022-000000-aaaa".into()),
13357 ResumeRefusal::Retired("retirement-successor".into()),
13358 ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
13359 ] {
13360 let mut state = exhausted.clone();
13361 let expected = match refusal {
13362 ResumeRefusal::Status(_) => {
13363 state.status = RunStatus::Ready;
13364 "status `ready`"
13365 }
13366 ResumeRefusal::Released(ref target) => {
13367 state.released_to = Some(target.clone());
13368 "execution was released"
13369 }
13370 ResumeRefusal::Retired(ref target) => {
13371 state.retired_to = Some(target.clone());
13372 "execution was retired"
13373 }
13374 ResumeRefusal::OwnershipTransferred(ref target) => {
13375 state.pr_taken_over_by = Some(target.clone());
13376 "PR ownership was transferred"
13377 }
13378 _ => "review budget exhausted (3/3 rounds used)",
13379 };
13380 assert_eq!(
13381 resume_refusal_under(&state, Some(home.path())),
13382 Some(refusal.clone())
13383 );
13384 assert_eq!(
13385 refusal.successor(),
13386 state
13387 .released_to
13388 .as_deref()
13389 .or(state.retired_to.as_deref())
13390 .or(state.pr_taken_over_by.as_deref())
13391 );
13392 state.save_under(home.path()).unwrap();
13393 let queue = Queue::at(home.path().join("queue"));
13394 let mut task = Task::new(
13395 "retained implementation".into(),
13396 state.instruction.clone(),
13397 state.repo.clone(),
13398 Source::Agent {
13399 run: "talk".into(),
13400 node: crate::queue::CHAT_NODE.into(),
13401 },
13402 );
13403 task.runs.push(state.id.clone());
13404 task.hold_machine(Some("stopped".into()));
13405 queue.put(&mut task).unwrap();
13406 let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
13407 let before_run = serde_json::to_value(&state).unwrap();
13408 let error = crate::chat_control::resume(&queue, home.path(), &state.id)
13409 .unwrap_err()
13410 .to_string();
13411 assert!(error.contains(expected), "{error}");
13412 assert!(!error.contains("only a stalled or blocked"), "{error}");
13413 if matches!(refusal, ResumeRefusal::Status(_)) {
13414 assert!(
13415 error.contains("is final; there is nothing left to resume"),
13416 "{error}"
13417 );
13418 }
13419 if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
13420 assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
13421 assert!(error.contains("review-only successor with a new review budget"));
13422 assert!(error.contains("does not resume this run"));
13423 }
13424 for target in [
13425 &state.released_to,
13426 &state.retired_to,
13427 &state.pr_taken_over_by,
13428 ]
13429 .into_iter()
13430 .flatten()
13431 {
13432 let short = if state.retired_to.as_ref() == Some(target) {
13433 target.as_str()
13434 } else {
13435 crate::run::short_of(target)
13436 };
13437 assert!(
13438 error.contains(&format!("run {short}; inspect `magi show {short}`")),
13439 "{error}"
13440 );
13441 if short != target {
13442 assert!(!error.contains(target), "full successor id leaked: {error}");
13443 }
13444 }
13445 assert_eq!(
13446 serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
13447 before_task
13448 );
13449 assert_eq!(
13450 serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
13451 .unwrap(),
13452 before_run
13453 );
13454 let question = action_question(&state.id, resume_action(&state.id));
13455 for phrases in [&PHRASES_EN, &PHRASES_JA] {
13456 let decision = decide_action(home.path(), &task, &question, phrases, |id| {
13457 RunState::load_under(id, home.path())
13458 });
13459 let ActionDecision::Refuse(detail) = decision else {
13460 panic!(
13461 "refusal expected: decision={decision:?}, refusal={refusal:?}, run={}, home={}",
13462 state.id,
13463 home.path().display()
13464 );
13465 };
13466 assert!(detail.contains(expected), "{detail}");
13467 }
13468 }
13469 exhausted.status = RunStatus::Ready;
13471 exhausted.released_to = Some("released".into());
13472 exhausted.retired_to = Some("retired".into());
13473 exhausted.pr_taken_over_by = Some("owner".into());
13474 let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
13475 assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
13476 let detail = reason.diagnostic(&exhausted);
13477 for target in ["released", "retired", "owner"] {
13478 assert!(detail.contains(&format!("magi show {target}")));
13479 }
13480 }
13481
13482 #[test]
13483 fn resume_action_ignores_question_checkpoints_in_another_home() {
13484 crate::run::pin_test_home();
13485 let home = tempfile::tempdir().unwrap();
13486 let mut state = run_state(RunStatus::Blocked);
13487 state.id = format!(
13490 "resume-context-{}",
13491 home.path().file_name().unwrap().to_str().unwrap()
13492 );
13493 state.driver_exited = true;
13494 state.config.graph.review_rounds = 1;
13495 state.reviews = vec![review_round(1)];
13496 state.save_under(home.path()).unwrap();
13497 let task = held_task_with(&state.id);
13498 let answer = action_question(&state.id, resume_action(&state.id));
13499 let mut checkpoint = approval_question(&state.id);
13500 let foreign = Questions::open();
13501 foreign.put(&mut checkpoint).unwrap();
13502 let refusal = crate::handover::resume_refusal_under(&state, Some(home.path()));
13503 let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
13504 RunState::load_under(id, home.path())
13505 });
13506 let matching: Vec<_> = foreign
13507 .list()
13508 .into_iter()
13509 .filter(|q| q.run == state.id && q.status.open())
13510 .collect();
13511 std::fs::remove_file(foreign.path_of(&checkpoint.id)).unwrap();
13512 assert!(
13513 matches!(decision, ActionDecision::Refuse(_)),
13514 "decision={decision:?}, refusal={refusal:?}, run={}, home={}, foreign_home={}, matching={matching:?}",
13515 state.id,
13516 home.path().display(),
13517 crate::run::test_home().display()
13518 );
13519 assert_eq!(
13520 refusal,
13521 Some(crate::handover::ResumeRefusal::ReviewBudget { used: 1, limit: 1 })
13522 );
13523 let local = Questions::at(home.path().join("questions"));
13524 for status in [
13525 ask::QuestionStatus::Open,
13526 ask::QuestionStatus::Answered,
13527 ask::QuestionStatus::Abandoned,
13528 ] {
13529 let mut question = checkpoint.clone();
13530 match status {
13531 ask::QuestionStatus::Open => {}
13532 ask::QuestionStatus::Answered => {
13533 question
13534 .answer(ask::Answer::Choice(question.choices[0].clone()))
13535 .unwrap();
13536 }
13537 ask::QuestionStatus::Abandoned => question.abandon("fixture closed"),
13538 }
13539 local.put(&mut question).unwrap();
13540 let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
13541 RunState::load_under(id, home.path())
13542 });
13543 if status.open() {
13544 assert_eq!(decision, ActionDecision::Resume(state.id.clone()));
13545 } else {
13546 assert!(
13547 matches!(decision, ActionDecision::Refuse(ref detail) if detail.contains("review budget exhausted")),
13548 "status={status:?}, decision={decision:?}"
13549 );
13550 }
13551 }
13552 }
13553
13554 #[test]
13555 fn resume_action_checks_the_driver_lease_in_the_supplied_home() {
13556 let home = tempfile::tempdir().unwrap();
13557 let mut state = run_state(RunStatus::Stalled);
13558 state.id = format!(
13559 "resume-driver-{}",
13560 home.path().file_name().unwrap().to_str().unwrap()
13561 );
13562 state.driver_claimed = Some(false);
13563 state.save_under(home.path()).unwrap();
13564 let task = held_task_with(&state.id);
13565 let question = action_question(&state.id, resume_action(&state.id));
13566 let decide = || {
13567 decide_action(home.path(), &task, &question, &PHRASES_EN, |id| {
13568 RunState::load_under(id, home.path())
13569 })
13570 };
13571 let lease = crate::driver::maintenance(home.path(), &state.id).unwrap();
13572 assert_eq!(state.liveness_under(home.path(), false), Liveness::Live);
13573 assert_eq!(
13574 decide(),
13575 ActionDecision::Refuse("run already has a live driver".into())
13576 );
13577 drop(lease);
13578 assert_eq!(decide(), ActionDecision::Resume(state.id.clone()));
13579 }
13580
13581 #[test]
13582 fn resume_checkpoint_admission_uses_the_supplied_question_store() {
13583 let home = tempfile::tempdir().unwrap();
13584 let mut state = run_state(RunStatus::Blocked);
13585 state.driver_exited = true;
13586 state.config.graph.review_rounds = 1;
13587 state.reviews = vec![review_round(1)];
13588 assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
13589 for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
13590 let mut saved = state.clone();
13591 match checkpoint {
13592 "publication" => saved.pr_publication_pending = true,
13593 "approval" => {
13594 saved.land_approval = Some(crate::run::LandApproval {
13595 question: "approval".into(),
13596 head: "head".into(),
13597 })
13598 }
13599 "armed" => saved.land_armed_head = Some("head".into()),
13600 "landing" => saved.status = RunStatus::Landing,
13601 _ => {
13602 let mut question = ask::Question::new(
13603 saved.id.clone(),
13604 "review".into(),
13605 "review-1".into(),
13606 "continue?".into(),
13607 String::new(),
13608 vec!["continue".into()],
13609 );
13610 ask::Questions::at(home.path().join("questions"))
13611 .put(&mut question)
13612 .unwrap();
13613 }
13614 }
13615 saved.save_under(home.path()).unwrap();
13616 assert!(
13617 crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
13618 "{checkpoint}"
13619 );
13620 assert!(
13621 crate::resume::validate(home.path(), &saved.id).is_ok(),
13622 "{checkpoint}"
13623 );
13624 }
13625 }
13626
13627 #[test]
13628 fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
13629 let mut state = run_state(RunStatus::Blocked);
13630 state.config.graph.review_rounds = 3;
13631 state.reviews = vec![review_round(1), review_round(2), review_round(3)];
13632 assert!(exhausted_review_budget(&state));
13633
13634 state.reviews.pop();
13636 assert!(!exhausted_review_budget(&state));
13637
13638 let mut stalled = run_state(RunStatus::Stalled);
13641 stalled.config.graph.review_rounds = 1;
13642 stalled.reviews = vec![review_round(1)];
13643 assert!(!exhausted_review_budget(&stalled));
13644 }
13645
13646 fn review_round(round: usize) -> crate::run::ReviewRound {
13647 crate::run::ReviewRound {
13648 round,
13649 head: "deadbeef".to_owned(),
13650 verified_head: None,
13651 verified_at: None,
13652 reviews: Vec::new(),
13653 e2e: Vec::new(),
13654 verify_retried: false,
13655 e2e_deferred: false,
13656 e2e_defer_reason: None,
13657 fix: None,
13658 blocking: 0,
13659 answered: 1,
13660 expected: 1,
13661 clean: false,
13662 progressed: true,
13663 vote_split: false,
13664 reconsideration: Vec::new(),
13665 verdict: None,
13666 }
13667 }
13668
13669 #[test]
13670 fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
13671 let mut run = RunState::new(
13672 PathBuf::from("/repo"),
13673 "main".to_owned(),
13674 "abc1234def".to_owned(),
13675 "add retries".to_owned(),
13676 Config::default(),
13677 );
13678 run.status = RunStatus::Judging;
13679 run.parked = true;
13680 let mut task = Task::new(
13681 "add retries".to_owned(),
13682 "add retries".to_owned(),
13683 PathBuf::from("/repo"),
13684 crate::queue::Source::Human,
13685 );
13686 task.status = TaskStatus::Failed;
13687 task.runs = vec![run.id.clone()];
13688 let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
13689 assert!(with(&task, &run), "parked after judging is the case");
13690 let mut parked_task = task.clone();
13691 parked_task.status = TaskStatus::Parked;
13692 assert!(with(&parked_task, &run), "the Parked status is the case");
13693
13694 let mut not_parked = run.clone();
13695 not_parked.parked = false;
13696 not_parked.status = RunStatus::Stalled;
13697 assert!(!with(&task, ¬_parked), "a stall is the conductor's");
13698
13699 let mut fresh = task.clone();
13700 fresh.fresh_start = true;
13701 assert!(!with(&fresh, &run), "a requeue asked for a new competition");
13702
13703 let mut review = task.clone();
13704 review.review_branch = Some("magi/x/A".to_owned());
13705 assert!(!with(&review, &run), "review is ranked before resume");
13706
13707 let mut held = task.clone();
13708 held.status = TaskStatus::Held;
13709 assert!(!with(&held, &run), "a hold stays visible to the conductor");
13710
13711 let mut released = run.clone();
13712 released.released_to = Some("20260901-000000-new1".to_owned());
13713 assert!(!with(&task, &released), "nothing left to resume into");
13714
13715 assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
13716 "unreadable"
13717 )));
13718 }
13719
13720 #[test]
13721 fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
13722 let mut released = RunState::new(
13723 PathBuf::from("/repo"),
13724 "main".to_owned(),
13725 "abc1234def".to_owned(),
13726 "add retries".to_owned(),
13727 Config::default(),
13728 );
13729 released.status = RunStatus::Blocked;
13730 assert_eq!(
13731 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
13732 Some(released.id.clone())
13733 );
13734 released.released_to = Some("20260901-000000-new1".to_owned());
13735 assert_eq!(
13736 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
13737 None,
13738 "there is nothing left to resume it into"
13739 );
13740 }
13741
13742 #[test]
13743 fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
13744 let mut exhausted = RunState::new(
13753 PathBuf::from("/repo"),
13754 "main".to_owned(),
13755 "abc1234def".to_owned(),
13756 "add retries".to_owned(),
13757 Config::default(),
13758 );
13759 exhausted.status = RunStatus::Blocked;
13760 exhausted.config.graph.review_rounds = 1;
13761 exhausted.reviews = vec![review_round(1)];
13762
13763 assert_eq!(
13764 unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
13765 None,
13766 "an exhausted `Blocked` run must not be offered as resumable"
13767 );
13768
13769 let mut has_budget_left = RunState::new(
13772 PathBuf::from("/repo"),
13773 "main".to_owned(),
13774 "abc1234def".to_owned(),
13775 "add retries".to_owned(),
13776 Config::default(),
13777 );
13778 has_budget_left.status = RunStatus::Blocked;
13779 has_budget_left.config.graph.review_rounds = 3;
13780 has_budget_left.reviews = vec![review_round(1)];
13781
13782 assert_eq!(
13783 unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
13784 Ok(has_budget_left.clone())
13785 }),
13786 Some(has_budget_left.id.clone())
13787 );
13788 }
13789
13790 #[test]
13791 fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
13792 let mut run = RunState::new(
13793 PathBuf::from("/repo"),
13794 "main".to_owned(),
13795 "abc1234def".to_owned(),
13796 "add retries".to_owned(),
13797 Config::default(),
13798 );
13799 run.status = RunStatus::Blocked;
13800 run.config.graph.review_rounds = 1;
13801 run.reviews = vec![review_round(1)];
13802 run.pr_publication_pending = true;
13803 assert_eq!(
13804 unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
13805 Some(run.id.clone()),
13806 "a spent review budget must not turn a failed publication into a re-competition"
13807 );
13808 }
13809
13810 #[test]
13811 fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
13812 let mut task = Task::new(
13813 "recover work".into(),
13814 "recover work".into(),
13815 PathBuf::from("/repo"),
13816 crate::queue::Source::Human,
13817 );
13818 let mut history = std::collections::BTreeMap::new();
13819 for index in 0..8 {
13820 let mut run = run_state(RunStatus::Blocked);
13821 run.id = format!("20260101-000000-{index:04}");
13822 run.base_commit = format!("upstream-{index}");
13823 if index > 0 {
13825 run.candidates.clear();
13826 }
13827 task.runs.extend([run.id.clone(), run.id.clone()]);
13828 history.insert(run.id.clone(), run);
13829 task.requeue();
13830 }
13831 let check = |task: &Task, starter: &Starter, limit| {
13832 retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
13833 };
13834 assert!(
13835 check(&task, &Starter::Start, 8)
13836 .unwrap()
13837 .contains("8 unretired")
13838 );
13839 assert!(check(&task, &Starter::Start, 9).is_none());
13840 assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
13841 task.release_operator("owner", None);
13842 assert_eq!(task.attempts, 0);
13843 let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
13844 assert!(check(&restored, &Starter::Start, 8).is_some());
13845 assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
13846 assert!(check(&restored, &Starter::Start, 0).is_none());
13847 }
13848
13849 #[test]
13850 fn retained_attempt_bound_includes_failed_startups_without_execution_history() {
13851 let tmp = tempfile::tempdir().unwrap();
13852 let mut task = Task::new(
13853 "recover selected PR".into(),
13854 "preserve implementation".into(),
13855 tmp.path().join("repo"),
13856 crate::queue::Source::Human,
13857 );
13858 let mut failed = run_state(RunStatus::Failed);
13859 failed.id = "20260101-000000-fail".into();
13860 failed.candidates.clear();
13861 failed.prep_complete = Some(false);
13862 failed.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
13863 failed.startup = Some(crate::run::Startup {
13864 kind: "pr-recovery".into(),
13865 branch: Some("selected-public-head".into()),
13866 stage: "worktree-setup".into(),
13867 complete: false,
13868 failure: Some("setup modified a tracked file and failed".into()),
13869 });
13870 let worktree = failed.worktree_root().join("under-review");
13873 std::fs::create_dir_all(&worktree).unwrap();
13874 let retained_edit = worktree.join("implementation");
13875 std::fs::write(&retained_edit, "retained setup edit").unwrap();
13876 task.record_startup_failure(crate::run::StartupFailure {
13877 run: failed.id.clone(),
13878 stage: "worktree-setup".into(),
13879 });
13880 let task: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
13881 assert!(task.runs.is_empty() && task.passes.is_empty());
13882 assert_eq!(task.attempts, 0);
13883 let starter = Starter::Review("selected-public-head".into());
13884 assert!(
13885 retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone()))
13886 .unwrap()
13887 .contains("1 unretired")
13888 );
13889 assert!(retained_attempt_hold(&task, &starter, 2, |_| Ok(failed.clone())).is_none());
13890 assert!(
13891 retained_attempt_hold(&task, &starter, 2, |_| anyhow::bail!("unreadable"))
13892 .unwrap()
13893 .contains("Cannot verify")
13894 );
13895 let mut mixed = task.clone();
13897 mixed.runs.push(failed.id.clone());
13898 mixed
13899 .startup_failures
13900 .push(task.startup_failures[0].clone());
13901 assert!(retained_attempt_hold(&mixed, &starter, 2, |_| Ok(failed.clone())).is_none());
13902 failed.retired_to = Some("verified-recovery-owner".into());
13903 assert!(retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone())).is_none());
13904 assert!(
13905 retained_attempt_hold(&task, &Starter::Resume(failed.id.clone()), 1, |_| {
13906 panic!("resuming the existing owner must not allocate a new attempt")
13907 })
13908 .is_none()
13909 );
13910 assert_eq!(
13911 std::fs::read_to_string(retained_edit).unwrap(),
13912 "retained setup edit"
13913 );
13914 assert!(task.runs.is_empty() && task.passes.is_empty());
13915 assert_eq!(task.attempts, 0);
13916 }
13917
13918 #[test]
13919 fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
13920 let mut task = Task::new(
13921 "recover work".into(),
13922 "recover work".into(),
13923 PathBuf::from("/repo"),
13924 crate::queue::Source::Human,
13925 );
13926 let mut run = run_state(RunStatus::Superseded);
13927 run.candidates.clear();
13928 task.runs.push(run.id.clone());
13929 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
13930 run.retired_to = Some("authority".into());
13931 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
13932 run.retired_to = None;
13933 run.released_to = Some("authority".into());
13934 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
13935 assert!(
13936 retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
13937 .unwrap()
13938 .contains("Cannot verify")
13939 );
13940 assert!(
13942 retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
13943 panic!("resume must not load historical attempts")
13944 })
13945 .is_none()
13946 );
13947 }
13948
13949 #[test]
13950 fn retired_resume_requires_a_valid_same_repository_authority() {
13951 let mut source = run_state(RunStatus::Blocked);
13952 let mut empty = run_state(RunStatus::Blocked);
13953 empty.retired_to = Some(source.id.clone());
13954 let runs = vec![source.id.clone(), empty.id.clone()];
13955 let resolve = |source: &RunState, empty: &RunState| {
13956 unfinished_run_with(&runs, "fixture", |id| {
13957 if id == source.id {
13958 Ok(source.clone())
13959 } else if id == empty.id {
13960 Ok(empty.clone())
13961 } else {
13962 bail!("unreadable authority")
13963 }
13964 })
13965 };
13966 assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
13967 assert_eq!(
13968 choose_starter(None, false, resolve(&source, &empty).as_deref()),
13969 Starter::Resume(source.id.clone())
13970 );
13971 source.retired_to = Some(empty.id.clone());
13972 assert!(
13973 resolve(&source, &empty).is_none(),
13974 "cycles do not revive obsolete runs"
13975 );
13976 source.retired_to = None;
13977 source.repo = PathBuf::from("/another-repository");
13978 assert!(resolve(&source, &empty).is_none());
13979 source.repo = empty.repo.clone();
13980 source.released_to = Some("later".into());
13981 assert!(resolve(&source, &empty).is_none());
13982 empty.retired_to = Some("unlisted-run".into());
13983 assert!(resolve(&source, &empty).is_none());
13984 }
13985
13986 #[test]
13987 fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
13988 let mut older_stalled = RunState::new(
13996 PathBuf::from("/repo"),
13997 "main".to_owned(),
13998 "abc1234def".to_owned(),
13999 "add retries".to_owned(),
14000 Config::default(),
14001 );
14002 older_stalled.status = RunStatus::Stalled;
14003
14004 let mut newest_exhausted = RunState::new(
14005 PathBuf::from("/repo"),
14006 "main".to_owned(),
14007 "abc1234def".to_owned(),
14008 "add retries".to_owned(),
14009 Config::default(),
14010 );
14011 newest_exhausted.status = RunStatus::Blocked;
14012 newest_exhausted.config.graph.review_rounds = 1;
14013 newest_exhausted.reviews = vec![review_round(1)];
14014
14015 assert_eq!(
14016 unfinished_run_with(
14017 &[older_stalled.id.clone(), newest_exhausted.id.clone()],
14018 "t",
14019 |_| Ok(newest_exhausted.clone())
14020 ),
14021 None,
14022 "the newest run is exhausted, so nothing here is worth resuming - \
14023 least of all the older, already-superseded run"
14024 );
14025 }
14026
14027 #[test]
14028 fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
14029 assert_eq!(
14030 unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
14031 Err(anyhow::anyhow!("fixture is absent"))
14032 }),
14033 None
14034 );
14035 }
14036
14037 fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
14038 let mut q = ask::Question::new(
14039 run.to_owned(),
14040 "implement".to_owned(),
14041 "impl-A".to_owned(),
14042 "continue?".to_owned(),
14043 String::new(),
14044 vec!["resume で続行する".to_owned(), "other".to_owned()],
14045 );
14046 q.actions.insert("resume で続行する".to_owned(), action);
14047 q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
14048 .unwrap();
14049 q
14050 }
14051
14052 fn held_task_with(run: &str) -> Task {
14053 let mut t = task();
14054 t.runs = vec![run.to_owned()];
14055 t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
14056 t
14057 }
14058
14059 fn resume_action(run: &str) -> ask::ChoiceAction {
14060 ask::ChoiceAction::Resume { run: run.into() }
14061 }
14062
14063 #[test]
14064 fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
14065 let home = crate::run::test_home();
14066 for parked in [false, true] {
14067 let mut t = task();
14068 t.start("A".into());
14069 t.start("B".into());
14070 assert_eq!(t.runs, vec!["A", "B"]);
14071 t.start("A".into());
14072 let mut resumed = run_state(RunStatus::Blocked);
14073 resumed.id = "A".into();
14074 resumed.parked = parked;
14075 resumed.driver_exited = true;
14076 t.hold_machine(Some("resumed run stopped".into()));
14077 let q = action_question("A", resume_action("A"));
14078 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
14079 assert_eq!(
14080 decide_action(&home, &t, &q, &PHRASES_EN, |id| {
14081 assert_eq!(id, "A");
14082 Ok(resumed.clone())
14083 }),
14084 ActionDecision::Resume("A".into())
14085 );
14086 assert_eq!(
14087 action_standing(&t, &action_question("B", resume_action("B"))),
14088 ActionStanding::Stale
14089 );
14090 t.release_operator("cli", None);
14091 let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
14092 assert_eq!(id, "A");
14093 Ok(resumed.clone())
14094 });
14095 assert_eq!(
14096 choose_starter(None, false, unfinished.as_deref()),
14097 Starter::Resume("A".into())
14098 );
14099 assert_eq!(t.runs, vec!["B", "A"]);
14100 }
14101 }
14102
14103 #[test]
14104 fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
14105 let home = crate::run::test_home();
14106 let mut state = crate::land::tests::repair_state(true, true);
14107 state.status = RunStatus::Landing;
14108 state.parked = true;
14109 state.driver_exited = true;
14110 let mut q = ask::Question::new(
14111 state.id.clone(),
14112 land::APPROVAL_NODE.into(),
14113 "land".into(),
14114 "Merge?".into(),
14115 String::new(),
14116 vec![land::APPROVE.into(), land::HOLD.into()],
14117 );
14118 q.id = state.id.clone();
14119 state.land_approval = Some(crate::run::LandApproval {
14120 question: q.id.clone(),
14121 head: "current-head".into(),
14122 });
14123 assert!(land::upgrade_repair_choice(&mut q, &state));
14124 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14125 let mut task = held_task_with(&state.id);
14126 task.status = TaskStatus::Parked;
14127 assert_eq!(
14128 decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
14129 ActionDecision::Resume(state.id.clone())
14130 );
14131 q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
14132 q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
14133 task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
14134 assert_eq!(
14135 decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
14136 ActionDecision::Resume(state.id.clone()),
14137 "a repair answer newer than the manual hold resumes the existing owner"
14138 );
14139 task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
14140 for answered_at in [q.answered_at, None] {
14141 let mut older = q.clone();
14142 older.answered_at = answered_at;
14143 let refused = decide_action(&home, &task, &older, &PHRASES_EN, |_| {
14144 panic!("a later manual hold must prevent dispatch")
14145 });
14146 let ActionDecision::Refuse(reason) = refused else {
14147 panic!("expected an actionable refusal, got {refused:?}");
14148 };
14149 assert!(reason.contains("later operator decision"));
14150 assert!(reason.contains(&format!("magi task release {}", task.id)));
14151 }
14152 task.operator_decided_at = None;
14153 let mut superseded = state.clone();
14154 superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
14155 assert_eq!(
14156 decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(superseded)),
14157 ActionDecision::Stale
14158 );
14159 for case in 1..4 {
14160 let mut changed = state.clone();
14161 match case {
14162 1 => changed.status = RunStatus::Blocked,
14163 2 => changed.released_to = Some("new-owner".into()),
14164 _ => changed.land_approval.as_mut().unwrap().head.clear(),
14165 }
14166 assert!(matches!(
14167 decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(changed)),
14168 ActionDecision::Refuse(_)
14169 ));
14170 }
14171 assert!(matches!(
14172 decide_action(&home, &task, &q, &PHRASES_EN, |_| anyhow::bail!(
14173 "missing owner"
14174 )),
14175 ActionDecision::Refuse(_)
14176 ));
14177 task.runs.push("replacement".into());
14178 task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
14179 assert_eq!(
14180 decide_action(&home, &task, &q, &PHRASES_EN, |_| panic!(
14181 "old owner must not load"
14182 )),
14183 ActionDecision::Stale
14184 );
14185 }
14186
14187 #[test]
14188 fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
14189 let mut state = crate::land::tests::repair_state(true, true);
14190 state.status = RunStatus::Landing;
14191 state.parked = true;
14192 state.driver_exited = true;
14193 let mut q = ask::Question::new(
14194 state.id.clone(),
14195 land::APPROVAL_NODE.into(),
14196 "land".into(),
14197 "Merge?".into(),
14198 String::new(),
14199 vec![land::APPROVE.into(), land::HOLD.into()],
14200 );
14201 q.id = state.id.clone();
14202 state.land_approval = Some(crate::run::LandApproval {
14203 question: q.id.clone(),
14204 head: "current-head".into(),
14205 });
14206 state.save().unwrap();
14207 land::upgrade_repair_choice(&mut q, &state);
14208 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14209 Questions::open().put(&mut q).unwrap();
14210 let tmp = tempfile::tempdir().unwrap();
14211 let queue = Queue::at(tmp.path().join("queue"));
14212 let mut task = held_task_with(&state.id);
14213 task.status = TaskStatus::Parked;
14214 queue.put(&mut task).unwrap();
14215 let empty = Arc::new(tokio::sync::Semaphore::new(0));
14216 let free = Arc::new(tokio::sync::Semaphore::new(1));
14217 assert!(matches!(
14218 claim_dispatch(&queue, &task, false, &empty, &free),
14219 Err(SkipReason::OrdinaryCapacity)
14220 ));
14221 assert!(matches!(
14222 claim_dispatch(&queue, &task, true, &free, &free),
14223 Err(SkipReason::CoolingDown)
14224 ));
14225 let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
14226 assert!(claim.permit.is_some());
14227 assert!(matches!(
14228 claim_dispatch(&queue, &task, false, &free, &free),
14229 Err(SkipReason::ClaimUnavailable)
14230 ));
14231 drop(claim);
14232 Questions::open()
14233 .update(&q.id, |q| {
14234 q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
14235 Ok(())
14236 })
14237 .unwrap();
14238 let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
14239 assert!(claim.permit.is_none());
14240 assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
14241 }
14242
14243 #[test]
14244 fn decide_action_resumes_only_the_latest_resumable_run() {
14245 let home = crate::run::test_home();
14246 let t = held_task_with("r1");
14247 let q = action_question("r1", resume_action("r1"));
14248 let load = |s: RunState| move |_: &str| Ok(s);
14249 assert_eq!(
14250 decide_action(
14251 &home,
14252 &t,
14253 &q,
14254 &PHRASES_EN,
14255 load(run_state(RunStatus::Blocked))
14256 ),
14257 ActionDecision::Resume("r1".into())
14258 );
14259 let q_other = action_question("r1", resume_action("r0"));
14261 assert!(matches!(
14262 decide_action(
14263 &home,
14264 &t,
14265 &q_other,
14266 &PHRASES_EN,
14267 load(run_state(RunStatus::Blocked))
14268 ),
14269 ActionDecision::Refuse(_)
14270 ));
14271 assert!(matches!(
14273 decide_action(
14274 &home,
14275 &t,
14276 &q,
14277 &PHRASES_EN,
14278 load(run_state(RunStatus::Ready))
14279 ),
14280 ActionDecision::Refuse(_)
14281 ));
14282 let mut released = run_state(RunStatus::Blocked);
14284 released.released_to = Some("elsewhere".into());
14285 assert!(matches!(
14286 decide_action(&home, &t, &q, &PHRASES_EN, load(released)),
14287 ActionDecision::Refuse(_)
14288 ));
14289 assert!(matches!(
14291 decide_action(&home, &t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
14292 ActionDecision::Refuse(_)
14293 ));
14294 }
14295
14296 #[test]
14297 fn decide_action_ignores_a_question_about_an_earlier_run() {
14298 let home = crate::run::test_home();
14299 let mut t = held_task_with("r1");
14300 t.runs.push("r2".to_owned());
14301 let never = |_: &str| -> Result<RunState> { bail!("not read") };
14302 assert_eq!(
14303 decide_action(
14304 &home,
14305 &t,
14306 &action_question("r1", ask::ChoiceAction::Done),
14307 &PHRASES_EN,
14308 never
14309 ),
14310 ActionDecision::Stale
14311 );
14312 }
14313
14314 #[test]
14315 fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
14316 let home = crate::run::test_home();
14317 let mut t = held_task_with("r1");
14318 let never = |_: &str| -> Result<RunState> { bail!("not read") };
14319 assert_eq!(
14320 decide_action(
14321 &home,
14322 &t,
14323 &action_question("r1", ask::ChoiceAction::Requeue),
14324 &PHRASES_EN,
14325 never
14326 ),
14327 ActionDecision::Requeue
14328 );
14329 let done_q = action_question("r1", ask::ChoiceAction::Done);
14330 assert_eq!(
14331 decide_action(&home, &t, &done_q, &PHRASES_EN, never),
14332 ActionDecision::Done
14333 );
14334 t.mark_action_applied(&done_q.id);
14335 assert_eq!(
14336 decide_action(&home, &t, &done_q, &PHRASES_EN, never),
14337 ActionDecision::Skip
14338 );
14339
14340 let mut plain = action_question("r1", ask::ChoiceAction::Done);
14342 plain.actions.clear();
14343 assert_eq!(
14344 decide_action(&home, &held_task_with("r1"), &plain, &PHRASES_EN, never),
14345 ActionDecision::Skip
14346 );
14347 let mut running = held_task_with("r1");
14349 running.status = TaskStatus::Running;
14350 assert_eq!(
14351 decide_action(
14352 &home,
14353 &running,
14354 &action_question("r1", ask::ChoiceAction::Done),
14355 &PHRASES_EN,
14356 never
14357 ),
14358 ActionDecision::Skip
14359 );
14360 }
14361
14362 #[test]
14363 fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
14364 crate::run::pin_test_home();
14365 for legacy in [false, true] {
14366 let dir = tempfile::tempdir().unwrap();
14367 let queue = Queue::at(dir.path().join("queue"));
14368 let questions = Questions::at(dir.path().join("questions"));
14369 let run = "20260101-000000-hold";
14370 let mut task = held_task_with(run);
14371 task.status = TaskStatus::Parked;
14372 let mut q = ask::Question::new(
14373 run.into(),
14374 land::APPROVAL_NODE.into(),
14375 "land".into(),
14376 "Repair?".into(),
14377 String::new(),
14378 vec![land::REPAIR.into()],
14379 );
14380 q.actions.insert(land::REPAIR.into(), resume_action(run));
14381 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14382 q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
14384 q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
14385 questions.put(&mut q).unwrap();
14386 task.hold_manual(Some("Keep this PR paused".into()));
14387 if legacy {
14388 task.hold_source = None;
14389 }
14390 queue.put(&mut task).unwrap();
14391
14392 apply_task_choice_actions(&queue, &questions, dir.path());
14393 let after = queue.get(&task.id).unwrap();
14394 assert!(after.operator_held());
14395 assert_eq!(after.hold_source, task.hold_source);
14396 assert_eq!(after.operator_decided_at, task.operator_decided_at);
14397 assert_eq!(after.runs, task.runs);
14398 assert_eq!(after.instruction, task.instruction);
14399 assert!(after.resume_override.is_none());
14400 assert!(after.action_applied(&q.id));
14401 let reason = after.hold_reason.as_deref().unwrap();
14402 assert!(reason.starts_with("Keep this PR paused"));
14403 assert!(reason.contains("later operator decision"));
14404 assert!(reason.contains(&format!("magi task release {}", task.id)));
14405
14406 for recovery in [
14407 crate::conduct::Recovery::Review,
14408 crate::conduct::Recovery::Requeue,
14409 ] {
14410 crate::conduct::apply(
14411 &queue,
14412 &questions,
14413 &crate::conduct::Verdict {
14414 decisions: vec![crate::conduct::Decision {
14415 id: task.id.clone(),
14416 recovery: Some(recovery),
14417 ..Default::default()
14418 }],
14419 },
14420 )
14421 .unwrap();
14422 }
14423 apply_task_choice_actions(&queue, &questions, dir.path());
14426 let still_held = queue.get(&task.id).unwrap();
14427 assert!(still_held.operator_held());
14428 assert_eq!(still_held.hold_reason, after.hold_reason);
14429 assert_eq!(still_held.runs, task.runs);
14430 assert!(still_held.review_branch.is_none());
14431 assert!(!still_held.fresh_start);
14432 assert!(queue.next_runnable().is_none());
14433 }
14434 }
14435
14436 #[test]
14437 fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
14438 for held in [false, true] {
14439 for retry in [false, true] {
14440 let dir = tempfile::tempdir().unwrap();
14441 let queue = Queue::at(dir.path().join("queue"));
14442 let questions = Questions::at(dir.path().join("questions"));
14443 let home = dir.path().join("home");
14444 let mut t = task();
14445 if held {
14446 t.hold_machine(Some("driver state unknown".into()));
14447 }
14448 queue.put(&mut t).unwrap();
14449 let verdict = serde_json::from_value(serde_json::json!({
14450 "decisions": [{
14451 "id": t.id,
14452 "question": "Driver state unknown; retry the checks or hold?",
14453 "choices": ["daemon: recheck and retry", "daemon: hold the task"],
14454 "actions": {
14455 "daemon: recheck and retry": {"do": "requeue"},
14456 "daemon: hold the task": {"do": "hold"}
14457 }
14458 }]
14459 }))
14460 .unwrap();
14461 crate::conduct::apply(&queue, &questions, &verdict).unwrap();
14462 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
14463 let mut q = questions.list().pop().unwrap();
14464 let choice = if retry {
14465 "daemon: recheck and retry"
14466 } else {
14467 "daemon: hold the task"
14468 };
14469 assert_eq!(q.actions.len(), 2);
14470 q.answer(ask::Answer::Choice(choice.into())).unwrap();
14471 questions.put(&mut q).unwrap();
14472
14473 questions.beat(&q.id, ask::WaiterKind::Deputy);
14475 for _ in 0..2 {
14476 resolve_blockers(&queue, &questions);
14477 apply_task_choice_actions(&queue, &questions, &home);
14478 let waiting = queue.get(&t.id).unwrap();
14479 assert_eq!(waiting.status, TaskStatus::Blocked);
14480 assert_eq!(waiting.blocked_by, [q.id.clone()]);
14481 assert!(waiting.answers.is_empty());
14482 assert!(!waiting.action_applied(&q.id));
14483 assert!(runnable(&queue).is_empty());
14484 let free = Arc::new(tokio::sync::Semaphore::new(1));
14485 assert!(claim_dispatch(&queue, &t, false, &free, &free).is_err());
14486 }
14487 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
14488
14489 resolve_blockers(&queue, &questions);
14491 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
14492 apply_task_choice_actions(&queue, &questions, &home);
14493 let after = queue.get(&t.id).unwrap();
14494 assert_eq!(
14495 after.status,
14496 if retry {
14497 TaskStatus::Queued
14498 } else {
14499 TaskStatus::Held
14500 }
14501 );
14502 assert!(after.action_applied(&q.id));
14503 assert_eq!(after.operator_held(), !retry);
14504 assert_eq!(after.answers.len(), 1);
14505
14506 let mut changed = after;
14508 if retry {
14509 changed.hold_manual(Some("later hold".into()));
14510 } else {
14511 changed.release_operator("test", None);
14512 }
14513 let expected = changed.status;
14514 queue.put(&mut changed).unwrap();
14515 apply_task_choice_actions(&queue, &questions, &home);
14516 assert_eq!(queue.get(&t.id).unwrap().status, expected);
14517 }
14518 }
14519 }
14520
14521 #[test]
14522 fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
14523 let dir = tempfile::tempdir().unwrap();
14524 let queue = Queue::at(dir.path().join("queue"));
14525 let questions = Questions::at(dir.path().join("questions"));
14526 let home = dir.path().join("home");
14527 let mut state = run_state(RunStatus::Blocked);
14528 state.id = "20260101-000000-act1".to_owned();
14529 state.save_under(&home).unwrap();
14530
14531 let mut t = held_task_with(&state.id);
14532 queue.put(&mut t).unwrap();
14533 let mut q = action_question(&state.id, resume_action(&state.id));
14534 questions.put(&mut q).unwrap();
14535
14536 apply_task_choice_actions(&queue, &questions, &home);
14537 let after = queue.get(&t.id).unwrap();
14538 assert_eq!(after.status, TaskStatus::Queued);
14539 assert!(!after.fresh_start);
14540 assert!(after.action_applied(&q.id));
14541 let pin = after.resume_override.clone().unwrap();
14542 assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
14543 assert!(pin.forced);
14544
14545 let mut again = queue.get(&t.id).unwrap();
14547 again.hold_machine(Some("later".into()));
14548 queue.put(&mut again).unwrap();
14549 apply_task_choice_actions(&queue, &questions, &home);
14550 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14551 }
14552
14553 #[test]
14554 fn a_delivered_answer_is_still_acted_on_exactly_once() {
14555 let dir = tempfile::tempdir().unwrap();
14556 let queue = Queue::at(dir.path().join("queue"));
14557 let questions = Questions::at(dir.path().join("questions"));
14558 let home = dir.path().join("home");
14559 let mut state = run_state(RunStatus::Blocked);
14560 state.id = "20260101-000000-act2".to_owned();
14561 state.save_under(&home).unwrap();
14562
14563 let mut t = held_task_with(&state.id);
14564 queue.put(&mut t).unwrap();
14565 let mut q = action_question(&state.id, resume_action(&state.id));
14566 q.answer_delivered = true;
14567 questions.put(&mut q).unwrap();
14568
14569 apply_task_choice_actions(&queue, &questions, &home);
14572 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
14573 assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
14574
14575 let mut again = queue.get(&t.id).unwrap();
14577 again.hold_machine(Some("later".into()));
14578 queue.put(&mut again).unwrap();
14579 apply_task_choice_actions(&queue, &questions, &home);
14580 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14581 }
14582
14583 #[test]
14584 fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
14585 let dir = tempfile::tempdir().unwrap();
14586 let queue = Queue::at(dir.path().join("queue"));
14587 let questions = Questions::at(dir.path().join("questions"));
14588 let home = dir.path().join("home");
14589 let mut state = run_state(RunStatus::Blocked);
14590 state.id = "20260101-000000-act3".to_owned();
14591 state.save_under(&home).unwrap();
14592 let mut t = held_task_with(&state.id);
14593 queue.put(&mut t).unwrap();
14594 let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
14595 questions.put(&mut q).unwrap();
14596
14597 questions.beat(&q.id, crate::ask::WaiterKind::Asker);
14598 apply_task_choice_actions(&queue, &questions, &home);
14599 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14600
14601 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
14602 apply_task_choice_actions(&queue, &questions, &home);
14603 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
14604 }
14605
14606 #[test]
14607 fn action_standing_tells_the_reasons_apart() {
14608 let mut t = held_task_with("r1");
14609 let q = action_question("r1", ask::ChoiceAction::Requeue);
14610 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
14611 let mut plain = q.clone();
14612 plain.actions.clear();
14613 assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
14614
14615 t.mark_action_applied(&q.id);
14617 assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
14618
14619 let mut t = held_task_with("r1");
14621 t.start("r2".to_owned());
14622 assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
14623 let q2 = action_question("r2", ask::ChoiceAction::Requeue);
14625 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
14626 t.status = TaskStatus::Blocked;
14627 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
14628
14629 let mut c = action_question("r0", ask::ChoiceAction::Requeue);
14631 c.node = crate::conduct::NODE.to_owned();
14632 assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
14633 assert!(!ActionStanding::Busy.daemon_owns());
14634 }
14635
14636 #[test]
14637 fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
14638 let dir = tempfile::tempdir().unwrap();
14639 let queue = Queue::at(dir.path().join("queue"));
14640 let questions = Questions::at(dir.path().join("questions"));
14641 let home = dir.path().join("home");
14642 let mut state = run_state(RunStatus::Blocked);
14643 state.id = "20260101-000000-act4".to_owned();
14644 state.save_under(&home).unwrap();
14645 let mut t = held_task_with(&state.id);
14646 t.status = TaskStatus::Running;
14647 queue.put(&mut t).unwrap();
14648 let mut q = action_question(&state.id, ask::ChoiceAction::Done);
14649 q.cwd = Some(dir.path().display().to_string());
14650 questions.put(&mut q).unwrap();
14651
14652 let running = queue.get(&t.id).unwrap();
14655 assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
14656 assert!(matches!(
14657 crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
14658 crate::waiter::Action::Deliver(_)
14659 ));
14660 apply_task_choice_actions(&queue, &questions, &home);
14662 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
14663 let mut back = queue.get(&t.id).unwrap();
14664 back.hold_machine(Some("later".into()));
14665 queue.put(&mut back).unwrap();
14666 apply_task_choice_actions(&queue, &questions, &home);
14667 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
14668 let mut again = queue.get(&t.id).unwrap();
14669 again.hold_machine(Some("again".into()));
14670 queue.put(&mut again).unwrap();
14671 apply_task_choice_actions(&queue, &questions, &home);
14672 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14673 }
14674}