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::{CompletionActor, CompletionContext, 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 mut decision = decide_action(home, &task, &q, phrases(&language), |id| {
1633 RunState::load_under(id, home)
1634 });
1635 let completion = if matches!(decision, ActionDecision::Done) {
1636 match crate::task_completion::prepare_close(
1637 &task,
1638 home,
1639 CompletionActor::DaemonSettle,
1640 Some(format!(
1641 "Question {}: {} — {}",
1642 q.id,
1643 q.summary,
1644 q.resolution().unwrap_or_default()
1645 )),
1646 false,
1647 ) {
1648 Ok(context) => Some(context),
1649 Err(error) => {
1650 decision = ActionDecision::Refuse(error.to_string());
1651 None
1652 }
1653 }
1654 } else {
1655 None
1656 };
1657 let ran = matches!(
1658 decision,
1659 ActionDecision::Resume(_)
1660 | ActionDecision::Requeue
1661 | ActionDecision::Hold
1662 | ActionDecision::Done
1663 );
1664 if ran && asker_may_still_read(questions, &q, home) {
1665 continue;
1674 }
1675 let done = matches!(decision, ActionDecision::Done);
1676 let completed = matches!(
1679 decision,
1680 ActionDecision::Requeue | ActionDecision::Hold | ActionDecision::Done
1681 );
1682 match decision {
1683 ActionDecision::Skip => continue,
1684 ActionDecision::Resume(run) => {
1685 task.release_operator("choice", Some(&q.id));
1686 task.resume_override = Some(crate::queue::OperatorResume {
1687 question_id: q.id.clone(),
1688 at: Timestamp::now(),
1689 conductor_rehold: None,
1690 forced: true,
1691 pinned_run: Some(run),
1692 });
1693 }
1694 ActionDecision::Stale => {}
1695 ActionDecision::Requeue => {
1696 task.release_operator("choice-requeue", Some(&q.id));
1697 task.requeue();
1698 }
1699 ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1700 ActionDecision::Done => {
1701 task.succeed(completion.expect("done passed completion admission"));
1702 }
1703 ActionDecision::Refuse(why) => {
1704 let _ =
1705 crate::task_inquiry::Outbox::at(home).update_decision(&q.id, |d| d.fail(&why));
1706 if task.operator_held() {
1707 task.hold_reason = Some(match task.hold_reason.take() {
1710 Some(reason) => format!("{reason}\n\n{why}"),
1711 None => why,
1712 });
1713 } else {
1714 task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1715 task.hold_machine(Some(why));
1716 }
1717 notices::raise(
1718 Notice::warn(
1719 &format!("action:{}", q.id),
1720 "An answered task action could not be applied; the task stays held.",
1721 )
1722 .link(Link::Task {
1723 id: task.id.clone(),
1724 }),
1725 );
1726 }
1727 }
1728 task.mark_action_applied(&q.id);
1729 if completed {
1730 task.decision_effects.insert(
1731 q.id.clone(),
1732 format!("decision: {}", q.resolution().expect("answered action")),
1733 );
1734 }
1735 record(queue, &mut task);
1738 if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1739 supersede_prior_runs(&task, home);
1740 }
1741 let _ = questions.update_in(&q.id, &ownership, |r| {
1744 r.answer_delivered = true;
1745 Ok(())
1746 });
1747 }
1748}
1749
1750fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1754 let now = Timestamp::now();
1755 if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1756 return true;
1757 }
1758 q.node != crate::conduct::NODE
1759 && RunState::load_under(&q.run, home).is_ok_and(|s| {
1760 s.seats_active()
1761 .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1762 })
1763}
1764
1765fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1776 let tasks = queue.list();
1777 let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
1778 let by_id: std::collections::BTreeMap<&str, &Task> =
1779 tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1780 let referenced: Vec<&str> = tasks
1781 .iter()
1782 .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1783 .collect();
1784
1785 for mut question in questions.list_for_effects_in(&ownership) {
1786 if !question.status.open()
1787 || question.node != crate::conduct::NODE
1788 || questions.held_reply_in(&question.id, &ownership)
1789 {
1790 continue;
1791 }
1792 if referenced
1797 .iter()
1798 .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1799 {
1800 continue;
1801 }
1802 let Some(task) = by_id.get(question.run.as_str()) else {
1803 continue;
1804 };
1805 question.abandon(format!(
1806 "task {} no longer waits for this answer",
1807 task.short()
1808 ));
1809 if let Err(e) = questions.put_in(&mut question, &ownership) {
1810 tracing::warn!(
1811 "could not retire question {} for task {}: {e:#}",
1812 question.short(),
1813 task.short()
1814 );
1815 }
1816 }
1817}
1818
1819#[derive(Debug, Clone, Copy)]
1826pub struct Verdict {
1827 pub status: RunStatus,
1829 pub left_pr: bool,
1831 pub quota_hit: bool,
1833 pub parked: bool,
1835 pub no_viable_candidates: bool,
1842}
1843
1844pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1903 settle_in(task, verdict, detail, max_attempts, &PHRASES_EN, None)
1904}
1905
1906fn settle_in(
1908 task: &mut Task,
1909 verdict: Verdict,
1910 detail: &str,
1911 max_attempts: usize,
1912 p: &Phrases,
1913 state: Option<&RunState>,
1914) {
1915 if verdict.parked {
1921 task.park(detail);
1922 return;
1923 }
1924 let completion = |task: &Task| match state {
1925 Some(state) => CompletionContext::from_run(
1926 CompletionActor::DaemonSettle,
1927 Some(detail.to_owned()),
1928 task,
1929 state,
1930 ),
1931 None => CompletionContext::new(
1932 CompletionActor::DaemonSettle,
1933 Some(detail.to_owned()),
1934 &crate::run::home(),
1935 task,
1936 ),
1937 };
1938 match verdict.status {
1939 RunStatus::Merged | RunStatus::Ready
1940 if task.pr_recovery.as_ref().is_some_and(|s| {
1941 s.disposition != Some(crate::pr_recovery::Disposition::Review)
1942 }) =>
1943 {
1944 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()));
1945 }
1946 RunStatus::Merged | RunStatus::Ready => task.succeed(completion(task)),
1947 RunStatus::AlreadyInBase => task.already_landed(detail, completion(task)),
1948 RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1949 RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1950 task.stall(detail)
1951 }
1952 RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1953 RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1954 RunStatus::Blocked => task.fail(detail, max_attempts),
1955 RunStatus::VerifiedNoop => task.handed_off(detail),
1956 other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1957 }
1958}
1959
1960pub fn supersede_prior_runs(task: &Task, home: &Path) {
2009 if task
2010 .completion_history
2011 .last()
2012 .is_some_and(|event| event.discard)
2013 {
2014 return;
2015 }
2016 let now = Timestamp::now();
2017 let last_run_succeeded = task
2024 .runs
2025 .last()
2026 .and_then(|id| RunState::load_under(id, home).ok())
2027 .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
2028 for id in task.superseded_attempts(last_run_succeeded) {
2029 let mut state = match RunState::load_under(id, home) {
2030 Ok(s) => s,
2031 Err(e) => {
2032 tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
2033 continue;
2034 }
2035 };
2036 if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
2037 continue;
2038 }
2039 let daemon_claims = is_working_on(home, id, now);
2040 if state.liveness(daemon_claims) == Liveness::Live {
2041 continue;
2042 }
2043 state.status = RunStatus::Superseded;
2044 if let Err(e) = state.save_under(home) {
2045 tracing::warn!("could not mark run {id} superseded: {e:#}");
2046 }
2047 }
2048}
2049
2050fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
2072 for task in queue.list() {
2073 if task.status != TaskStatus::Done || task.runs.len() < 2 {
2074 continue;
2075 }
2076 supersede_prior_runs(&task, home);
2077 }
2078}
2079
2080fn settle_and_diagnose(
2087 task: &mut Task,
2088 verdict: Verdict,
2089 detail: &str,
2090 max_attempts: usize,
2091 state: &RunState,
2092) {
2093 let p = phrases(&state.config.graph.language);
2094 if let Some(d) = &state.merge_decision {
2097 use crate::merge_decision as md;
2098 if task
2099 .execution_runs()
2100 .last()
2101 .is_some_and(|id| id != &state.id)
2102 {
2103 return;
2104 }
2105 if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
2106 task.succeed(CompletionContext::from_run(
2107 CompletionActor::DaemonSettle,
2108 Some(format!("Owner merge decision {}: {}", d.question, d.choice)),
2109 task,
2110 state,
2111 ));
2112 } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
2113 if state.liveness(false) != Liveness::Dead {
2114 task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
2115 return;
2116 }
2117 let replacement = md::Replacement {
2118 question: d.question.clone(),
2119 run: state.id.clone(),
2120 pr: d.target.pr.clone(),
2121 agent: agent.to_owned(),
2122 context: format!(
2123 "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
2124 d.target.pr,
2125 state.id,
2126 serde_json::to_string(&state.reviews).unwrap_or_default()
2127 ),
2128 };
2129 task.requeue();
2130 task.pr_recovery = None;
2131 task.review_of = None;
2132 task.replacement = Some(replacement);
2133 } else {
2134 task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
2135 format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
2136 } 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())) }));
2137 }
2138 task.mark_action_applied(&d.question);
2139 if d.choice.eq_ignore_ascii_case(land::HOLD) {
2140 task.decision_effects
2141 .insert(d.question.clone(), format!("decision: {}", d.choice));
2142 }
2143 if let Some(pass) = state.passes.last() {
2144 task.record_pass_at(
2145 &state.id,
2146 pass.index,
2147 Some(pass.started_at),
2148 task.attempts,
2149 None,
2150 );
2151 }
2152 return;
2153 }
2154 if let Some(replacement) = &task.replacement
2155 && !state.parked
2156 && state.resource_block.is_none()
2157 && (state.viable().is_empty()
2158 || (state.status == RunStatus::Blocked && state.tally.is_none()))
2159 {
2160 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)));
2161 return;
2162 }
2163 if !verdict.parked && verdict.quota_hit && state.status == RunStatus::Stalled {
2164 let mut agents: Vec<_> = state
2165 .quota
2166 .iter()
2167 .filter(|q| {
2168 q.cause == crate::agent::QuotaCause::Authentication
2169 && state
2170 .passes
2171 .last()
2172 .is_none_or(|pass| q.at >= pass.started_at)
2173 })
2174 .map(|q| q.agent.as_str())
2175 .collect();
2176 agents.sort_unstable();
2177 agents.dedup();
2178 if !agents.is_empty() {
2179 task.stall(detail);
2180 task.notice_cause("agent-authentication", None, None);
2181 task.hold_machine(Some(format!("[authentication] Agents {} cannot authenticate; re-authenticate, then resume the held task. No attempt was spent.", agents.join(", "))));
2182 return;
2183 }
2184 }
2185 let attempts_before = task.attempts;
2186 if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
2193 let disk_checked_at = task.disk_checked_at;
2194 task.notice_cause(
2195 &format!("resource:{}:{}", block.kind, block.node),
2196 None,
2197 None,
2198 );
2199 task.last_error = Some(detail.to_owned());
2200 task.diagnostic = None;
2201 task.attempts = task.attempts.saturating_sub(1);
2202 if block.kind == "agent authentication" {
2203 task.hold_machine(Some(format!(
2204 "[authentication] {}; no attempt was spent",
2205 block.detail
2206 )));
2207 } else if block.kind == "agent usage limit" {
2208 if let Some(agent) = &state.config.graph.selected_implementer {
2210 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.")));
2211 } else {
2212 task.status = TaskStatus::Failed;
2213 task.last_error = Some(block.detail.clone());
2214 }
2215 } else if block.kind == "disk pressure" {
2216 task.hold_machine(Some(format!(
2217 "{}{}",
2218 crate::disk::RUNNING_PRESSURE,
2219 block.detail
2220 )));
2221 } else {
2222 task.hold_machine(Some(format!(
2223 "{}{}; no attempt was spent; resume to retry the affected operation",
2224 crate::cache::RESOURCE_HOLD,
2225 block.description()
2226 )));
2227 }
2228 if matches!(block.kind.as_str(), "disk pressure" | "disk admission")
2229 && matches!(block.cause, crate::run::ResourceBlockCause::Other)
2230 {
2231 task.mark_disk_capacity();
2232 task.disk_checked_at = disk_checked_at;
2233 }
2234 if let Some(pass) = state.passes.last() {
2235 task.record_pass_at(
2236 &state.id,
2237 pass.index,
2238 Some(pass.started_at),
2239 attempts_before,
2240 None,
2241 );
2242 }
2243 return;
2244 }
2245 if let Some(hold) = state.land_unrelated.as_ref().filter(|hold| {
2246 state.parked
2247 && state.status == RunStatus::Landing
2248 && state
2249 .pr_pushed_head
2250 .as_ref()
2251 .is_none_or(|h| h == &hold.head)
2252 && task.execution_runs().last() == Some(&state.id)
2253 }) {
2254 let pass = state.passes.last().map_or(0, |p| p.index);
2257 if !task
2258 .passes
2259 .iter()
2260 .any(|p| p.run == state.id && p.pass_index == pass)
2261 {
2262 task.attempts = task.attempts.saturating_sub(1);
2263 }
2264 task.hold_machine(Some(format!(
2265 "[ci-unrelated] CI failure reproduced on base; owner question {}",
2266 hold.question
2267 )));
2268 task.last_error = Some(detail.to_owned());
2269 task.diagnostic = None;
2270 task.record_pass_at(
2271 &state.id,
2272 pass,
2273 state.passes.last().map(|p| p.started_at),
2274 attempts_before,
2275 Some(crate::run::ParkCause::Question),
2276 );
2277 return;
2278 }
2279 let unresolved = task.hold_notice_cause.clone();
2280 if state.base_sync_blocked() {
2281 task.hold_machine(Some(detail.to_owned()));
2283 task.last_error = Some(detail.to_owned());
2284 } else if !verdict.parked
2285 && task
2286 .pr_recovery
2287 .as_ref()
2288 .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
2289 && matches!(
2290 verdict.status,
2291 RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
2292 )
2293 {
2294 if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
2295 task.succeed(CompletionContext::from_run(
2296 CompletionActor::DaemonSettle,
2297 Some(detail.to_owned()),
2298 task,
2299 state,
2300 ));
2301 } else {
2302 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()));
2303 }
2304 } else if !verdict.parked
2305 && task.pr_recovery.is_some()
2306 && matches!(
2307 verdict.status,
2308 RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
2309 )
2310 && !verdict.quota_hit
2311 {
2312 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.")));
2313 } else {
2314 settle_in(task, verdict, detail, max_attempts, p, Some(state));
2315 }
2316 if !verdict.parked
2317 && !verdict.quota_hit
2318 && matches!(
2319 verdict.status,
2320 RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
2321 )
2322 {
2323 task.recovery_failed(state);
2324 }
2325 if state.prep_failure.is_some() {
2326 task.hold_notice_cause = unresolved;
2329 task.startup_notice_cause("startup-candidates");
2330 }
2331 if let Some(pass) = state.passes.last() {
2334 let parked = match &pass.end {
2335 Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2336 _ => None,
2337 };
2338 task.record_pass_at(
2339 &state.id,
2340 pass.index,
2341 Some(pass.started_at),
2342 attempts_before,
2343 parked,
2344 );
2345 }
2346 if task.status == TaskStatus::Held {
2347 if state.base_sync_blocked() {
2348 task.base_sync_notice(state);
2349 } else if state.prep_failure.is_none() {
2350 task.notice_cause(
2351 label(verdict.status),
2352 Some(&state.id),
2353 state.passes.last().map(|p| p.index),
2354 );
2355 }
2356 task.diagnostic = diagnostic(state);
2357 note_open_question(task, &state.id, p);
2358 }
2359}
2360
2361fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2376 let Some(home) = crate::run::try_home() else {
2377 return;
2378 };
2379 let open = Questions::at(home.join("questions")).open_for(run);
2380 let Some(q) = open.first() else {
2381 return;
2382 };
2383 let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2384 decisions.sort_unstable();
2385 task.notice_cause(
2386 &format!("questions:{}", decisions.join(",")),
2387 Some(run),
2388 None,
2389 );
2390 let base = task.hold_reason.clone().unwrap_or_default();
2391 task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2392}
2393
2394fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2405 if let Some(request) = task.sync_only.clone() {
2406 crate::base_sync_only::settle(task, &request, last_run.as_ref(), None);
2407 return;
2408 }
2409 match last_run {
2410 Some(state) => {
2411 let verdict = Verdict {
2412 status: state.status,
2413 left_pr: state.pr.is_some(),
2414 quota_hit: state.quota.iter().any(|loss| {
2415 state
2416 .passes
2417 .last()
2418 .is_none_or(|pass| loss.at >= pass.started_at)
2419 }),
2420 parked: state.parked,
2421 no_viable_candidates: state.viable().is_empty(),
2422 };
2423 let detail = format!(
2424 "{}{}",
2425 phrases(&state.config.graph.language).recovered_running,
2426 describe(&state)
2427 );
2428 settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2429 }
2430 None => {
2431 let why = phrases(language).no_run_to_recover;
2434 task.last_error = Some(why.to_owned());
2435 task.notice_cause("missing-run", None, None);
2438 task.hold_machine(Some(why.to_owned()));
2439 }
2440 }
2441}
2442
2443fn reclaim_orphaned_running(
2465 queue: &Queue,
2466 max_attempts: usize,
2467 live_workers: &std::collections::BTreeSet<String>,
2468) -> Vec<String> {
2469 let mut reclaimed = Vec::new();
2470 for listed in queue.list() {
2471 if listed.status != TaskStatus::Running || live_workers.contains(&listed.id) {
2472 continue;
2473 }
2474 let Ok(_claim) = queue.claim(&listed.id) else {
2475 continue;
2476 };
2477 let Ok(mut task) = queue.get(&listed.id) else {
2481 continue;
2482 };
2483 if task.status != TaskStatus::Running {
2484 continue;
2485 }
2486 let last_run = task
2487 .execution_runs()
2488 .last()
2489 .and_then(|id| RunState::load(id).ok());
2490 if let Some(state) = &last_run
2500 && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2501 {
2502 tracing::warn!("abandon questions for {}: {e:#}", state.id);
2503 }
2504 let language = if last_run.is_none() {
2505 language_of(&task, Path::new("."))
2506 } else {
2507 String::new()
2508 };
2509 reclaim(&mut task, last_run, max_attempts, &language);
2510 if task.status == TaskStatus::Done {
2511 supersede_prior_runs(&task, &crate::run::home());
2512 }
2513 record(queue, &mut task);
2514 reclaimed.push(task.id.clone());
2515 }
2516 reclaimed
2517}
2518
2519fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2551 reclaim_abandoned_runs_with(
2552 home,
2553 now,
2554 crate::proc::pid_status,
2555 crate::proc::process_started_at,
2556 )
2557}
2558
2559fn reclaim_abandoned_runs_with<F, G>(
2565 home: &Path,
2566 now: Timestamp,
2567 query: F,
2568 identity: G,
2569) -> Vec<String>
2570where
2571 F: Fn(u32) -> Option<bool>,
2572 G: Fn(u32) -> Option<String>,
2573{
2574 let mut abandoned = Vec::new();
2575 for entry in std::fs::read_dir(home.join("runs"))
2576 .into_iter()
2577 .flatten()
2578 .flatten()
2579 {
2580 let id = entry.file_name().to_string_lossy().into_owned();
2581 if !crate::run::is_run_id(&id) {
2582 continue;
2583 }
2584 let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2587 continue;
2588 };
2589 let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2597 continue;
2598 };
2599 let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2600 continue;
2601 };
2602 if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2603 continue;
2604 }
2605 let daemon_claims = is_working_on(home, &id, now);
2617 if state.liveness_under_with(home, daemon_claims, &query, &identity)
2618 != crate::run::Liveness::Dead
2619 {
2620 continue;
2621 }
2622 state.abandon("daemon");
2623 if let Err(e) = state.save_under(home) {
2624 tracing::warn!("could not persist abandoned run {id}: {e:#}");
2625 continue;
2626 }
2627 if let Some(notice) = notices::run_ended(&state) {
2630 notices::raise_in(home, notice);
2631 }
2632 if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2640 tracing::warn!("abandon questions for {id}: {e:#}");
2641 }
2642 abandoned.push(id);
2643 }
2644 abandoned
2645}
2646
2647#[derive(Debug, Clone, Serialize, Deserialize)]
2648struct TaskWorker {
2649 opts: Opts,
2650 queue: PathBuf,
2651 task: String,
2652 #[serde(default)]
2653 lane: PermitKind,
2654 #[serde(default)]
2655 standalone: bool,
2656}
2657
2658fn task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2659 Ok(crate::worker::active(home)?
2660 .into_iter()
2661 .filter(|job| job.kind == "task")
2662 .collect())
2663}
2664
2665fn owned_task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2666 task_jobs(home)?
2667 .into_iter()
2668 .filter_map(
2669 |job| match serde_json::from_value::<TaskWorker>(job.payload.clone()) {
2670 Ok(request) if !request.standalone => Some(Ok(job)),
2671 Ok(_) => None,
2672 Err(error) => Some(Err(error.into())),
2673 },
2674 )
2675 .collect()
2676}
2677
2678#[must_use]
2680pub fn managed(home: &Path) -> bool {
2681 match crate::worker::active(home) {
2682 Err(error) => {
2683 tracing::error!("cannot determine scheduler ownership: {error:#}");
2684 true
2685 }
2686 Ok(jobs) if jobs.iter().any(|j| j.kind == "scheduler") => true,
2687 Ok(_) => {
2688 read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2689 && crate::worker::try_lease(home, "scheduler").map_or(true, |lease| lease.is_none())
2690 }
2691 }
2692}
2693
2694pub async fn spawn_detached(home: &Path, opts: &Opts) -> Result<crate::worker::Job> {
2696 anyhow::ensure!(
2697 crate::worker::control(home, "scheduler")?.is_none() || !managed(home),
2698 "the scheduler is stopping; wait for retirement before starting it again"
2699 );
2700 crate::worker::spawn(
2701 home,
2702 "scheduler",
2703 "scheduler",
2704 serde_json::to_value(opts.absolute()?)?,
2705 )
2706 .await
2707}
2708
2709fn park_request_path(home: &Path, job: &crate::worker::Job) -> PathBuf {
2710 home.join("worker-parks").join(format!("{}.json", job.id))
2711}
2712
2713fn request_task_park(
2714 home: &Path,
2715 job: &crate::worker::Job,
2716 cause: crate::run::ParkCause,
2717) -> Result<()> {
2718 let path = park_request_path(home, job);
2719 std::fs::create_dir_all(path.parent().context("worker park directory")?)?;
2720 std::fs::write(path, serde_json::to_vec(&cause)?)?;
2721 crate::worker::request(home, &job.key, crate::worker::Control::Park)
2722}
2723
2724pub fn request_control(home: &Path, control: crate::worker::Control) -> Result<()> {
2726 if control == crate::worker::Control::Park {
2727 for job in owned_task_jobs(home)? {
2728 request_task_park(home, &job, crate::run::ParkCause::Operator)?;
2729 }
2730 }
2731 crate::worker::request(home, "scheduler", control)
2732}
2733
2734pub(crate) fn scheduler_restart_options(home: &Path) -> Result<Option<Opts>> {
2736 if let Some(job) = crate::worker::active(home)?
2737 .into_iter()
2738 .find(|job| job.kind == "scheduler")
2739 {
2740 return serde_json::from_value(job.payload)
2741 .context("read detached scheduler options")
2742 .map(Some);
2743 }
2744 if read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2745 && crate::worker::try_lease(home, "scheduler")?.is_none()
2746 {
2747 let path = home.join("scheduler-options.json");
2748 let body = std::fs::read(&path).with_context(|| format!("read {}", path.display()))?;
2749 return serde_json::from_slice(&body)
2750 .context("decode detached scheduler options")
2751 .map(Some);
2752 }
2753 Ok(None)
2754}
2755
2756pub async fn restart_detached(home: &Path) -> Result<()> {
2758 let Some(opts) = scheduler_restart_options(home)? else {
2759 return Ok(());
2760 };
2761 request_control(home, crate::worker::Control::Stop)?;
2762 loop {
2763 let reserved = crate::worker::active(home)?
2764 .iter()
2765 .any(|job| job.kind == "scheduler");
2766 if !reserved && crate::worker::try_lease(home, "scheduler")?.is_some() {
2767 break;
2768 }
2769 tokio::time::sleep(Duration::from_millis(100)).await;
2770 }
2771 spawn_detached(home, &opts).await?;
2772 Ok(())
2773}
2774
2775pub async fn run_scheduler_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2777 let opts: Opts = serde_json::from_value(payload)?;
2778 let _ = home;
2779 serve_until(opts, Stop::new()).await
2780}
2781
2782pub async fn run_task_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2784 let request: TaskWorker = serde_json::from_value(payload)?;
2785 let queue = Queue::at(request.queue);
2786 let key = format!("task:{}", request.task);
2787 let job = task_jobs(home)?
2788 .into_iter()
2789 .find(|job| job.key == key)
2790 .context("task worker reservation is missing")?;
2791 let park_path = park_request_path(home, &job);
2792 let _claim = loop {
2795 match queue.claim(&request.task) {
2796 Ok(claim) => break claim,
2797 Err(e) if e.chain().any(|c| c.is::<std::io::Error>()) => {
2800 return Err(e.context("claim the task for its worker"));
2801 }
2802 Err(_) => {
2803 sweep_stale_claims(&queue, STALE_CLAIM);
2804 tokio::time::sleep(Duration::from_millis(50)).await;
2805 }
2806 }
2807 };
2808 let mut task = queue.get(&request.task)?;
2809 if !task.status.runnable()
2810 || (!request.standalone
2811 && request.lane
2812 != permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent))
2813 {
2814 return Ok(());
2815 }
2816 let stop = Stop::new();
2817 let watcher = {
2818 let home = home.to_path_buf();
2819 let stop = stop.clone();
2820 let park_path = park_path.clone();
2821 tokio::spawn(async move {
2822 loop {
2823 if crate::worker::control(&home, &key).ok().flatten().is_some() {
2824 let cause = std::fs::read(&park_path)
2825 .ok()
2826 .and_then(|body| serde_json::from_slice(&body).ok())
2827 .unwrap_or(crate::run::ParkCause::Operator);
2828 stop.park(cause);
2829 return;
2830 }
2831 tokio::time::sleep(Duration::from_millis(200)).await;
2832 }
2833 })
2834 };
2835 let quota = if request.standalone {
2836 run_claimed_until(&request.opts, &queue, &mut task, &stop).await
2837 } else {
2838 let status = Arc::new(Mutex::new(Status::new()));
2839 Box::pin(attempt(
2840 &request.opts,
2841 &queue,
2842 &status,
2843 &stop,
2844 crate::graph::Pause::new(),
2845 &mut task,
2846 ))
2847 .await
2848 };
2849 watcher.abort();
2850 let _ = std::fs::remove_file(park_path);
2851 persist_cooldown(home, "a).await?;
2852 Ok(())
2853}
2854
2855pub async fn spawn_claimed(
2858 home: &Path,
2859 opts: &Opts,
2860 queue: &Queue,
2861 task: &Task,
2862 claim: crate::queue::Claim,
2863) -> Result<crate::worker::Job> {
2864 let request = TaskWorker {
2865 opts: opts.absolute()?,
2866 queue: std::path::absolute(queue.root())?,
2867 task: task.id.clone(),
2868 lane: permit_kind(land_resume_state(task) == LandResume::Ready, task.urgent),
2869 standalone: true,
2870 };
2871 let job = crate::worker::spawn(
2872 home,
2873 "task",
2874 &format!("task:{}", task.id),
2875 serde_json::to_value(request)?,
2876 )
2877 .await?;
2878 drop(claim);
2879 Ok(job)
2880}
2881
2882pub async fn run_detached_claimed(
2885 opts: &Opts,
2886 queue: &Queue,
2887 task: &mut Task,
2888 claim: crate::queue::Claim,
2889) -> Result<()> {
2890 let home = crate::run::home();
2891 let job = spawn_claimed(&home, opts, queue, task, claim).await?;
2892 loop {
2893 crate::worker::active(&home)?;
2896 let current = crate::worker::get(&home, &job.id)?;
2897 if matches!(
2898 current.status,
2899 crate::worker::Status::Finished | crate::worker::Status::Failed
2900 ) {
2901 *task = queue.get(&task.id)?;
2902 anyhow::ensure!(
2903 current.status != crate::worker::Status::Failed,
2904 "task worker failed: {}",
2905 current.result.as_deref().unwrap_or("unknown failure")
2906 );
2907 return Ok(());
2908 }
2909 tokio::time::sleep(Duration::from_millis(200)).await;
2910 }
2911}
2912
2913async fn persist_cooldown(home: &Path, quota: &[QuotaLoss]) -> Result<()> {
2914 if let Some(until) = cooldown_until(quota, Timestamp::now()) {
2915 let _lease = loop {
2916 if let Some(lease) = crate::worker::try_lease(home, "task-quota-cooldown")? {
2917 break lease;
2918 }
2919 tokio::time::sleep(Duration::from_millis(10)).await;
2920 };
2921 if read_cooldown(home)?.is_none_or(|previous| previous < until) {
2922 let path = home.join("task-quota-cooldown.json");
2923 let temporary = path.with_extension("json.tmp");
2924 std::fs::write(&temporary, serde_json::to_vec(&until)?)?;
2925 std::fs::rename(temporary, path)?;
2926 }
2927 }
2928 Ok(())
2929}
2930
2931fn read_cooldown(home: &Path) -> Result<Option<Timestamp>> {
2932 match std::fs::read(home.join("task-quota-cooldown.json")) {
2933 Ok(body) => Ok(Some(serde_json::from_slice(&body)?)),
2934 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
2935 Err(error) => Err(error.into()),
2936 }
2937}
2938
2939pub async fn serve(opts: Opts) -> Result<()> {
2945 tracing::info!(
2946 "automatic update and restart requires magi web; standalone serve does not restart"
2947 );
2948 serve_until(opts, Stop::new()).await
2949}
2950
2951pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
2962 let opts = opts.absolute()?;
2963 let home = crate::run::home();
2964 let _scheduler = crate::worker::try_lease(&home, "scheduler")?
2965 .context("another scheduler already owns this home")?;
2966 if let Some(reading) = read_status(&home)
2967 && legacy_scheduler_running(&reading, Timestamp::now(), std::process::id())
2968 {
2969 bail!("a legacy scheduler is still running; stop it before starting independent dispatch");
2970 }
2971 if !crate::worker::active(&home)?
2972 .iter()
2973 .any(|job| job.kind == "scheduler")
2974 {
2975 crate::worker::clear_control(&home, "scheduler")?;
2976 }
2977 std::fs::write(
2978 home.join("scheduler-options.json"),
2979 serde_json::to_vec(&opts)?,
2980 )?;
2981 let control = {
2982 let home = home.clone();
2983 let stop = stop.clone();
2984 tokio::spawn(async move {
2985 loop {
2986 match crate::worker::control(&home, "scheduler").ok().flatten() {
2987 Some(crate::worker::Control::Park) => {
2988 let _ = request_control(&home, crate::worker::Control::Park);
2989 stop.park(crate::run::ParkCause::Operator);
2990 break;
2991 }
2992 Some(crate::worker::Control::Stop) => {
2993 stop.stop();
2994 break;
2995 }
2996 None => {}
2997 }
2998 tokio::time::sleep(Duration::from_millis(100)).await;
2999 }
3000 })
3001 };
3002 let signal = {
3003 let stop = stop.clone();
3004 tokio::spawn(async move {
3005 if tokio::signal::ctrl_c().await.is_ok() {
3006 stop.stop();
3007 tracing::info!("scheduler shutdown requested; independent workers continue");
3008 }
3009 })
3010 };
3011
3012 let worktrees_root = opts
3013 .worktrees_root
3014 .clone()
3015 .unwrap_or_else(crate::run::default_worktree_root);
3016 let outcome = drive(
3017 &opts,
3018 &Queue::open(),
3019 &status_path(),
3020 &crate::run::home(),
3021 &worktrees_root,
3022 &stop,
3023 )
3024 .await;
3025
3026 signal.abort();
3027 control.abort();
3028 outcome
3029}
3030
3031async fn drive(
3044 opts: &Opts,
3045 queue: &Queue,
3046 status_file: &Path,
3047 home: &Path,
3048 worktrees_root: &Path,
3049 stop: &Stop,
3050) -> Result<()> {
3051 let recovery_cfg = prepare(&opts.repo, opts).ok();
3059 let daemon_cfg = recovery_cfg
3060 .as_ref()
3061 .map(|c| c.daemon.clone())
3062 .unwrap_or_default();
3063 let reconciled = crate::driver::reconcile(home);
3064 if !reconciled.is_empty() {
3065 tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
3066 }
3067 let mut initial_status = Status::new();
3068 let owned = owned_task_jobs(home)?;
3069 initial_status.current = current_work(home, Timestamp::now())
3070 .into_iter()
3071 .filter(|current| {
3072 owned
3073 .iter()
3074 .any(|job| job.key.strip_prefix("task:") == Some(current.task.as_str()))
3075 })
3076 .collect();
3077 initial_status.idle = initial_status.current.is_empty();
3078 initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
3079 recovery_cfg.as_ref(),
3080 daemon_cfg.max_deputies,
3081 ));
3082 let status = Arc::new(Mutex::new(initial_status));
3083 write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
3084 let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
3085
3086 let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
3092
3093 tracing::info!(
3094 "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
3095 queue.root().display(),
3096 opts.poll.as_secs(),
3097 opts.max_attempts,
3098 concurrency,
3099 if daemon_cfg.pause_for_interrupts {
3100 ", interrupts enabled"
3101 } else {
3102 ""
3103 }
3104 );
3105
3106 let outcome = tokio::select! {
3107 outcome = poll(opts, queue, &status, home, worktrees_root, stop, DispatchLimits {
3108 max_concurrent: concurrency,
3109 pause_for_interrupts: daemon_cfg.pause_for_interrupts,
3110 recovery_cfg,
3111 }) => outcome,
3112 () = async {
3113 while !stop.stopped() {
3114 tokio::time::sleep(Duration::from_millis(25)).await;
3115 }
3116 } => {
3117 if stop.parking() {
3118 request_control(home, crate::worker::Control::Park)?;
3119 }
3120 Ok(())
3121 }
3122 };
3123
3124 stop.busy.store(0, Ordering::SeqCst);
3125 beat.abort();
3126 clear_status_at(status_file);
3127 outcome
3128}
3129
3130pub(crate) fn release_watch_settings_from_config(
3133 home: &Path,
3134 repo: &Path,
3135 cfg: &Config,
3136) -> (Vec<PathBuf>, u64) {
3137 let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
3138 .into_iter()
3139 .map(|r| r.path)
3140 .collect();
3141 let mut known: Vec<PathBuf> = Queue::at(home.join("queue"))
3144 .list()
3145 .into_iter()
3146 .map(|t| t.repo)
3147 .collect();
3148 let runs = home.join("runs");
3149 for id in crate::run::list_ids_in(&runs) {
3150 let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
3151 .ok()
3152 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
3153 .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
3154 known.extend(repo);
3155 }
3156 for k in known {
3157 let k = k.canonicalize().unwrap_or(k);
3158 if k.join(".git").exists() && !paths.contains(&k) {
3159 paths.push(k);
3160 }
3161 }
3162 let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
3163 if !paths.contains(&own) {
3164 paths.push(own);
3165 }
3166 (paths, cfg.daemon.release_stall_minutes)
3167}
3168
3169const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
3171
3172async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
3178 loop {
3179 tokio::time::sleep(HEARTBEAT).await;
3180 let snapshot = {
3181 let mut guard = lock(&status);
3182 guard.updated_at = Timestamp::now();
3183 guard.clone()
3184 };
3185 if let Err(e) = write_status_to(&path, &snapshot) {
3186 tracing::warn!("could not refresh the daemon status file: {e:#}");
3189 }
3190 }
3191}
3192
3193#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3196enum LandResume {
3197 NotLanding,
3200 StillWaiting,
3205 Ready,
3209}
3210
3211fn land_resume_state(task: &Task) -> LandResume {
3215 if task.sync_only.is_some() {
3216 return LandResume::NotLanding;
3217 }
3218 let Some(run_id) = task.execution_runs().last() else {
3219 return LandResume::NotLanding;
3220 };
3221 let Ok(state) = RunState::load(run_id) else {
3222 return LandResume::NotLanding;
3223 };
3224 if !state.parked {
3225 return LandResume::NotLanding;
3226 }
3227 if state.status == RunStatus::Landing
3228 && state.land_approval.as_ref().is_some_and(|binding| {
3229 ask::Questions::open()
3230 .get_for_effects(&binding.question)
3231 .is_ok_and(|q| {
3232 q.run == state.id
3233 && q.resolution()
3234 .as_deref()
3235 .is_some_and(crate::merge_decision::stops)
3236 })
3237 })
3238 {
3239 return LandResume::Ready;
3240 }
3241 if !implementers_match(task, &state) {
3242 return LandResume::NotLanding;
3243 }
3244 let node = if state.status == RunStatus::Landing {
3248 land::APPROVAL_NODE
3249 } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
3250 crate::github_text::ASK_NODE
3251 } else {
3252 return LandResume::NotLanding;
3253 };
3254 let store = ask::Questions::open();
3255 let waiting = store
3256 .list_for_effects()
3257 .into_iter()
3258 .filter(|q| &q.run == run_id && q.node == node)
3259 .max_by(|a, b| a.id.cmp(&b.id));
3260 let Some(mut q) = waiting else {
3261 return LandResume::Ready;
3262 };
3263 if !q.status.open() {
3264 if q.resolution().as_deref() == Some(land::REPAIR) {
3267 return if state.liveness(false) == Liveness::Live {
3268 LandResume::StillWaiting
3269 } else {
3270 LandResume::NotLanding
3271 };
3272 }
3273 return LandResume::Ready;
3274 }
3275 let timeout = Duration::from_secs(state.config.graph.answer_timeout);
3282 let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
3283 if !store.held_reply(&q.id) && elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
3284 q.abandon(format!(
3285 "no answer within {}s of asking",
3286 timeout.as_secs().max(1)
3287 ));
3288 if store.put(&mut q).is_ok() {
3291 return LandResume::Ready;
3292 }
3293 }
3294 LandResume::StillWaiting
3295}
3296
3297const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
3305
3306const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
3318
3319#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3332enum Interrupt {
3333 Idle,
3335 Parking {
3347 parked: Vec<String>,
3348 interrupt_task: String,
3349 },
3350 Running {
3358 parked: Vec<String>,
3359 interrupt_task: String,
3360 },
3361 Resuming { parked: Vec<String> },
3368}
3369
3370fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
3391 match state {
3392 Interrupt::Idle => {
3393 if in_flight.len() != 1 {
3405 return Interrupt::Idle;
3406 }
3407 match runnable.iter().find(|t| t.interrupt) {
3408 Some(t) => Interrupt::Parking {
3409 parked: in_flight.to_vec(),
3410 interrupt_task: t.id.clone(),
3411 },
3412 None => Interrupt::Idle,
3413 }
3414 }
3415 Interrupt::Parking {
3416 parked,
3417 interrupt_task,
3418 } => {
3419 if in_flight.iter().any(|id| parked.contains(id)) {
3420 Interrupt::Parking {
3422 parked,
3423 interrupt_task,
3424 }
3425 } else if in_flight.contains(&interrupt_task) {
3426 Interrupt::Running {
3427 parked,
3428 interrupt_task,
3429 }
3430 } else if runnable.iter().any(|t| t.id == interrupt_task) {
3431 Interrupt::Parking {
3435 parked,
3436 interrupt_task,
3437 }
3438 } else {
3439 Interrupt::Resuming { parked }
3444 }
3445 }
3446 Interrupt::Running {
3447 parked,
3448 interrupt_task,
3449 } => {
3450 if in_flight.contains(&interrupt_task) {
3451 Interrupt::Running {
3452 parked,
3453 interrupt_task,
3454 }
3455 } else {
3456 Interrupt::Resuming { parked }
3462 }
3463 }
3464 Interrupt::Resuming { parked } => {
3465 if in_flight.iter().any(|id| parked.contains(id)) {
3466 Interrupt::Idle
3472 } else if runnable.iter().any(|t| parked.contains(&t.id)) {
3473 Interrupt::Resuming { parked }
3474 } else {
3475 Interrupt::Idle
3478 }
3479 }
3480 }
3481}
3482
3483fn advance_interrupt_tick(
3489 enabled: bool,
3490 state: Interrupt,
3491 in_flight: &[String],
3492 runnable: &[Task],
3493) -> Interrupt {
3494 if !enabled {
3495 return Interrupt::Idle;
3496 }
3497 advance_interrupt(state, in_flight, runnable)
3498}
3499
3500fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
3505 match state {
3506 Interrupt::Idle => candidates,
3507 Interrupt::Parking {
3508 parked,
3509 interrupt_task,
3510 } => {
3511 if in_flight.iter().any(|id| parked.contains(id)) {
3512 Vec::new()
3513 } else {
3514 candidates
3515 .into_iter()
3516 .filter(|t| &t.id == interrupt_task)
3517 .collect()
3518 }
3519 }
3520 Interrupt::Running { .. } => Vec::new(),
3521 Interrupt::Resuming { parked } => candidates
3529 .into_iter()
3530 .find(|t| parked.contains(&t.id))
3531 .into_iter()
3532 .collect(),
3533 }
3534}
3535
3536struct DispatchLimits {
3540 max_concurrent: usize,
3543 pause_for_interrupts: bool,
3545 recovery_cfg: Option<Config>,
3546}
3547
3548#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3557enum PermitKind {
3558 None,
3563 Urgent,
3570 #[default]
3573 Ordinary,
3574}
3575
3576fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
3579 if priority {
3580 PermitKind::None
3581 } else if urgent {
3582 PermitKind::Urgent
3583 } else {
3584 PermitKind::Ordinary
3585 }
3586}
3587
3588fn available_slots(requests: &[TaskWorker], limit: usize) -> (usize, usize) {
3589 let (ordinary, urgent) = requests.iter().filter(|request| !request.standalone).fold(
3590 (0usize, 0usize),
3591 |(ordinary, urgent), request| match request.lane {
3592 PermitKind::Ordinary => (ordinary + 1, urgent),
3593 PermitKind::Urgent => (ordinary, urgent + 1),
3594 PermitKind::None => (ordinary, urgent),
3595 },
3596 );
3597 (
3598 limit.saturating_sub(ordinary),
3599 1usize.saturating_sub(urgent),
3600 )
3601}
3602
3603#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
3605enum SkipReason {
3606 ClaimUnavailable,
3607 RereadFailed,
3608 NoLongerRunnable,
3609 WaitingOnLanding,
3610 CoolingDown,
3611 OrdinaryCapacity,
3612 UrgentCapacity,
3613 InterruptGate,
3614}
3615
3616impl SkipReason {
3617 fn key(self) -> &'static str {
3618 match self {
3619 Self::ClaimUnavailable => "claim_unavailable",
3620 Self::RereadFailed => "reread_failed",
3621 Self::NoLongerRunnable => "no_longer_runnable",
3622 Self::WaitingOnLanding => "waiting_on_landing",
3623 Self::CoolingDown => "cooling_down",
3624 Self::OrdinaryCapacity => "ordinary_capacity",
3625 Self::UrgentCapacity => "urgent_capacity",
3626 Self::InterruptGate => "interrupt_gate",
3627 }
3628 }
3629
3630 fn describe(self) -> &'static str {
3631 match self {
3632 Self::ClaimUnavailable => "could not claim it (held elsewhere or claim failed)",
3633 Self::RereadFailed => "could not re-read it",
3634 Self::NoLongerRunnable => "no longer runnable",
3635 Self::WaitingOnLanding => "waiting on landing",
3636 Self::CoolingDown => "quota cooldown",
3637 Self::OrdinaryCapacity => "no free ordinary slot",
3638 Self::UrgentCapacity => "urgent slot busy",
3639 Self::InterruptGate => "withheld by the interrupt sequence",
3640 }
3641 }
3642}
3643
3644#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3646pub struct DispatchReasonCount {
3647 pub reason: String,
3649 pub count: usize,
3651}
3652
3653#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3655pub struct DispatchWait {
3656 pub runnable: usize,
3658 pub reasons: Vec<DispatchReasonCount>,
3660}
3661
3662type DispatchSkips = std::collections::BTreeSet<(String, SkipReason)>;
3663
3664fn aggregate_dispatch_wait(runnable: usize, skips: &DispatchSkips) -> Option<DispatchWait> {
3665 if runnable == 0 {
3666 return None;
3667 }
3668 let mut counts = std::collections::BTreeMap::new();
3669 for (_, reason) in skips {
3670 *counts.entry(*reason).or_insert(0usize) += 1;
3671 }
3672 let mut counts: Vec<_> = counts.into_iter().collect();
3673 counts.sort_by(|(a, n), (b, m)| m.cmp(n).then(a.cmp(b)));
3674 Some(DispatchWait {
3675 runnable,
3676 reasons: counts
3677 .into_iter()
3678 .map(|(reason, count)| DispatchReasonCount {
3679 reason: reason.key().to_owned(),
3680 count,
3681 })
3682 .collect(),
3683 })
3684}
3685
3686fn interrupt_skips(before: &[String], after: &[Task]) -> DispatchSkips {
3687 before
3688 .iter()
3689 .filter(|id| !after.iter().any(|task| &task.id == *id))
3690 .map(|id| (id.clone(), SkipReason::InterruptGate))
3691 .collect()
3692}
3693
3694fn changed_dispatch_skips(previous: &mut DispatchSkips, current: DispatchSkips) -> bool {
3695 if *previous == current {
3696 return false;
3697 }
3698 *previous = current;
3699 true
3700}
3701
3702struct DispatchClaim {
3703 task: Task,
3704 claim: crate::queue::Claim,
3705 permit: Option<tokio::sync::OwnedSemaphorePermit>,
3706}
3707
3708fn claim_dispatch(
3711 queue: &Queue,
3712 candidate: &Task,
3713 cooling_down: bool,
3714 ordinary: &Arc<tokio::sync::Semaphore>,
3715 urgent: &Arc<tokio::sync::Semaphore>,
3716) -> std::result::Result<DispatchClaim, SkipReason> {
3717 let claim = queue
3718 .claim(&candidate.id)
3719 .map_err(|_| SkipReason::ClaimUnavailable)?;
3720 let task = match queue.get(&candidate.id) {
3721 Ok(t) if t.status.runnable() => t,
3722 Ok(_) => return Err(SkipReason::NoLongerRunnable),
3723 Err(e) => {
3724 tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
3725 return Err(SkipReason::RereadFailed);
3726 }
3727 };
3728 let resume = land_resume_state(&task);
3729 if resume == LandResume::StillWaiting {
3730 return Err(SkipReason::WaitingOnLanding);
3731 }
3732 let priority = resume == LandResume::Ready;
3733 if !priority && cooling_down {
3734 return Err(SkipReason::CoolingDown);
3735 }
3736 let permit = match permit_kind(priority, task.urgent) {
3739 PermitKind::None => None,
3740 PermitKind::Urgent => Some(
3741 Arc::clone(urgent)
3742 .try_acquire_owned()
3743 .map_err(|_| SkipReason::UrgentCapacity)?,
3744 ),
3745 PermitKind::Ordinary => Some(
3746 Arc::clone(ordinary)
3747 .try_acquire_owned()
3748 .map_err(|_| SkipReason::OrdinaryCapacity)?,
3749 ),
3750 };
3751 let stamp = Timestamp::now();
3754 let mut task = task;
3755 task.dispatched_at = Some(stamp);
3756 if let Err(e) = queue.modify(&task.id, |t| {
3757 t.dispatched_at = Some(stamp);
3758 true
3759 }) {
3760 tracing::warn!("could not record dispatch order of {}: {e:#}", task.short());
3761 }
3762 Ok(DispatchClaim {
3763 task,
3764 claim,
3765 permit,
3766 })
3767}
3768
3769#[derive(Serialize, Deserialize)]
3788struct ServiceWorker {
3789 opts: Opts,
3790 queue: PathBuf,
3791 worktrees_root: PathBuf,
3792 operation: String,
3793}
3794
3795fn load_conductor(home: &Path) -> Result<Conductor> {
3796 match std::fs::read(home.join("conductor-state.json")) {
3797 Ok(body) => serde_json::from_slice(&body).context("read conductor state"),
3798 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Conductor::new()),
3799 Err(error) => Err(error.into()),
3800 }
3801}
3802
3803fn conductor_work(queue: &Queue, home: &Path) -> (Vec<Task>, Vec<Task>, Vec<Task>) {
3804 let live: std::collections::BTreeSet<_> = current_work(home, Timestamp::now())
3805 .into_iter()
3806 .map(|c| c.task)
3807 .collect();
3808 let stalled = stalled_tasks(queue, home, Timestamp::now());
3809 let stalled_ids: std::collections::BTreeSet<_> = stalled.iter().map(|t| t.id.clone()).collect();
3810 let finished = finished_tasks(queue)
3811 .into_iter()
3812 .filter(|t| !live.contains(&t.id) && !stalled_ids.contains(&t.id))
3813 .filter(|t| !awaiting_resume_with(t, |id| RunState::load_under(id, home)))
3814 .collect();
3815 let queued = queued_tasks(queue)
3816 .into_iter()
3817 .filter(|t| !live.contains(&t.id))
3818 .collect();
3819 (queued, stalled, finished)
3820}
3821
3822fn retention_service_receipt(
3825 home: &Path,
3826 operation: &str,
3827 phase: &str,
3828 outcome: &str,
3829 detail: &str,
3830 cfg: Option<&Config>,
3831) {
3832 if !matches!(operation, "housekeeping" | "disk-pressure") {
3833 return;
3834 }
3835 let receipt = serde_json::json!({"checked_at": Timestamp::now(),
3836 "version": env!("CARGO_PKG_VERSION"), "pid": std::process::id(),
3837 "operation": operation, "outcome": outcome, "detail": detail,
3838 "auto_fold": cfg.map(|c| c.disk.auto_fold),
3839 "reclaim_bytes": cfg.map(|c| c.disk.worktree_reclaim_bytes)});
3840 if let Err(error) = crate::fold_evidence::atomic_write(
3841 &home.join(format!("source-eviction-{operation}-{phase}.json")),
3842 &serde_json::to_vec(&receipt).expect("service receipt"),
3843 ) {
3844 tracing::warn!("retention service receipt failed: {error:#}");
3845 }
3846}
3847
3848async fn start_service(
3849 home: &Path,
3850 opts: &Opts,
3851 queue: &Queue,
3852 worktrees_root: &Path,
3853 operation: &str,
3854 cfg: Option<&Config>,
3855 busy: bool,
3856) -> Result<()> {
3857 let fetch_cfg = if operation == "fetch" {
3860 match prepare(&opts.repo, opts) {
3861 Ok(cfg) => Some(cfg),
3862 Err(error) => {
3863 tracing::warn!("could not reload periodic fetch configuration: {error:#}");
3864 return Ok(());
3865 }
3866 }
3867 } else {
3868 None
3869 };
3870 let cfg = fetch_cfg.as_ref().or(cfg);
3871 let ticks = home.join("service-ticks");
3872 std::fs::create_dir_all(&ticks)?;
3873 let receipt = ticks.join(format!("daemon-{operation}"));
3874 let last = std::fs::read(&receipt)
3875 .ok()
3876 .and_then(|body| serde_json::from_slice::<Timestamp>(&body).ok());
3877 let interval = match operation {
3878 "disk-pressure" => 30,
3879 "chat-goals" => 60,
3880 "cache" => CACHE_CHECK_INTERVAL_SECS,
3881 "fetch" => cfg.map_or(60, |cfg| cfg.repos.fetch_interval.max(1)),
3882 _ => opts.poll.as_secs().max(1),
3883 };
3884 let now = Timestamp::now();
3885 if !cache_check_due(last, now, interval) {
3886 retention_service_receipt(
3887 home,
3888 operation,
3889 "dispatch",
3890 "skipped",
3891 "cadence not due",
3892 cfg,
3893 );
3894 return Ok(());
3895 }
3896 let key = format!("service:daemon-{operation}");
3897 if crate::worker::active(home)?
3898 .iter()
3899 .any(|job| job.key == key)
3900 {
3901 retention_service_receipt(
3902 home,
3903 operation,
3904 "dispatch",
3905 "skipped",
3906 "service worker already active",
3907 cfg,
3908 );
3909 return Ok(());
3910 }
3911 let eligible = match operation {
3912 "conductor" => {
3913 let (queued, stalled, finished) = conductor_work(queue, home);
3914 !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3915 && load_conductor(home)?.worth_a_look(queue, &stalled, &finished)
3916 }
3917 "maintenance" => {
3918 queue.list().iter().any(|task| {
3919 crate::triage::disk_wait_eligible(task)
3920 && task
3921 .disk_checked_at
3922 .is_none_or(|at| now.as_second() - at.as_second() >= 60)
3923 }) || Questions::at(home.join("questions"))
3924 .list_for_effects()
3925 .iter()
3926 .any(|q| {
3927 q.chosen_action().is_some_and(|action| action.maintenance())
3928 && !home
3929 .join("choice-actions")
3930 .join(format!("{}.json", q.id))
3931 .exists()
3932 })
3933 }
3934 "housekeeping" => !busy && runnable(queue).is_empty(),
3935 "cache" => {
3936 !busy
3937 && !runnable(queue).is_empty()
3938 && cfg.is_some_and(|cfg| cfg.disk.cache_limit_bytes > 0)
3939 }
3940 "disk-pressure" => busy,
3941 "fetch" => {
3942 cfg.is_some_and(|cfg| cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty())
3943 }
3944 "chat-goals" => crate::talk::Talks::at(home.join("talks"))
3945 .list()
3946 .iter()
3947 .any(|talk| {
3948 talk.status.open()
3949 && talk.pending.is_empty()
3950 && talk.pending_attachments.is_empty()
3951 && talk.goals.iter().any(|goal| goal.active())
3952 }),
3953 _ => false,
3954 };
3955 if !eligible {
3956 retention_service_receipt(
3957 home,
3958 operation,
3959 "dispatch",
3960 "skipped",
3961 if operation == "housekeeping" {
3962 "active work or runnable task queue"
3963 } else {
3964 "no active work; idle housekeeping owns scan"
3965 },
3966 cfg,
3967 );
3968 return Ok(());
3969 }
3970 retention_service_receipt(
3971 home,
3972 operation,
3973 "dispatch",
3974 "launching",
3975 "eligible and cadence due",
3976 cfg,
3977 );
3978 let request = ServiceWorker {
3979 opts: opts.absolute()?,
3980 queue: std::path::absolute(queue.root())?,
3981 worktrees_root: std::path::absolute(worktrees_root)?,
3982 operation: operation.to_owned(),
3983 };
3984 if let Err(error) =
3985 crate::worker::spawn(home, "daemon-service", &key, serde_json::to_value(request)?).await
3986 {
3987 retention_service_receipt(
3988 home,
3989 operation,
3990 "dispatch",
3991 "error",
3992 &format!("worker launch: {error:#}"),
3993 cfg,
3994 );
3995 tracing::warn!(operation, "could not launch daemon service: {error:#}");
3996 }
3997 std::fs::write(receipt, serde_json::to_vec(&now)?)?;
3998 Ok(())
3999}
4000
4001pub async fn run_service_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
4004 let request: ServiceWorker = serde_json::from_value(payload)?;
4005 let opts = &request.opts;
4006 let queue = Queue::at(request.queue);
4007 let questions = Questions::at(home.join("questions"));
4008 match request.operation.as_str() {
4009 "chat-goals" => {
4010 let talks = crate::talk::Talks::at(home.join("talks"));
4011 crate::chat_goal_runtime::sweep(&talks, false).await;
4012 }
4013 "maintenance" => {
4014 apply_maintenance_choices(&queue, &questions, home).await;
4015 triage::monitor_disk_waits(
4016 &queue,
4017 &questions,
4018 opts.config.as_deref(),
4019 Timestamp::now(),
4020 );
4021 }
4022 "conductor" => {
4023 let path = home.join("conductor-state.json");
4024 let mut conductor = load_conductor(home)?;
4025 let (queued, stalled, finished) = conductor_work(&queue, home);
4026 if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
4027 && conductor.worth_a_look(&queue, &stalled, &finished)
4028 {
4029 let cfg = prepare(&opts.repo, opts)?;
4030 conductor
4031 .maybe_run(
4032 &cfg,
4033 &opts.repo,
4034 &queue,
4035 &questions,
4036 home,
4037 &queued,
4038 &stalled,
4039 &finished,
4040 opts.max_attempts,
4041 )
4042 .await;
4043 let temporary = path.with_extension("json.tmp");
4044 std::fs::write(&temporary, serde_json::to_vec(&conductor)?)?;
4045 std::fs::rename(temporary, path)?;
4046 }
4047 }
4048 "fetch" => {
4049 let cfg = prepare(&opts.repo, opts)?;
4050 if cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty() {
4051 let outcome = clean::fetch_origins(&cfg.repos.roots, FETCH_TIMEOUT, || false).await;
4052 tracing::debug!("fetch origins: {outcome:?}");
4053 }
4054 }
4055 "cache" => {
4056 if task_jobs(home)?.is_empty() {
4057 let mut checked = None;
4058 maybe_prune_cache_between_runs(
4059 &opts.repo,
4060 opts,
4061 home,
4062 &Stop::new(),
4063 &mut checked,
4064 Timestamp::now(),
4065 )
4066 .await;
4067 }
4068 }
4069 "disk-pressure" => {
4070 if let Ok(cfg) = prepare(&opts.repo, opts) {
4071 retention_service_receipt(
4072 home,
4073 "disk-pressure",
4074 "worker",
4075 "running",
4076 "retention sweep",
4077 Some(&cfg),
4078 );
4079 crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
4080 if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
4081 tracing::warn!("disk pressure cache cleanup failed: {e:#}");
4082 }
4083 if let Err(e) = crate::build_target::prune_registered(home, &cfg.disk) {
4084 tracing::warn!("disk pressure isolated build cleanup failed: {e:#}");
4085 }
4086 for current in current_work(home, Timestamp::now()) {
4087 if let Ok(state) = RunState::load_under(¤t.run, home)
4088 && let Some(reason) = disk_gate(&state.repo, &state.config)
4089 {
4090 for job in owned_task_jobs(home)?.into_iter().filter(|job| {
4091 job.key.strip_prefix("task:") == Some(current.task.as_str())
4092 }) {
4093 request_task_park(
4094 home,
4095 &job,
4096 crate::run::ParkCause::Interrupt {
4097 reason: reason.clone(),
4098 },
4099 )?;
4100 }
4101 notices::raise_in(
4102 home,
4103 Notice::warn(
4104 "disk:pressure",
4105 "Disk pressure persists after cleanup; active workers were asked to checkpoint and park. New starts and resumes wait for free space.",
4106 ),
4107 );
4108 }
4109 }
4110 } else {
4111 retention_service_receipt(
4112 home,
4113 "disk-pressure",
4114 "worker",
4115 "error",
4116 "configuration could not be loaded",
4117 None,
4118 );
4119 }
4120 }
4121 "housekeeping" => {
4122 if task_jobs(home)?.is_empty() {
4123 match prepare(&opts.repo, opts) {
4124 Ok(cfg) => {
4125 retention_service_receipt(
4126 home,
4127 "housekeeping",
4128 "worker",
4129 "running",
4130 "retention sweep",
4131 Some(&cfg),
4132 );
4133 crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
4134 }
4135 Err(error) => retention_service_receipt(
4136 home,
4137 "housekeeping",
4138 "worker",
4139 "error",
4140 &format!("configuration: {error:#}"),
4141 None,
4142 ),
4143 }
4144 janitor(&opts.repo, opts, home, &request.worktrees_root).await;
4145 resweep_superseded_attempts(&queue, home);
4146 triage_held(&queue, home, opts).await;
4147 } else {
4148 retention_service_receipt(
4149 home,
4150 "housekeeping",
4151 "worker",
4152 "skipped",
4153 "task worker became active",
4154 None,
4155 );
4156 }
4157 }
4158 operation => bail!("unknown daemon service {operation}"),
4159 }
4160 Ok(())
4161}
4162
4163fn task_worker_spawn_error(home: &Path, request: &TaskWorker, error: anyhow::Error) -> Result<()> {
4167 let key = format!("task:{}", request.task);
4168 let payload = serde_json::to_value(request)?;
4169 if crate::worker::active(home)?
4170 .iter()
4171 .any(|job| job.key == key && job.kind == "task" && job.payload != payload)
4172 {
4173 tracing::warn!(
4174 "task {} acquired a competing worker reservation: {error:#}",
4175 crate::run::short_of(&request.task)
4176 );
4177 return Ok(());
4178 }
4179 tracing::error!("task worker startup stopped dispatch: {error:#}");
4180 notices::raise_in(
4181 home,
4182 Notice::error(
4183 "loop:worker-startup",
4184 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),
4187 ).link(Link::Task { id: request.task.clone() }),
4188 );
4189 Err(error).with_context(|| {
4190 format!(
4191 "cannot start task {} worker; dispatcher stopped; any unacknowledged reservation remains occupied",
4192 crate::run::short_of(&request.task)
4193 )
4194 })
4195}
4196
4197async fn poll(
4198 opts: &Opts,
4199 queue: &Queue,
4200 status: &Arc<Mutex<Status>>,
4201 home: &Path,
4202 worktrees_root: &Path,
4203 stop: &Stop,
4204 limits: DispatchLimits,
4205) -> Result<()> {
4206 let mut attempted = Vec::new();
4207 let mut settling_once_services = false;
4208 let interrupt_path = home.join("scheduler-interrupt.json");
4209 let mut interrupt = match std::fs::read(&interrupt_path) {
4210 Ok(body) => serde_json::from_slice(&body).context("read scheduler interrupt state")?,
4211 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Interrupt::Idle,
4212 Err(error) => return Err(error.into()),
4213 };
4214 let mut previous = std::collections::BTreeSet::<String>::new();
4215 let mut previous_skips = DispatchSkips::new();
4216 while !stop.stopped() {
4217 let jobs: Vec<_> = crate::worker::active(home)?
4218 .into_iter()
4219 .filter(|job| job.kind == "task")
4220 .collect();
4221 let requests: Vec<_> = jobs
4222 .iter()
4223 .map(|job| {
4224 serde_json::from_value::<TaskWorker>(job.payload.clone())
4225 .with_context(|| format!("read live task worker {}", job.id))
4226 })
4227 .collect::<Result<_>>()?;
4228 let live: std::collections::BTreeSet<_> = requests.iter().map(|r| r.task.clone()).collect();
4229 let owned: std::collections::BTreeSet<_> = requests
4230 .iter()
4231 .filter(|r| !r.standalone)
4232 .map(|r| r.task.clone())
4233 .collect();
4234 let current: Vec<_> = requests
4235 .iter()
4236 .zip(&jobs)
4237 .filter(|(request, _)| !request.standalone)
4238 .map(|(request, job)| Current {
4239 worker: Some(job.id.clone()),
4240 task: request.task.clone(),
4241 run: queue
4242 .get(&request.task)
4243 .ok()
4244 .and_then(|task| task.execution_runs().last().cloned())
4245 .unwrap_or_default(),
4246 })
4247 .collect();
4248 {
4249 let mut snapshot = lock(status);
4250 snapshot.polls += 1;
4251 snapshot.completed += previous.difference(&owned).count();
4252 snapshot.current = current;
4253 snapshot.idle = owned.is_empty();
4254 snapshot.dispatch_wait = None;
4255 }
4256 previous = owned.clone();
4257 stop.busy.store(owned.len(), Ordering::SeqCst);
4258
4259 let (ordinary, urgent) = available_slots(&requests, limits.max_concurrent);
4262 let sem = Arc::new(tokio::sync::Semaphore::new(ordinary));
4263 let urgent_sem = Arc::new(tokio::sync::Semaphore::new(urgent));
4264 let mut permits = Vec::new();
4265 sweep_stale_claims(queue, STALE_CLAIM);
4266 reclaim_orphaned_running(queue, opts.max_attempts, &live);
4267 reclaim_abandoned_runs(home, Timestamp::now());
4268 let questions = Questions::at(home.join("questions"));
4269
4270 crate::task_chat::sweep(
4273 queue,
4274 &crate::talk::Talks::at(home.join("talks")),
4275 &questions,
4276 home,
4277 );
4278 if let Err(error) = crate::task_inquiry::Outbox::at(home)
4279 .sweep(queue, &crate::talk::Talks::at(home.join("talks")))
4280 {
4281 tracing::warn!("task inquiry delivery remains pending: {error:#}");
4282 }
4283 repair_choice_offers(&questions);
4284 resolve_blockers(queue, &questions);
4285 apply_task_choice_actions(queue, &questions, home);
4286 triage::apply_answers(queue, &questions);
4287 reconcile_task_questions(queue, &questions);
4288 let talks = crate::talk::Talks::at(home.join("talks"));
4289 crate::chat_notify::sweep(queue, &talks, home);
4290 crate::notice_delivery::sweep(queue, &talks, home, &opts.repo);
4291 crate::chat_watch::sweep(home, &talks);
4292 if let Err(error) = crate::chat_control::reconcile_decisions(queue, home) {
4293 tracing::warn!("decision receipt reconciliation remains pending: {error:#}");
4294 }
4295 let mut turns = tokio::task::JoinSet::new();
4296 crate::chat_notify::start_turns(&talks, stop.parking(), &mut turns);
4297 while turns.join_next().await.is_some() {}
4299
4300 crate::consult::start_services(
4301 home,
4302 &opts.repo,
4303 limits.recovery_cfg.as_ref(),
4304 opts.config.as_deref(),
4305 )
4306 .await?;
4307 for operation in [
4308 "conductor",
4309 "maintenance",
4310 "housekeeping",
4311 "disk-pressure",
4312 "cache",
4313 "fetch",
4314 "chat-goals",
4315 ] {
4316 if settling_once_services {
4320 break;
4321 }
4322 if operation == "chat-goals" && stop.parking() {
4323 continue;
4324 }
4325 start_service(
4326 home,
4327 opts,
4328 queue,
4329 worktrees_root,
4330 operation,
4331 limits.recovery_cfg.as_ref(),
4332 !live.is_empty(),
4333 )
4334 .await?;
4335 }
4336 let latest = crate::worker::active(home)?;
4337 if latest.iter().any(|job| job.key == "service:daemon-cache")
4338 || latest
4339 .iter()
4340 .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4341 {
4342 stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4343 continue;
4344 }
4345 let candidates: Vec<Task> = runnable(queue)
4346 .into_iter()
4347 .filter(|task| !live.contains(&task.id))
4348 .filter(|task| !opts.once || !attempted.contains(&task.id))
4349 .collect();
4350 let in_flight: Vec<_> = owned.iter().cloned().collect();
4351 let prior_interrupt = std::mem::discriminant(&interrupt);
4352 interrupt = advance_interrupt_tick(
4353 limits.pause_for_interrupts,
4354 interrupt,
4355 &in_flight,
4356 &candidates,
4357 );
4358 if prior_interrupt != std::mem::discriminant(&interrupt) {
4361 let temporary = interrupt_path.with_extension("json.tmp");
4362 std::fs::write(&temporary, serde_json::to_vec(&interrupt)?)?;
4363 std::fs::rename(temporary, &interrupt_path)?;
4364 }
4365 if let Interrupt::Parking {
4366 parked,
4367 interrupt_task,
4368 } = &interrupt
4369 {
4370 for job in jobs.iter().filter(|job| {
4371 parked
4372 .iter()
4373 .any(|id| job.key.strip_prefix("task:") == Some(id.as_str()))
4374 }) {
4375 if crate::worker::control(home, &job.key)?.is_none() {
4376 request_task_park(
4377 home,
4378 job,
4379 crate::run::ParkCause::Interrupt {
4380 reason: format!(
4381 "task {} asked to run first",
4382 crate::run::short_of(interrupt_task)
4383 ),
4384 },
4385 )?;
4386 }
4387 }
4388 }
4389 let candidate_ids: Vec<_> = candidates.iter().map(|task| task.id.clone()).collect();
4390 let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
4391 let mut skips = interrupt_skips(&candidate_ids, &candidates);
4392 let cooling = read_cooldown(home)?.is_some_and(|until| Timestamp::now() < until);
4393 let mut started = false;
4394 let mut resync = false;
4395 for candidate in candidates {
4396 if stop.stopped() {
4397 break;
4398 }
4399 let DispatchClaim {
4400 task,
4401 claim,
4402 permit,
4403 } = match claim_dispatch(queue, &candidate, cooling, &sem, &urgent_sem) {
4404 Ok(claim) => claim,
4405 Err(reason) => {
4406 skips.insert((candidate.id, reason));
4407 continue;
4408 }
4409 };
4410 if crate::worker::active(home)?
4411 .iter()
4412 .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4413 {
4414 drop(claim);
4415 resync = true;
4416 break;
4417 }
4418 let lane = permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent);
4419 let request = TaskWorker {
4420 opts: opts.absolute()?,
4421 queue: std::path::absolute(queue.root())?,
4422 task: task.id.clone(),
4423 lane,
4424 standalone: false,
4425 };
4426 if let Err(error) = crate::worker::spawn(
4429 home,
4430 "task",
4431 &format!("task:{}", task.id),
4432 serde_json::to_value(&request)?,
4433 )
4434 .await
4435 {
4436 task_worker_spawn_error(home, &request, error)?;
4437 drop(claim);
4438 resync = true;
4439 break;
4440 }
4441 drop(claim);
4442 permits.extend(permit);
4443 attempted.push(task.id);
4444 started = true;
4445 }
4446 if !resync && !stop.stopped() {
4447 if !started {
4448 lock(status).dispatch_wait = aggregate_dispatch_wait(candidate_ids.len(), &skips);
4449 }
4450 if changed_dispatch_skips(&mut previous_skips, skips) {
4451 if previous_skips.is_empty() {
4452 tracing::info!("dispatch skips cleared");
4453 }
4454 for (task, reason) in &previous_skips {
4455 tracing::info!(
4456 task,
4457 reason = reason.key(),
4458 "task {} skipped: {}",
4459 crate::run::short_of(task),
4460 reason.describe()
4461 );
4462 }
4463 }
4464 }
4465 if started || resync {
4466 continue;
4467 }
4468 if owned.is_empty() && opts.once {
4469 settling_once_services = true;
4470 if crate::worker::active(home)?.iter().any(|job| {
4474 job.kind == "daemon-service"
4475 && matches!(
4476 job.key.as_str(),
4477 "service:daemon-housekeeping"
4478 | "service:daemon-conductor"
4479 | "service:daemon-maintenance"
4480 )
4481 }) {
4482 stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4483 continue;
4484 }
4485 break;
4486 }
4487 stop.idle(if live.is_empty() {
4488 opts.poll
4489 } else {
4490 RECHECK_WHILE_BUSY.min(opts.poll)
4491 })
4492 .await;
4493 }
4494 stop.busy.store(0, Ordering::SeqCst);
4497 lock(status).dispatch_wait = None;
4498 Ok(())
4499}
4500
4501async fn resume_owner_lock(home: &Path, id: &str) -> Result<crate::pr_head::OwnerLock> {
4505 let busy = |error: &anyhow::Error| {
4506 error.downcast_ref::<std::io::Error>().is_some_and(|error| {
4507 error.kind() == std::io::ErrorKind::WouldBlock
4508 || cfg!(windows) && error.raw_os_error() == Some(33)
4509 })
4510 };
4511 match crate::pr_head::owner_lock(home, id) {
4512 Ok(lock) => return Ok(lock),
4513 Err(error) if busy(&error) => {}
4514 Err(error) => return Err(error),
4515 }
4516 let wait = RunState::load_under(id, home)?
4517 .config
4518 .graph
4519 .timeout_resource_wait;
4520 crate::pr_head::owner_lock_wait(home, id, Duration::from_secs(wait)).await
4521}
4522
4523async fn public_resume_owner(
4527 home: &Path,
4528 runs: &[String],
4529 repo: &Path,
4530) -> Result<Option<RunState>> {
4531 let mut owner = None;
4532 for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
4533 let _lock = resume_owner_lock(home, id).await?;
4534 let state = RunState::load_under(id, home)?;
4535 if state.released()
4536 || state.retired_to.is_some()
4537 || state.pr_taken_over_by.is_some()
4538 || !crate::handover::landing_checkpoint(&state)
4539 {
4540 continue;
4541 }
4542 anyhow::ensure!(
4543 crate::git::toplevel(&state.repo).await?.canonicalize()?
4544 == crate::git::toplevel(repo).await?.canonicalize()?,
4545 "public owner repository differs; inspect run lineage"
4546 );
4547 anyhow::ensure!(
4548 owner.is_none(),
4549 "multiple retained public owners; inspect run lineage"
4550 );
4551 if let Some(reason) = crate::handover::resume_refusal_under(&state, Some(home)) {
4552 anyhow::bail!(reason.diagnostic(&state));
4553 }
4554 let claimed = is_working_on_other(home, id, Timestamp::now())?;
4555 anyhow::ensure!(
4556 state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
4557 "public owner's driver is live or unknown; wait before retrying"
4558 );
4559 owner = Some(state);
4560 }
4561 Ok(owner)
4562}
4563
4564async fn attempt(
4570 opts: &Opts,
4571 queue: &Queue,
4572 status: &Arc<Mutex<Status>>,
4573 stop: &Stop,
4574 interrupt_pause: crate::graph::Pause,
4575 task: &mut Task,
4576) -> Vec<QuotaLoss> {
4577 if let Some(request) = task.sync_only.clone() {
4578 Box::pin(attempt_sync_only(
4579 queue,
4580 status,
4581 stop,
4582 interrupt_pause,
4583 task,
4584 request,
4585 ))
4586 .await;
4587 return Vec::new();
4588 }
4589 let repo = repo_for(task, &opts.repo);
4590 tracing::info!(
4591 "task {} — {} (repo {})",
4592 task.short(),
4593 task.title,
4594 repo.display()
4595 );
4596
4597 let public_owner = match public_resume_owner(&crate::run::home(), &task.runs, &repo).await {
4598 Ok(owner) => owner,
4599 Err(e) => {
4600 task.hold_machine(Some(format!(
4601 "Cannot verify existing public owner: {e:#}; no attempt started."
4602 )));
4603 record(queue, task);
4604 return Vec::new();
4605 }
4606 };
4607 let resume_runs = public_owner
4608 .as_ref()
4609 .map(|s| vec![s.id.clone()])
4610 .unwrap_or_else(|| task.execution_runs().to_vec());
4611
4612 if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
4616 && previous
4617 .merge_decision
4618 .as_ref()
4619 .is_some_and(|decision| !decision.closed)
4620 && previous.status != RunStatus::Landing
4621 && !crate::merge_decision::resumable_hold(&previous)
4622 {
4623 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)));
4624 record(queue, task);
4625 return Vec::new();
4626 }
4627 let stop_owner = resume_runs
4628 .last()
4629 .and_then(|id| RunState::load(id).ok())
4630 .filter(|state| {
4631 crate::merge_decision::resumable_hold(state)
4632 || state.status == RunStatus::Landing
4633 && state.land_approval.as_ref().is_some_and(|binding| {
4634 Questions::open()
4635 .get_for_effects(&binding.question)
4636 .is_ok_and(|q| {
4637 q.run == state.id
4638 && q.resolution()
4639 .as_deref()
4640 .is_some_and(crate::merge_decision::stops)
4641 })
4642 })
4643 });
4644 if let Some(owner) = stop_owner {
4645 let mut runner = match Runner::resume(&owner.id) {
4646 Ok(runner) => runner,
4647 Err(e) => {
4648 task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
4649 record(queue, task);
4650 return Vec::new();
4651 }
4652 };
4653 runner.on_pause(stop.pause());
4654 runner.watch_interrupt(interrupt_pause);
4655 let quota_before = runner.state.quota.clone();
4656 let before_start = task.clone();
4657 task.start(owner.id.clone());
4658 if let Err(error) = queue.put(task) {
4659 *task = before_start;
4660 let error = runner.fail_startup("task-start", error);
4661 if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
4662 task.record_startup_failure(failure.clone());
4663 }
4664 task.hold_manual(Some(format!(
4665 "Could not persist task start; no agents dispatched: {error:#}"
4666 )));
4667 record(queue, task);
4668 return Vec::new();
4669 }
4670 lock(status).current.push(Current {
4671 worker: None,
4672 task: task.id.clone(),
4673 run: owner.id,
4674 });
4675 runner.state.carry_dispatched_resumes(task);
4676 runner.state.next_pass_task_entry = true;
4677 let result = runner.execute().await;
4678 return finish_attempt(
4679 opts.max_attempts,
4680 queue,
4681 task,
4682 &runner.state,
4683 "a_before,
4684 result,
4685 );
4686 }
4687
4688 if let Some(owner) = &public_owner
4689 && (task.fresh_start || !may_resume_run(owner, task))
4690 {
4691 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)));
4692 record(queue, task);
4693 return Vec::new();
4694 }
4695
4696 if let Some(state) = task
4697 .execution_runs()
4698 .last()
4699 .and_then(|id| RunState::load(id).ok())
4700 && let Some(reason) = crate::repair_budget::conflict_failure(task, &state)
4701 {
4702 task.hold_machine(Some(reason));
4703 record(queue, task);
4704 return Vec::new();
4705 }
4706
4707 if let Some(held) = crate::base_sync_recovery::held_run(queue, task)
4708 && !task.fresh_start
4709 && task.pr_recovery.is_none()
4710 {
4711 let authorized = if crate::repair_budget::conflict_pending(task, &held) {
4714 true
4715 } else if task.resumption.is_some() && compatible_run_instruction(&held, task) {
4716 let home = queue.root().parent().expect("queue has a home");
4717 match Runner::authorize_base_recovery_from_resumption(home, &held.id, &task.id).await {
4718 Ok(()) => true,
4719 Err(error) => {
4720 tracing::debug!(run = %held.id, %error, "base recovery resumption refused");
4721 false
4722 }
4723 }
4724 } else {
4725 false
4726 };
4727 if !authorized {
4728 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())));
4729 task.base_sync_notice(&held);
4731 task.resume_override = None;
4732 record(queue, task);
4733 return Vec::new();
4734 }
4735 }
4736 let unfinished = (!task.fresh_start)
4737 .then(|| unfinished_run(&resume_runs, task.short()))
4738 .flatten()
4739 .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
4740 let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
4741 if task.repair_grants.last().is_some_and(|receipt| {
4742 task.execution_runs().last() == Some(&receipt.request.run)
4743 && task.operator_decided_at == receipt.decision
4744 && previous
4745 .as_ref()
4746 .is_none_or(|run| run.id != receipt.request.run)
4747 }) {
4748 task.hold_unrequested_retry(Some(
4749 "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(),
4750 ));
4751 record(queue, task);
4752 return Vec::new();
4753 }
4754 if let Some(id) = &task.disk_resume_run
4755 && unfinished.as_ref() != Some(id)
4756 {
4757 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()));
4758 record(queue, task);
4759 return Vec::new();
4760 }
4761
4762 if !task.fresh_start
4763 && task.pr_recovery.is_none()
4764 && task.review_branch.is_none()
4765 && task.resume_override.is_none()
4766 && previous
4767 .as_ref()
4768 .is_some_and(|run| run.retired_to.is_some())
4769 && unfinished.is_none()
4770 {
4771 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()));
4772 record(queue, task);
4773 return Vec::new();
4774 }
4775
4776 let saved_recovery = previous.as_ref().filter(|run| {
4777 task.replacement.is_none()
4778 && task.pr_recovery.as_ref().is_some_and(|selected| {
4779 selected
4780 .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
4781 .is_ok()
4782 && selected_starter(selected, Some(run), unfinished.as_deref())
4783 == Starter::Resume(run.id.clone())
4784 })
4785 });
4786
4787 let explicit = match &task.overrides {
4791 Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
4792 Some(_) => opts.config.as_deref(),
4793 None => opts.config.as_deref(),
4794 };
4795 let (mut config, layers) = if let Some(run) = saved_recovery {
4796 let mut saved = run.clone();
4799 if let Err(e) = saved.configure_recovery_resume() {
4800 task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
4801 record(queue, task);
4802 return Vec::new();
4803 }
4804 (saved.config, Vec::new())
4805 } else {
4806 let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
4807 Ok(loaded) => loaded,
4808 Err(e) => {
4809 let reason = format!("[config] {e:#}");
4810 record_config_failure(task, &e);
4811 task.last_error = Some(reason.clone());
4812 task.hold_machine(Some(reason));
4813 record(queue, task);
4814 return Vec::new();
4815 }
4816 };
4817 if let Err(e) = apply_options(&mut config, opts, task) {
4818 task.hold_manual(Some(format!(
4819 "[config] {e:#}; correct the merge override before releasing the task"
4820 )));
4821 record(queue, task);
4822 return Vec::new();
4823 }
4824 if let Some(selected) = &task.pr_recovery
4825 && let Err(e) = selected.configure(&mut config)
4826 {
4827 task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
4828 record(queue, task);
4829 return Vec::new();
4830 }
4831 (config, layers)
4832 };
4833 let config_evidence = crate::pr_recovery::ConfigEvidence {
4834 layers,
4835 overrides: task.overrides.clone(),
4836 daemon_merge: task
4837 .overrides
4838 .as_ref()
4839 .is_none_or(|o| o.inherit_daemon_options)
4840 .then(|| opts.merge.clone())
4841 .flatten(),
4842 };
4843 apply_task_implementers(&mut config, task);
4844 if let Some(replacement) = &task.replacement {
4845 let safe = RunState::load(&replacement.run).is_ok_and(|old| {
4846 old.liveness(false) == Liveness::Dead
4847 && old.merge_decision.as_ref().is_some_and(|d| {
4848 d.closed
4849 && d.question == replacement.question
4850 && d.replacement_run.as_ref().is_none_or(|run| {
4851 task.execution_runs().last() == Some(run)
4852 && RunState::load(run).is_ok_and(|current| {
4853 current.replaces.as_ref().is_some_and(|pin| {
4854 pin.question == replacement.question
4855 && pin.agent == replacement.agent
4856 })
4857 })
4858 })
4859 })
4860 });
4861 if !safe {
4862 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()));
4863 record(queue, task);
4864 return Vec::new();
4865 }
4866 match config.agent(&replacement.agent) {
4867 Ok(agent) if crate::agent::installed(agent) => {}
4868 _ => {
4869 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)));
4870 record(queue, task);
4871 return Vec::new();
4872 }
4873 }
4874 config.graph.implementers = 1;
4875 config.graph.land_approval = true;
4876 config.merge.mode = MergeMode::Pr;
4877 config.graph.selected_implementer = Some(replacement.agent.clone());
4878 }
4879 let p = phrases(&config.graph.language);
4880 let start_failed = p.could_not_start;
4881 if let Ok(base) =
4886 crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
4887 .await
4888 && let Ok(head) =
4889 crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
4890 {
4891 let mut inputs = crate::queue::recovery_inputs(&task.sources);
4892 if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
4893 let source = crate::git::rev_parse(&repo, branch)
4894 .await
4895 .unwrap_or_default();
4896 inputs.push_str(&format!(";review:{branch}:{source}"));
4897 }
4898 if let Some(reason) = task
4899 .recovery_exhausted(
4900 &head,
4901 &inputs,
4902 task.attempt_limit
4903 .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
4904 )
4905 .filter(|_| {
4906 !task.repair_grants.last().is_some_and(|receipt| {
4907 RunState::load(&receipt.request.run)
4908 .is_ok_and(|run| crate::repair_budget::pending(task, &run))
4909 })
4910 })
4911 {
4912 task.hold_recovery_budget(
4913 reason,
4914 crate::queue::RecoveryAdmission { base: head, inputs },
4915 );
4916 record(queue, task);
4917 return Vec::new();
4918 }
4919 task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
4920 }
4921
4922 let consume_review = !previous
4943 .as_ref()
4944 .is_some_and(|state| crate::repair_budget::pending(task, state));
4945 let review_branch = consume_review
4946 .then(|| review_branch_for(task, previous.as_ref()))
4947 .flatten();
4948 let branch_exists = match review_branch {
4949 Some(branch) => crate::git::branch_exists(&repo, branch)
4950 .await
4951 .unwrap_or(false),
4952 None => false,
4953 };
4954 let proposed = review_retry_starter(
4958 task,
4959 previous.as_ref(),
4960 review_branch,
4961 branch_exists,
4962 unfinished.as_deref(),
4963 );
4964 let retry_selected = task.replacement.is_some()
4965 && task.resumption.is_some()
4966 && !task.fresh_start
4967 && previous.as_ref().is_some_and(|run| {
4968 run.replaces.is_some()
4969 && ((run.status == RunStatus::Failed && run.viable().is_empty())
4970 || (run.status == RunStatus::Blocked && run.tally.is_none()))
4971 });
4972 let stop_pin = task
4973 .resume_override
4974 .as_ref()
4975 .filter(|pin| {
4976 Questions::open()
4977 .get_for_effects(&pin.question_id)
4978 .is_ok_and(|q| {
4979 q.node == land::APPROVAL_NODE
4980 && q.resolution()
4981 .as_deref()
4982 .is_some_and(crate::merge_decision::stops)
4983 })
4984 })
4985 .and_then(|pin| pin.pinned_run.clone());
4986 let granted_run = task.repair_grants.last().and_then(|receipt| {
4987 let state = RunState::load(&receipt.request.run).ok()?;
4988 crate::repair_budget::pending(task, &state).then(|| receipt.request.run.clone())
4989 });
4990 let starter = if let Some(run) = granted_run {
4991 Starter::Resume(run)
4992 } else if let Some(owner) = &public_owner {
4993 Starter::Resume(owner.id.clone())
4994 } else if let Some(run) = stop_pin {
4995 Starter::Resume(run)
4998 } else if retry_selected {
4999 Starter::Resume(previous.as_ref().unwrap().id.clone())
5000 } else if let Some(selected) = &task.pr_recovery {
5001 if selected
5002 .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
5003 .is_ok()
5004 {
5005 selected_starter(selected, previous.as_ref(), unfinished.as_deref())
5006 } else {
5007 Starter::Review(selected.branch.clone())
5008 }
5009 } else {
5010 starter_with_implementers(task, previous.as_ref(), proposed)
5011 };
5012 let disk_reason = match &starter {
5015 Starter::Resume(id) => previous.as_ref().filter(|run| &run.id == id).map_or_else(
5016 || {
5017 RunState::load(id)
5018 .ok()
5019 .and_then(|run| disk_gate(&run.repo, &run.config))
5020 },
5021 |run| disk_gate(&run.repo, &run.config),
5022 ),
5023 _ => disk_gate(&repo, &config),
5024 };
5025 if let Some(reason) = disk_reason {
5026 task.notice_cause("disk-space", None, None);
5027 task.last_error = Some(reason.clone());
5028 let disk_checked_at = task.disk_checked_at;
5029 task.hold_machine(Some(reason.clone()));
5030 if matches!(starter, Starter::Resume(_)) {
5031 task.mark_disk_capacity();
5032 } else {
5033 task.mark_startup_disk_capacity();
5034 }
5035 task.disk_checked_at = disk_checked_at;
5036 record(queue, task);
5037 tracing::warn!("holding {} for want of disk space: {reason}", task.short());
5038 notices::raise(
5039 Notice::warn(
5040 &format!("disk:{}", repo.display()),
5041 format!("Task {} is waiting for disk space. It will resume automatically when disk and output admission checks succeed.", task.id),
5042 )
5043 .link(Link::Task {
5044 id: task.id.clone(),
5045 }),
5046 );
5047 return Vec::new();
5048 }
5049 let review_branch = if consume_review {
5050 let valid = review_branch.is_some();
5051 task.review_instruction = None;
5052 task.review_branch.take().filter(|_| valid)
5053 } else {
5054 None
5055 };
5056 if let Some(pin) = &task.resume_override
5059 && let Some(run) = &pin.pinned_run
5060 && starter != Starter::Resume(run.clone())
5061 {
5062 let run = run.clone();
5063 task.notice_cause("resume-owner", Some(&run), None);
5064 task.hold_machine(Some(format!(
5065 "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
5066 task.id
5067 )));
5068 record(queue, task);
5069 return Vec::new();
5070 }
5071 if let Some(run) = &task.disk_resume_run
5075 && starter != Starter::Resume(run.clone())
5076 {
5077 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()));
5078 record(queue, task);
5079 return Vec::new();
5080 }
5081 if task.replacement.is_some()
5082 && previous.as_ref().is_some_and(|run| run.replaces.is_some())
5083 && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
5084 {
5085 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()));
5086 record(queue, task);
5087 return Vec::new();
5088 }
5089 if let Some(reason) = retained_attempt_hold(
5090 task,
5091 &starter,
5092 config.disk.retained_attempt_limit,
5093 RunState::load,
5094 ) {
5095 if let Starter::Review(branch) = &starter {
5098 task.review_branch = Some(branch.clone());
5099 }
5100 task.hold_unrequested_retry(Some(reason));
5101 record(queue, task);
5102 return Vec::new();
5103 }
5104 let attachments = match task_attachments(queue, task) {
5109 Ok(a) => a,
5110 Err(e) => {
5111 task.attempts += 1;
5112 task.fail_startup_target(
5113 "startup-attachments",
5114 e.name.clone(),
5115 format!("{start_failed}{e:#}"),
5116 opts.max_attempts,
5117 );
5118 record(queue, task);
5119 return Vec::new();
5120 }
5121 };
5122 let startup_pause = stop.pause();
5123 let startup_interrupt = interrupt_pause.clone();
5124 let wait = crate::repo_lock::WaitPolicy::new(
5125 Duration::from_secs(config.graph.timeout_resource_wait),
5126 move || startup_pause.parked() || startup_interrupt.parked(),
5127 );
5128 let started = wait.scope(Box::pin(async { match &starter {
5131 Starter::Review(_) if task.pr_recovery.is_some() => {
5132 let selected = task.pr_recovery.clone().expect("selected recovery");
5133 match selected.check_task_assignment(&task.id, &task.instruction, task.reassignments.len()) {
5134 Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
5135 .await
5136 .map(|mut r| {
5137 r.state.attachments = attachments.clone();
5138 r
5139 }),
5140 Err(e) => Err(e),
5141 }
5142 }
5143 Starter::Review(branch) => {
5144 tracing::info!(
5145 "task {} reopens `{branch}` as a review-only pass",
5146 task.short()
5147 );
5148 let takeover = crate::handover::Takeover {
5151 earlier: task.earlier_attempts().to_vec(),
5152 home: crate::run::home(),
5153 choice: take_divergence_answer(branch, &config.merge.remote, task),
5154 task_instruction: Some(instruction_for(task)),
5155 };
5156 Runner::review_taking_over(
5157 &repo,
5158 branch,
5159 config,
5160 Some(takeover),
5161 crate::run::Origin::queue(&task.id),
5162 )
5163 .await
5164 }
5165 Starter::Resume(id) => {
5166 tracing::info!("resuming run {id} rather than competing again");
5167 Runner::resume(id).and_then(|mut r| {
5168 if retry_selected {
5169 for candidate in &mut r.state.candidates {
5172 candidate.failed = None;
5173 candidate.empty = false;
5174 candidate.commits = 0;
5175 }
5176 r.state.status = RunStatus::Implementing;
5177 r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
5178 }
5179 if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
5180 r.state.sources = task.sources.clone();
5181 }
5182 if r.state.prep_failure.is_some() {
5183 let approval = task
5184 .resumption
5185 .as_ref()
5186 .context("preparation retry requires an explicit task release")?;
5187 r.retry_preparation(approval.at)?;
5188 }
5189 if let Some(instruction) =
5190 prepare_instruction(&starter, Some(&r.state.instruction), task)
5191 {
5192 r.state.instruction = instruction;
5193 }
5194 r.state.attachments = attachments.clone();
5195 if task.replacement.is_some() {
5196 r.state.config.merge.mode = MergeMode::Pr;
5197 r.state.config.graph.land_approval = true;
5198 }
5199 if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
5203 .overrides
5204 .as_ref()
5205 .and_then(|o| o.merge.as_deref())
5206 .and_then(|m| merge_mode(m).ok())
5207 {
5208 r.state.config.merge.mode = mode;
5209 }
5210 Ok(r)
5211 })
5212 }
5213 Starter::Start => {
5214 if let Some(branch) = &review_branch {
5215 tracing::warn!(
5216 "conductor chose review for task {} but branch `{branch}` no longer \
5217 exists; requeuing as a fresh competition instead",
5218 task.short()
5219 );
5220 }
5221 let instruction = prepare_instruction(&starter, None, task)
5222 .unwrap_or_else(|| task.instruction.clone());
5223 Runner::start_naming(
5224 &repo,
5225 instruction,
5226 &task.title,
5227 config,
5228 crate::run::Origin::queue(&task.id),
5229 )
5230 .await
5231 .map(|mut r| {
5232 r.state.attachments = attachments.clone();
5233 r.state.sources = task.sources.clone();
5234 r
5235 })
5236 }
5237 }})).await;
5238 if let Err(error) = &started
5239 && let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>()
5240 {
5241 task.record_startup_failure(failure.clone());
5242 }
5243 let mut runner = match started {
5244 Ok(r) => r,
5245 Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
5246 let detail = format!("{e:#}");
5247 task.last_error = Some(detail.clone());
5248 if e.is::<crate::build_target::AdmissionDiskWait>()
5249 && let Starter::Review(branch) = &starter
5250 && review_branch.is_some()
5251 {
5252 task.review_branch = Some(branch.clone());
5253 task.review_instruction = Some(task.instruction.clone());
5254 }
5255 if stop.parking() || interrupt_pause.parked() {
5256 let attempts = task.attempts;
5257 task.park(e.to_string());
5258 task.attempts = attempts;
5260 } else if e.is::<crate::build_target::AdmissionDiskWait>() {
5261 let disk_checked_at = task.disk_checked_at;
5262 task.hold_machine(Some(detail));
5263 task.mark_startup_disk_capacity();
5264 task.disk_checked_at = disk_checked_at;
5265 } else {
5266 task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
5267 }
5268 record(queue, task);
5269 return Vec::new();
5270 }
5271 Err(e) if task.pr_recovery.is_some() => {
5275 task.startup_notice_cause("startup-public-head");
5276 task.attempts += 1;
5277 task.last_error = Some(format!("{start_failed}{e:#}"));
5278 task.hold_unrequested_retry(Some(format!(
5279 "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."
5280 )));
5281 record(queue, task);
5282 return Vec::new();
5283 }
5284 Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
5285 let detail = match e.downcast_ref::<crate::handover::Refused>() {
5286 Some(r) => (p.handover_refused)(r),
5287 None => format!("{e:#}"),
5288 };
5289 task.startup_notice_cause("startup-handover");
5290 let reason = format!("{start_failed}{detail}");
5291 task.last_error = Some(reason.clone());
5292 let branch = match &starter {
5295 Starter::Review(branch) => Some(branch.clone()),
5296 _ => None,
5297 };
5298 task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
5302 record(queue, task);
5303 tracing::warn!(
5304 "holding {} for a branch it cannot take over: {e:#}",
5305 task.short()
5306 );
5307 return Vec::new();
5308 }
5309 Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
5314 let d = e
5315 .downcast_ref::<crate::reconcile::Diverged>()
5316 .expect("checked by the guard");
5317 let mut q = ask::Question::new(
5318 task.id.clone(),
5319 crate::reconcile::NODE.to_owned(),
5320 crate::reconcile::SEAT.to_owned(),
5321 d.summary(),
5322 d.detail(),
5323 d.choices(),
5324 );
5325 match Questions::open().put(&mut q) {
5326 Ok(()) => {
5327 task.last_error = Some(format!("{e:#}"));
5328 task.review_branch = Some(d.branch.clone());
5331 task.review_instruction = Some(task.instruction.clone());
5332 task.block(vec![q.id.clone()], Some(d.summary()));
5333 }
5334 Err(put) => {
5335 tracing::warn!("could not file the divergence question: {put:#}");
5336 task.attempts += 1;
5337 task.fail_startup(
5338 "startup-question-store",
5339 format!("{start_failed}{e:#}"),
5340 opts.max_attempts,
5341 );
5342 }
5343 }
5344 record(queue, task);
5345 return Vec::new();
5346 }
5347 Err(e) => {
5348 if e.downcast_ref::<crate::reconcile::Stale>().is_some()
5354 && let Starter::Review(branch) = &starter
5355 {
5356 task.review_branch = Some(branch.clone());
5357 task.review_instruction = Some(task.instruction.clone());
5358 task.last_error = Some(format!("{start_failed}{e:#}"));
5359 task.status = crate::queue::TaskStatus::Failed;
5360 record(queue, task);
5361 return Vec::new();
5362 }
5363 task.attempts += 1;
5364 task.last_error = Some(format!("{start_failed}{e:#}"));
5365 task.startup_notice_cause("startup-source");
5366 task.hold_unrequested_retry(Some(format!(
5367 "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
5368 )));
5369 record(queue, task);
5370 return Vec::new();
5371 }
5372 };
5373 if !matches!(starter, Starter::Resume(_))
5374 && let Some((mode, source)) = task.build_cache_override(&runner.state.config)
5375 {
5376 runner
5377 .state
5378 .event("build-cache", format!("{mode} selected by {source}"));
5379 }
5380 if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
5381 runner.state.recovery_config = Some(config_evidence);
5382 }
5383 if let Some(replacement) = &task.replacement {
5384 if matches!(starter, Starter::Start) {
5385 runner.state.instruction.push_str(&format!(
5386 "\n\n# Replacement review context\n{}",
5387 replacement.context
5388 ));
5389 }
5390 runner.state.replaces = Some(replacement.clone());
5391 runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
5392 if let Ok(mut old) = RunState::load(&replacement.run)
5393 && let Some(d) = &mut old.merge_decision
5394 {
5395 d.replacement_run = Some(runner.state.id.clone());
5396 old.event(
5397 "replacement",
5398 format!(
5399 "replacement run {} owns the next attempt; old PR remains closed",
5400 runner.state.id
5401 ),
5402 );
5403 if let Err(e) = old.save() {
5404 let error = runner.fail_startup("replacement-history", e);
5405 if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5406 task.record_startup_failure(failure.clone());
5407 }
5408 task.hold_manual(Some(format!(
5409 "Could not link replacement history: {error:#}; no agents dispatched"
5410 )));
5411 record(queue, task);
5412 return Vec::new();
5413 }
5414 }
5415 }
5416 runner.state.task_instruction = Some(task.instruction.clone());
5417 runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
5420 if runner.state.origin_chat.is_none() {
5421 runner.state.origin_chat = task.chat_talk().map(str::to_owned);
5422 }
5423 runner.on_pause(stop.pause());
5425 runner.watch_interrupt(interrupt_pause);
5429
5430 let run = runner.state.id.clone();
5433 let before_start = task.clone();
5434 task.start(run.clone());
5435 if let Err(error) = queue.put(task) {
5436 *task = before_start;
5437 let error = runner.fail_startup("task-start", error);
5438 if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5439 task.record_startup_failure(failure.clone());
5440 }
5441 task.hold_manual(Some(format!(
5442 "Could not persist task start; no agents dispatched: {error:#}"
5443 )));
5444 record(queue, task);
5445 return Vec::new();
5446 }
5447 if task.status != TaskStatus::Running {
5448 return Vec::new();
5450 }
5451 lock(status).current.push(Current {
5452 worker: None,
5453 task: task.id.clone(),
5454 run,
5455 });
5456
5457 let quota_before = runner.state.quota.clone();
5460 runner.state.carry_dispatched_resumes(task);
5461 runner.state.next_pass_task_entry = true;
5462 let result = runner.execute().await;
5463 finish_attempt(
5464 opts.max_attempts,
5465 queue,
5466 task,
5467 &runner.state,
5468 "a_before,
5469 result,
5470 )
5471}
5472
5473async fn attempt_sync_only(
5474 queue: &Queue,
5475 status: &Arc<Mutex<Status>>,
5476 stop: &Stop,
5477 interrupt: crate::graph::Pause,
5478 task: &mut Task,
5479 request: crate::base_sync_only::Request,
5480) {
5481 let result = async {
5482 anyhow::ensure!(
5483 task.status == TaskStatus::Queued
5484 && task.execution_runs().last() == Some(&request.run)
5485 && task.resume_override.as_ref().is_some_and(
5486 |pin| pin.at == request.at && pin.pinned_run.as_ref() == Some(&request.run)
5487 ),
5488 "sync-base-only request no longer owns the exact queued run"
5489 );
5490 let mut runner = Runner::resume(&request.run)?;
5491 anyhow::ensure!(
5492 public_resume_owner(&crate::run::home(), &task.runs, &runner.state.repo)
5493 .await?
5494 .is_none(),
5495 "the task still has a public execution owner"
5496 );
5497 anyhow::ensure!(
5498 !stop.parking() && !interrupt.parked(),
5499 "paused before base synchronization"
5500 );
5501 let original = task.clone();
5502 task.start(request.run.clone());
5503 task.attempts = original.attempts;
5504 if let Err(error) = queue.put(task) {
5505 *task = original;
5506 return Err(error);
5507 }
5508 if task.status != TaskStatus::Running || task.sync_only.as_ref() != Some(&request) {
5509 return Ok(());
5510 }
5511 lock(status).current.push(Current {
5512 worker: None,
5513 task: task.id.clone(),
5514 run: request.run.clone(),
5515 });
5516 runner.on_pause(stop.pause());
5517 runner.watch_interrupt(interrupt);
5518 runner.execute_sync_only(request.clone()).await
5519 }
5520 .await;
5521 if task.sync_only.as_ref() == Some(&request) {
5522 let saved = RunState::load(&request.run).ok();
5523 let detail = result.err().map(|error| {
5524 format!("Base synchronization only: {error:#}; verification was not allowed")
5525 });
5526 crate::base_sync_only::settle(task, &request, saved.as_ref(), detail);
5527 record(queue, task);
5528 }
5529}
5530
5531pub fn finish_attempt(
5536 max_attempts: usize,
5537 queue: &Queue,
5538 task: &mut Task,
5539 state: &RunState,
5540 quota_before: &[QuotaLoss],
5541 result: Result<()>,
5542) -> Vec<QuotaLoss> {
5543 let detail = match result {
5544 Ok(()) => describe(state),
5545 Err(e) => format!("{e:#}"),
5546 };
5547 let fresh = losses_this_attempt(quota_before, &state.quota);
5548 let verdict = Verdict {
5549 status: state.status,
5550 left_pr: state.pr.is_some(),
5553 quota_hit: !fresh.is_empty(),
5559 parked: state.parked,
5563 no_viable_candidates: state.viable().is_empty(),
5566 };
5567 if let Some(replacement) = &state.replaces
5568 && let Some(pr) = &state.pr
5569 && let Ok(mut old) = RunState::load(&replacement.run)
5570 && let Some(d) = &mut old.merge_decision
5571 {
5572 d.replacement_pr = Some(pr.url.clone());
5573 let _ = old.save();
5574 }
5575 settle_and_diagnose(task, verdict, &detail, max_attempts, state);
5576 if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
5577 task.hold_unrequested_retry(Some(format!(
5578 "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.",
5579 task.short()
5580 )));
5581 }
5582 if task.status == TaskStatus::Done {
5583 supersede_prior_runs(task, &crate::run::home());
5584 }
5585 record(queue, task);
5586 tracing::info!(
5587 "task {} is {} after run {} ({})",
5588 task.short(),
5589 task.status.as_str(),
5590 state.short(),
5591 label(state.status)
5592 );
5593 fresh
5594}
5595
5596pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
5600 if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
5603 && !awaiting_resume_with(task, RunState::load)
5604 && withheld_text_wait(task).is_none()
5608 && !(task.fresh_start && task.replacement.is_some())
5609 {
5610 let why = task.last_error.clone().map_or_else(
5611 || "the run did not finish".to_owned(),
5612 |e| format!("the run did not finish: {e}"),
5613 );
5614 task.hold_unrequested_retry(Some(format!(
5615 "{why}. It was started by hand, so it is not retried \
5616 automatically; `magi task release` retries it."
5617 )));
5618 record(queue, task);
5619 }
5620}
5621
5622#[must_use]
5626pub fn loop_would_resume(run: &str) -> bool {
5627 unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
5628}
5629
5630#[must_use]
5640pub fn foreign_loop(
5641 reading: Option<&Reading>,
5642 now: Timestamp,
5643 own_pid: u32,
5644) -> Option<Option<u32>> {
5645 let reading = reading.filter(|r| r.running(now))?;
5646 match reading.pid {
5647 Some(pid) if pid == own_pid => None,
5648 pid => Some(pid),
5649 }
5650}
5651
5652fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
5653 reading.worker_protocol != Some(1)
5654 && (foreign_loop(Some(reading), now, own_pid).is_some()
5655 || reading
5656 .pid
5657 .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
5658}
5659
5660pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
5671 run_claimed_until(opts, queue, task, &Stop::new()).await;
5672}
5673
5674async fn run_claimed_until(
5675 opts: &Opts,
5676 queue: &Queue,
5677 task: &mut Task,
5678 stop: &Stop,
5679) -> Vec<QuotaLoss> {
5680 let status = Arc::new(Mutex::new(Status::new()));
5681 let mut quota = Box::pin(attempt(
5684 opts,
5685 queue,
5686 &status,
5687 stop,
5688 crate::graph::Pause::new(),
5689 task,
5690 ))
5691 .await;
5692 let mut resumes = 0;
5701 while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
5702 let Some(timeout) = withheld_text_wait(task) else {
5703 break;
5704 };
5705 eprintln!(
5706 "waiting for the owner's answer on a withheld pull request text \
5707 (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
5708 );
5709 let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
5712 let ready = loop {
5713 match land_resume_state(task) {
5714 LandResume::StillWaiting
5715 if !stop.parking() && std::time::Instant::now() < limit =>
5716 {
5717 tokio::time::sleep(WITHHELD_POLL).await;
5718 }
5719 LandResume::Ready => break true,
5720 _ => break false,
5721 }
5722 };
5723 if !ready || stop.parking() {
5724 break;
5725 }
5726 resumes += 1;
5727 quota.extend(
5728 Box::pin(attempt(
5729 opts,
5730 queue,
5731 &status,
5732 stop,
5733 crate::graph::Pause::new(),
5734 task,
5735 ))
5736 .await,
5737 );
5738 }
5739 hold_if_runnable(queue, task);
5740 quota
5741}
5742
5743const MAX_WITHHELD_RESUMES: u32 = 3;
5746
5747const WITHHELD_POLL: Duration = Duration::from_secs(15);
5749
5750fn withheld_text_wait(task: &Task) -> Option<u64> {
5753 let id = task.execution_runs().last()?;
5754 let s = RunState::load(id).ok()?;
5755 (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
5756 .then_some(s.config.graph.answer_timeout)
5757}
5758
5759fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
5769 after
5770 .iter()
5771 .filter(|q| !before.contains(q))
5772 .cloned()
5773 .collect()
5774}
5775
5776fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
5779 let quota: Vec<_> = quota
5780 .iter()
5781 .filter(|q| q.cause == crate::agent::QuotaCause::UsageLimit)
5782 .collect();
5783 if quota.is_empty() {
5784 return None;
5785 }
5786 let with_hint = quota.iter().find(|q| q.reset.is_some());
5787 let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
5788 let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
5789 let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
5790 Some(
5791 now.checked_add(jiff::SignedDuration::from_secs(secs))
5792 .unwrap_or(Timestamp::MAX),
5793 )
5794}
5795
5796fn implementers_match(task: &Task, state: &RunState) -> bool {
5798 task.replacement.as_ref().map_or_else(
5799 || {
5800 task.implementers()
5801 .is_none_or(|n| n == state.config.graph.implementers)
5802 },
5803 |replacement| {
5804 state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
5805 && state.config.graph.implementers == 1
5806 },
5807 )
5808}
5809
5810fn starter_with_implementers(
5812 task: &Task,
5813 previous: Option<&RunState>,
5814 proposed: Starter,
5815) -> Starter {
5816 if previous.is_some_and(|s| !implementers_match(task, s)) {
5817 task.review_of
5818 .as_ref()
5819 .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
5820 } else {
5821 proposed
5822 }
5823}
5824
5825fn apply_task_implementers(config: &mut Config, task: &Task) {
5827 if let Some(n) = task.implementers() {
5828 config.graph.implementers = n;
5829 }
5830}
5831
5832#[cfg(test)]
5837fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
5838 let explicit = match &task.overrides {
5839 Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
5840 _ => opts.config.as_deref(),
5841 };
5842 let (mut config, _) = Config::discover(repo, explicit)?;
5843 apply_options(&mut config, opts, task)?;
5844 Ok(config)
5845}
5846
5847fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
5848 if task
5849 .overrides
5850 .as_ref()
5851 .is_none_or(|o| o.inherit_daemon_options)
5852 && let Some(mode) = opts.merge.as_deref()
5853 {
5854 config.merge.mode = merge_mode(mode)?;
5855 }
5856 if let Some(o) = &task.overrides {
5857 o.apply(config);
5858 }
5859 if let Some((mode, _)) = task.build_cache_override(config) {
5860 config.verify.build_cache = mode;
5861 }
5862 Ok(())
5863}
5864
5865fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
5867 let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
5868 if let Some(mode) = &opts.merge {
5869 config.merge.mode = merge_mode(mode)?;
5870 }
5871 Ok(config)
5872}
5873
5874async fn maybe_prune_cache_between_runs(
5879 repo: &Path,
5880 opts: &Opts,
5881 home: &Path,
5882 stop: &Stop,
5883 last_checked: &mut Option<Timestamp>,
5884 now: Timestamp,
5885) {
5886 if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
5887 return;
5888 }
5889 *last_checked = Some(now);
5890 let cfg = match prepare(repo, opts) {
5891 Ok(cfg) => cfg,
5892 Err(e) => {
5893 tracing::warn!("cache check: no config: {e:#}");
5894 return;
5895 }
5896 };
5897 match clean::prune_cache_if_over_limit(&cfg, home) {
5898 Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
5899 "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
5900 pruned.files,
5901 pruned.freed
5902 ),
5903 Ok(_) => {}
5904 Err(e) => {
5905 tracing::warn!("housekeep: prune cache: {e:#}");
5906 notices::raise_in(
5907 home,
5908 Notice::warn(
5909 "housekeep:cache",
5910 format!(
5911 "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
5912 e.to_string()
5913 .lines()
5914 .next()
5915 .unwrap_or("unknown cleanup error")
5916 ),
5917 ),
5918 );
5919 }
5920 }
5921}
5922
5923fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
5927 last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
5928}
5929
5930async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
5949 let cfg = match prepare(repo, opts) {
5950 Ok(cfg) => cfg,
5951 Err(e) => {
5952 tracing::warn!("housekeep: no config: {e:#}");
5953 return;
5954 }
5955 };
5956 let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
5965 let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
5966 if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
5971 let mut extra = Vec::new();
5972 if out.unreadable > 0 {
5973 extra.push(format!("{} unreadable", out.unreadable));
5974 }
5975 if out.orphaned_worktrees > 0 {
5976 extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
5977 }
5978 let detail = if extra.is_empty() {
5979 String::new()
5980 } else {
5981 format!(" ({})", extra.join(", "))
5982 };
5983 tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
5984 }
5985 if out.external_merges_recorded > 0 {
5986 tracing::info!(
5987 "housekeep: recorded {} run(s) as merged externally",
5988 out.external_merges_recorded
5989 );
5990 }
5991 if out.stale_pr_states_repaired > 0 {
5992 tracing::info!(
5993 "housekeep: rewrote {} run record(s) whose pull request had already settled",
5994 out.stale_pr_states_repaired
5995 );
5996 }
5997 if out.cache_files > 0 {
5998 tracing::info!(
5999 "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
6000 out.cache_files,
6001 out.cache_freed
6002 );
6003 }
6004 if out.questions_abandoned > 0 {
6005 tracing::info!(
6006 "housekeep: abandoned {} question(s) left open by a finished run",
6007 out.questions_abandoned
6008 );
6009 }
6010}
6011
6012async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
6021 let questions = Questions::at(home.join("questions"));
6022 let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
6023 if report.is_empty() {
6024 return;
6025 }
6026 if !report.quarantined.is_empty() {
6027 tracing::info!(
6028 "triage: held {} blocked task(s) whose blocked-on task or \
6029 question no longer exists: {}",
6030 report.quarantined.len(),
6031 report.quarantined.join(", ")
6032 );
6033 }
6034 if !report.resumed.is_empty() {
6035 tracing::info!(
6036 "triage: resumed {} held task(s) whose machine hold had resolved: {}",
6037 report.resumed.len(),
6038 report.resumed.join(", ")
6039 );
6040 }
6041 if !report.asked.is_empty() {
6042 tracing::info!(
6043 "triage: asked about {} held task(s): {}",
6044 report.asked.len(),
6045 report.asked.join(", ")
6046 );
6047 }
6048 if !report.answered.is_empty() {
6049 tracing::info!(
6050 "triage: applied {} operator answer(s): {}",
6051 report.answered.len(),
6052 report.answered.join(", ")
6053 );
6054 }
6055}
6056
6057pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
6064 disk_gate_at(repo, config, crate::run::home)
6065}
6066
6067pub(crate) fn disk_gate_at(
6068 repo: &Path,
6069 config: &Config,
6070 home: impl FnOnce() -> PathBuf,
6071) -> Option<String> {
6072 let measure = if crate::build_target::isolated(config) {
6073 crate::disk::managed_free_bytes
6074 } else {
6075 crate::disk::free_bytes
6076 };
6077 disk_gate_with(repo, config, home, measure)
6078}
6079
6080fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
6084 repo: &Path,
6085 config: &Config,
6086 home: impl FnOnce() -> PathBuf,
6087 free_bytes: F,
6088) -> Option<String> {
6089 let min = config.disk.min_free_bytes;
6090 if min == 0 {
6091 return None;
6092 }
6093 let output = match config.verify.build_cache {
6094 BuildCache::Shared => config.cache_dir(),
6095 BuildCache::Isolated => Some(home()),
6096 };
6097 let default_worktree_root;
6098 let worktree_root = match config.graph.worktree_root.as_deref() {
6099 Some(root) => root,
6100 None => {
6101 default_worktree_root = crate::run::default_worktree_root();
6102 &default_worktree_root
6103 }
6104 };
6105 for path in [Some(repo), output.as_deref(), Some(worktree_root)]
6106 .into_iter()
6107 .flatten()
6108 {
6109 let probe = if path == repo {
6110 path
6111 } else {
6112 path.ancestors().find(|p| p.exists()).unwrap_or(path)
6113 };
6114 let reason = match free_bytes(probe) {
6115 Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
6116 Err(e) => Some(crate::disk::unmeasured_in(
6117 probe,
6118 &e,
6119 &config.graph.language,
6120 )),
6121 };
6122 if reason.is_some() {
6123 return reason;
6124 }
6125 }
6126 None
6127}
6128
6129const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
6136
6137const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
6141
6142fn quota_wait(
6151 reset_at: Option<Timestamp>,
6152 now: Timestamp,
6153 fallback: Duration,
6154 cap: Duration,
6155) -> Duration {
6156 match reset_at {
6157 Some(at) if at > now => {
6158 let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
6159 Duration::from_secs(secs).min(cap)
6160 }
6161 _ => fallback,
6162 }
6163}
6164
6165fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
6179 parse_reset_hint_zoned(text, now)
6180 .or_else(|| parse_reset_hint_dated(text))
6181 .or_else(|| parse_reset_hint_relative(text, recorded))
6182}
6183
6184fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
6188 let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
6189 let mut rest = rest.trim();
6190 if rest.is_empty() {
6191 return None;
6192 }
6193 let mut total: i64 = 0;
6194 let mut matched = false;
6195 for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
6196 if let Some((digits, tail)) = rest.split_once(unit)
6197 && !digits.is_empty()
6198 && digits.bytes().all(|b| b.is_ascii_digit())
6199 {
6200 total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
6201 rest = tail;
6202 matched = true;
6203 }
6204 }
6205 if !rest.is_empty() || !matched {
6206 return None;
6207 }
6208 recorded
6209 .checked_add(jiff::SignedDuration::from_secs(total))
6210 .ok()
6211}
6212
6213fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
6217 let clock = clock.trim().to_lowercase();
6218 let (digits, pm) = clock
6219 .strip_suffix("am")
6220 .map(|d| (d, false))
6221 .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
6222 let (h, m) = digits.trim().split_once(':')?;
6223 let mut hour: i8 = h.trim().parse().ok()?;
6224 let minute: i8 = m.trim().parse().ok()?;
6225 if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
6226 return None;
6227 }
6228 if pm && hour != 12 {
6229 hour += 12;
6230 } else if !pm && hour == 12 {
6231 hour = 0;
6232 }
6233 Some((hour, minute))
6234}
6235
6236fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
6241 let open = text.find('(')?;
6242 let close = text.rfind(')')?;
6243 if close <= open {
6244 return None;
6245 }
6246 let zone = text[open + 1..close].trim();
6247 let (hour, minute) = parse_12h_clock(&text[..open])?;
6248 let tz = jiff::tz::TimeZone::get(zone).ok()?;
6249 let candidate = now
6250 .to_zoned(tz)
6251 .with()
6252 .hour(hour)
6253 .minute(minute)
6254 .second(0)
6255 .millisecond(0)
6256 .microsecond(0)
6257 .nanosecond(0)
6258 .build()
6259 .ok()?;
6260 let mut at = candidate.timestamp();
6261 if at <= now {
6262 at += jiff::SignedDuration::from_hours(24);
6263 }
6264 Some(at)
6265}
6266
6267fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
6276 let words: Vec<&str> = text.split_whitespace().collect();
6277 if words.len() < 5 {
6278 return None;
6279 }
6280 (0..=words.len() - 5)
6281 .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
6282}
6283
6284fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
6290 if trailing.is_some_and(|next| next.starts_with('(')) {
6291 return None;
6292 }
6293 let month = month_number(window[0])?;
6294 let day_token = window[1].strip_suffix(',')?.to_lowercase();
6295 let day_digits = ["st", "nd", "rd", "th"]
6296 .iter()
6297 .find_map(|suffix| day_token.strip_suffix(*suffix))?;
6298 let day: i8 = day_digits.parse().ok()?;
6299 let year_token = window[2];
6300 if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
6301 return None;
6302 }
6303 let year: i16 = year_token.parse().ok()?;
6304 let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
6308 let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
6309 let date = jiff::civil::Date::new(year, month, day).ok()?;
6310 let candidate = date
6311 .at(hour, minute, 0, 0)
6312 .to_zoned(jiff::tz::TimeZone::UTC)
6313 .ok()?;
6314 Some(candidate.timestamp())
6315}
6316
6317fn month_number(name: &str) -> Option<i8> {
6320 const NAMES: [&str; 12] = [
6321 "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
6322 ];
6323 let lower = name.to_lowercase();
6324 NAMES
6325 .iter()
6326 .position(|n| *n == lower.as_str())
6327 .map(|i| i as i8 + 1)
6328}
6329
6330#[cfg(test)]
6332fn exhausted_review_budget(state: &RunState) -> bool {
6333 !crate::handover::can_resume(state)
6336 && state.status == RunStatus::Blocked
6337 && !state.released()
6338 && state.retired_to.is_none()
6339}
6340
6341fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
6378 unfinished_run_with(runs, short, RunState::load)
6379}
6380
6381pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
6384where
6385 F: FnMut(&str) -> Result<RunState>,
6386{
6387 let mut id = runs.last()?.clone();
6388 let mut visited = std::collections::BTreeSet::new();
6389 let mut repo = None;
6390 loop {
6391 if !runs.contains(&id) || !visited.insert(id.clone()) {
6392 tracing::warn!("invalid or cyclic recovery authority for task {short}");
6393 return None;
6394 }
6395 let state = match load(&id) {
6396 Ok(state) if state.id == id => state,
6397 Ok(_) => return None,
6398 Err(e) => {
6399 tracing::warn!("could not read run {id} for task {short}: {e:#}");
6400 return None;
6401 }
6402 };
6403 if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
6404 return None;
6405 }
6406 repo = Some(state.repo.clone());
6407 if let Some(authority) = state.retired_to {
6408 id = authority;
6409 continue;
6410 }
6411 return (crate::handover::can_resume(&state)
6412 && state.liveness(false) != crate::run::Liveness::Live)
6413 .then_some(id);
6414 }
6415}
6416
6417fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
6425where
6426 F: FnOnce(&str) -> Result<RunState>,
6427{
6428 if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
6430 || task.fresh_start
6431 || task.review_branch.is_some()
6432 {
6433 return false;
6434 }
6435 let Some(id) = task.execution_runs().last() else {
6436 return false;
6437 };
6438 load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
6439}
6440
6441#[derive(Debug, Clone, PartialEq, Eq)]
6444enum Starter {
6445 Review(String),
6448 Resume(String),
6450 Start,
6452}
6453
6454fn retained_attempt_hold(
6459 task: &Task,
6460 starter: &Starter,
6461 limit: usize,
6462 mut load: impl FnMut(&str) -> Result<RunState>,
6463) -> Option<String> {
6464 if limit == 0 || matches!(starter, Starter::Resume(_)) {
6465 return None;
6466 }
6467 let mut retained = 0;
6468 for id in task
6469 .runs
6470 .iter()
6471 .chain(task.startup_failures.iter().map(|failure| &failure.run))
6472 .collect::<std::collections::BTreeSet<_>>()
6473 {
6474 let state = match load(id) {
6475 Ok(state) if state.id == *id => state,
6476 _ => {
6477 return Some(format!(
6478 "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
6479 ));
6480 }
6481 };
6482 if state.retired_to.is_some() || state.released() {
6483 continue;
6484 }
6485 retained += 1;
6488 }
6489 (retained >= limit).then(|| format!(
6490 "[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."
6491 ))
6492}
6493
6494fn selected_starter(
6496 selected: &crate::pr_recovery::Selection,
6497 previous: Option<&RunState>,
6498 unfinished: Option<&str>,
6499) -> Starter {
6500 if let Some(id) = unfinished
6501 && previous.is_some_and(|r| {
6502 r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
6503 })
6504 {
6505 Starter::Resume(id.to_owned())
6506 } else {
6507 Starter::Review(selected.branch.clone())
6508 }
6509}
6510
6511fn take_divergence_answer(
6515 branch: &str,
6516 remote: &str,
6517 task: &mut Task,
6518) -> Option<crate::reconcile::Choice> {
6519 let summary = crate::reconcile::summary_for(branch, remote);
6520 let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
6521 (a.question == summary)
6522 .then(|| crate::reconcile::Choice::from_answer(&a.answer))
6523 .flatten()
6524 .map(|c| (i, c))
6525 })?;
6526 task.answers.remove(idx);
6527 Some(choice)
6528}
6529
6530fn choose_starter(
6542 review_branch: Option<&str>,
6543 branch_exists: bool,
6544 unfinished: Option<&str>,
6545) -> Starter {
6546 match review_branch {
6547 Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
6548 Some(_) => Starter::Start,
6549 None => match unfinished {
6550 Some(id) => Starter::Resume(id.to_owned()),
6551 None => Starter::Start,
6552 },
6553 }
6554}
6555
6556fn review_retry_starter(
6560 task: &Task,
6561 previous: Option<&RunState>,
6562 branch: Option<&str>,
6563 exists: bool,
6564 unfinished: Option<&str>,
6565) -> Starter {
6566 if let Some(run) = previous
6567 && unfinished == Some(run.id.as_str())
6568 && run.reviewed_commits.is_some()
6569 && branch.is_some_and(|branch| {
6570 exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
6571 })
6572 && may_resume_run(run, task)
6573 {
6574 return Starter::Resume(run.id.clone());
6575 }
6576 match (branch, unfinished, &task.review_of) {
6577 (None, None, Some(branch)) => Starter::Review(branch.clone()),
6578 _ => choose_starter(branch, exists, unfinished),
6579 }
6580}
6581
6582fn review_branch_for<'a>(task: &'a Task, previous: Option<&RunState>) -> Option<&'a str> {
6584 task.review_branch
6585 .as_deref()
6586 .filter(|&branch| match &task.review_instruction {
6587 Some(authored) => *authored == task.instruction,
6588 None => previous.map_or_else(
6591 || task.review_of.as_deref() == Some(branch),
6592 |run| compatible_run_instruction(run, task),
6593 ),
6594 })
6595}
6596
6597fn may_resume_run(run: &RunState, task: &Task) -> bool {
6600 if !task.assignment_accepts(run) {
6601 return false;
6602 }
6603 task.resume_override
6604 .as_ref()
6605 .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
6606 || compatible_run_instruction(run, task)
6607}
6608
6609pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
6611 if let Some(authored) = &run.task_instruction {
6612 return compatible_instruction(authored, task);
6613 }
6614 if compatible_instruction(&run.instruction, task) {
6615 return true;
6616 }
6617 if run.reviewed_commits.is_some() {
6620 if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
6621 return strip_answers_block(authored, task).trim() == task.instruction.trim();
6622 }
6623 if let Some(branch) = &task.review_of {
6624 let canonical = format!(
6625 "Review the branch `{branch}` (review-only: no implementation, no judging)."
6626 );
6627 let generated = format!(
6628 "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"
6629 );
6630 return task.instruction == canonical && run.instruction.starts_with(&generated);
6631 }
6632 }
6633 false
6634}
6635
6636pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
6638 strip_answers_block(old, task) == task.instruction
6639}
6640
6641fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
6644 if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
6645 return fallback.to_path_buf();
6646 }
6647 task.repo.clone()
6648}
6649
6650const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
6654
6655fn answers_block(task: &Task, count: usize) -> String {
6657 let mut s = ANSWERS_HEADER.to_owned();
6658 for a in &task.answers[..count] {
6659 s.push_str(&format!("- {}: {}\n", a.question, a.answer));
6660 }
6661 s
6662}
6663
6664fn resumption_block(r: &crate::queue::Resumption) -> String {
6667 format!(
6668 "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
6669 Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
6670 r.generation, r.at, r.instruction, r.answers_through,
6671 )
6672}
6673
6674fn append_answers(base: &str, task: &Task) -> String {
6676 let mut s = base.to_owned();
6677 if !task.answers.is_empty() {
6678 s.push_str(&answers_block(task, task.answers.len()));
6679 }
6680 if let Some(r) = &task.resumption {
6681 s.push_str(&resumption_block(r));
6682 }
6683 s
6684}
6685
6686fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
6690 let mut instruction = instruction;
6691 for approval in task
6692 .resumption
6693 .iter()
6694 .chain(task.resumption_history.iter().rev())
6695 {
6696 if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
6697 instruction = base;
6698 break;
6699 }
6700 }
6701 for count in (1..=task.answers.len()).rev() {
6702 let block = answers_block(task, count);
6703 if let Some(base) = instruction.strip_suffix(&block) {
6704 return base;
6705 }
6706 }
6707 instruction
6708}
6709
6710fn instruction_for(task: &Task) -> String {
6718 append_answers(&task.instruction, task)
6719}
6720
6721fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
6733 append_answers(strip_answers_block(old_instruction, task), task)
6734}
6735
6736fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
6738 let failure = error.downcast_ref::<crate::config::ConfigFailure>();
6739 task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
6740 if let Some(cause) = task.hold_notice_cause.as_mut() {
6741 cause.target = failure.map(|f| f.target.clone());
6742 }
6743}
6744
6745#[derive(Debug, thiserror::Error)]
6746#[error("attachment `{name}` is recorded on the task but {path} is missing")]
6747struct MissingAttachment {
6748 name: String,
6749 path: PathBuf,
6750}
6751
6752fn task_attachments(
6754 queue: &Queue,
6755 task: &Task,
6756) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
6757 let paths = queue.attachment_paths(task);
6758 for (name, path) in task.attachments.iter().zip(&paths) {
6759 if !path.is_file() {
6760 return Err(MissingAttachment {
6761 name: name.clone(),
6762 path: path.clone(),
6763 });
6764 }
6765 }
6766 Ok(paths)
6767}
6768
6769fn prepare_instruction(
6780 starter: &Starter,
6781 old_instruction: Option<&str>,
6782 task: &Task,
6783) -> Option<String> {
6784 match starter {
6785 Starter::Start => Some(instruction_for(task)),
6786 Starter::Resume(_) => Some(resumed_instruction(
6787 old_instruction.expect("a resumed run always has a prior instruction"),
6788 task,
6789 )),
6790 Starter::Review(_) => None,
6791 }
6792}
6793
6794fn record(queue: &Queue, task: &mut Task) {
6798 if let Err(e) = queue.put(task) {
6799 tracing::error!("could not record task {}: {e:#}", task.short());
6800 let notice = Notice::error(
6801 "loop:record",
6802 format!(
6803 "Task {} state could not be saved: {}. Check the disk.",
6804 task.id,
6805 e.to_string().lines().next().unwrap_or("unknown save error")
6806 ),
6807 )
6808 .link(Link::Task {
6809 id: task.id.clone(),
6810 });
6811 match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
6813 Some(home) => notices::raise_in(home, notice),
6814 None => notices::raise(notice),
6815 }
6816 }
6817}
6818
6819fn runnable(queue: &Queue) -> Vec<Task> {
6825 let mut tasks: Vec<Task> = queue
6826 .list()
6827 .into_iter()
6828 .filter(|t| t.status.runnable())
6829 .collect();
6830 tasks.sort_unstable_by(crate::queue::dispatch_order);
6831 tasks
6832}
6833
6834fn describe(state: &RunState) -> String {
6848 let p = phrases(&state.config.graph.language);
6849 let mut detail = if state.status == RunStatus::Stalled {
6850 let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
6851 seats.sort_unstable();
6852 seats.dedup();
6853 if seats.is_empty() {
6854 p.quorum_lost.to_owned()
6855 } else {
6856 format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
6857 }
6858 } else {
6859 format!("{}{}", p.run_ended, state.status.display_label())
6860 };
6861 if let Some(cause) = state.verification_blocking_cause() {
6862 detail.push_str(&format!(" ({cause})"));
6863 } else if let Some(last) = state.events.last() {
6864 let unanswered = state
6868 .reviews
6869 .last()
6870 .filter(|r| {
6871 state.status == RunStatus::Blocked
6872 && last.node == "review"
6873 && r.incomplete()
6874 && r.blocking == 0
6875 && r.round == state.config.graph.review_rounds
6876 && r.e2e.iter().all(crate::run::CommandOutcome::ok)
6877 })
6878 .map(|r| (r.expected - r.answered, r.round));
6879 match unanswered {
6880 Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
6881 detail.push_str(&format!(
6882 " ({}: {})",
6883 last.node,
6884 (p.reviewers_never_answered)(missing, rounds)
6885 ));
6886 }
6887 _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
6888 }
6889 }
6890 detail.push_str(&format!(" [run {}]", state.id));
6891 detail
6892}
6893
6894const DIAGNOSTIC_MAX: usize = 4_000;
6900
6901const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
6906
6907fn diagnostic(state: &RunState) -> Option<String> {
6921 let mut parts: Vec<String> = Vec::new();
6922
6923 for o in state.gate.iter().filter(|o| !o.ok()) {
6925 parts.push(format!(
6926 "gate `{}` failed ({}):\n{}",
6927 o.command,
6928 notices::exit_status(o.code),
6929 crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
6930 ));
6931 }
6932
6933 if let Some(last) = state
6936 .events
6937 .iter()
6938 .rev()
6939 .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
6940 {
6941 parts.push(last.message.clone());
6942 }
6943
6944 if state.viable().is_empty() {
6951 for c in &state.candidates {
6952 if let Some(evidence) = &c.verified_noop {
6953 parts.push(format!(
6954 "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
6955 c.label
6956 ));
6957 } else if !c.summary.trim().is_empty() {
6958 parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
6959 } else if let Some(why) = &c.failed {
6960 parts.push(format!("candidate {}: {why}", c.label));
6961 }
6962 }
6963 }
6964
6965 if parts.is_empty() {
6966 return None;
6967 }
6968 Some(crate::run::tail(
6973 &parts.join("\n\n"),
6974 DIAGNOSTIC_MAX.saturating_sub(100),
6975 ))
6976}
6977
6978fn label(status: RunStatus) -> &'static str {
6986 status.as_str()
6987}
6988
6989pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
6991 match mode {
6992 "none" => Ok(MergeMode::None),
6993 "local" => Ok(MergeMode::Local),
6994 "pr" => Ok(MergeMode::Pr),
6995 other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
6996 }
6997}
6998
6999fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
7004 mutex
7005 .lock()
7006 .unwrap_or_else(std::sync::PoisonError::into_inner)
7007}
7008
7009#[cfg(test)]
7010mod tests {
7011 use super::*;
7012 use crate::queue::{Source, TaskStatus};
7013 use crate::run::{Candidate, CommandOutcome};
7014 use pretty_assertions::assert_eq;
7015
7016 fn task() -> Task {
7017 Task::new(
7018 "add retries".to_owned(),
7019 "add retries".to_owned(),
7020 PathBuf::from("/repo"),
7021 Source::Human,
7022 )
7023 }
7024
7025 #[test]
7026 fn dispatch_wait_aggregates_unique_skips_in_stable_count_order() {
7027 let skips = DispatchSkips::from([
7028 ("a".into(), SkipReason::CoolingDown),
7029 ("b".into(), SkipReason::WaitingOnLanding),
7030 ("c".into(), SkipReason::WaitingOnLanding),
7031 ("d".into(), SkipReason::OrdinaryCapacity),
7032 ]);
7033 let wait = aggregate_dispatch_wait(4, &skips).unwrap();
7034 assert_eq!(wait.runnable, 4);
7035 assert_eq!(
7036 wait.reasons
7037 .iter()
7038 .map(|r| (r.reason.as_str(), r.count))
7039 .collect::<Vec<_>>(),
7040 [
7041 ("waiting_on_landing", 2),
7042 ("cooling_down", 1),
7043 ("ordinary_capacity", 1)
7044 ]
7045 );
7046 assert_eq!(aggregate_dispatch_wait(0, &DispatchSkips::new()), None);
7047 assert!(
7048 aggregate_dispatch_wait(2, &DispatchSkips::new())
7049 .unwrap()
7050 .reasons
7051 .is_empty()
7052 );
7053 }
7054
7055 #[test]
7056 fn dispatch_wait_tracks_interrupt_withholding_and_set_changes() {
7057 let before = vec!["a".into(), "b".into(), "c".into()];
7058 let allowed = vec![task_with_id("b")];
7059 let skips = interrupt_skips(&before, &allowed);
7060 assert_eq!(
7061 skips,
7062 DispatchSkips::from([
7063 ("a".into(), SkipReason::InterruptGate),
7064 ("c".into(), SkipReason::InterruptGate),
7065 ])
7066 );
7067 let mut previous = DispatchSkips::new();
7068 assert!(!changed_dispatch_skips(&mut previous, DispatchSkips::new()));
7069 assert!(changed_dispatch_skips(&mut previous, skips.clone()));
7070 assert!(!changed_dispatch_skips(&mut previous, skips));
7071 assert!(changed_dispatch_skips(
7072 &mut previous,
7073 DispatchSkips::from([("a".into(), SkipReason::CoolingDown),])
7074 ));
7075 assert!(changed_dispatch_skips(&mut previous, DispatchSkips::new()));
7076 }
7077
7078 #[test]
7079 fn dispatch_wait_status_reads_legacy_and_future_reason_keys() {
7080 let mut value = serde_json::to_value(Status::new()).unwrap();
7081 value.as_object_mut().unwrap().remove("dispatch_wait");
7082 assert!(
7083 serde_json::from_value::<Status>(value.clone())
7084 .unwrap()
7085 .dispatch_wait
7086 .is_none()
7087 );
7088 assert!(
7089 serde_json::from_value::<Reading>(value.clone())
7090 .unwrap()
7091 .dispatch_wait
7092 .is_none()
7093 );
7094 value["dispatch_wait"] = serde_json::json!({
7095 "runnable": 3, "reasons": [{"reason": "future_reason", "count": 3}]
7096 });
7097 let reading = serde_json::from_value::<Reading>(value).unwrap();
7098 assert_eq!(
7099 reading.dispatch_wait.unwrap().reasons[0].reason,
7100 "future_reason"
7101 );
7102 }
7103
7104 fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
7105 let job = crate::worker::Job {
7106 id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
7107 sequence: 1,
7108 kind: "task".into(),
7109 key: format!("task:{}", request.task),
7110 payload: serde_json::to_value(request).unwrap(),
7111 generation: "a".repeat(64),
7112 version: None,
7113 status: crate::worker::Status::Starting,
7114 result: None,
7115 pid: None,
7116 created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
7117 finished_at: None,
7118 };
7119 let dir = home.join("workers/jobs").join(&job.id);
7120 std::fs::create_dir_all(&dir).unwrap();
7121 std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
7122 job
7123 }
7124
7125 #[test]
7126 fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
7127 let home = tempfile::tempdir().unwrap();
7128 let request = TaskWorker {
7129 opts: Opts::default(),
7130 queue: home.path().join("queue"),
7131 task: "startup".into(),
7132 lane: PermitKind::Ordinary,
7133 standalone: false,
7134 };
7135 let job = starting_task_reservation(home.path(), &request);
7136 let error = task_worker_spawn_error(
7137 home.path(),
7138 &request,
7139 anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
7140 )
7141 .expect_err("our own reservation must not turn a failed spawn into a resync");
7142 let active = crate::worker::active(home.path()).unwrap();
7143 assert_eq!(active.len(), 1);
7144 assert_eq!(active[0].id, job.id);
7145 assert_eq!(active[0].status, crate::worker::Status::Starting);
7146 assert!(
7147 crate::worker::control(home.path(), &job.key)
7148 .unwrap()
7149 .is_none()
7150 );
7151 let notices = notices::Notices::at(home.path().join("notifications")).list();
7152 assert_eq!(notices.len(), 1);
7153 assert_eq!(notices[0].key, "loop:worker-startup");
7154 assert!(!notices[0].message.contains("private-error-detail"));
7155 assert!(notices[0].message.contains(&request.task));
7156 assert!(
7157 notices[0]
7158 .message
7159 .contains("could not be started or acknowledged")
7160 );
7161 assert!(notices[0].message.contains("worker.log"));
7162 assert_eq!(
7163 notices[0].link,
7164 Some(Link::Task {
7165 id: request.task.clone()
7166 })
7167 );
7168 assert!(format!("{error:#}").contains("private-error-detail"));
7169 }
7170
7171 #[test]
7172 fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
7173 let home = tempfile::tempdir().unwrap();
7174 let mut request = TaskWorker {
7175 opts: Opts::default(),
7176 queue: home.path().join("queue"),
7177 task: "handoff".into(),
7178 lane: PermitKind::Ordinary,
7179 standalone: true,
7180 };
7181 let job = starting_task_reservation(home.path(), &request);
7182 request.standalone = false;
7183 task_worker_spawn_error(
7184 home.path(),
7185 &request,
7186 anyhow::anyhow!("operation key is already reserved for a different request"),
7187 )
7188 .expect("a different standalone request is the handoff race, not our startup failure");
7189 let active = crate::worker::active(home.path()).unwrap();
7190 assert_eq!(active.len(), 1);
7191 assert_eq!(active[0].id, job.id);
7192 assert_eq!(active[0].payload, job.payload);
7193 assert!(
7194 notices::Notices::at(home.path().join("notifications"))
7195 .list()
7196 .is_empty()
7197 );
7198 }
7199
7200 #[test]
7201 fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
7202 let home = tempfile::tempdir().unwrap();
7203 let queue = Queue::at(home.path().join("queue"));
7204 let mut task = task();
7205 task.runs = vec!["previous".into()];
7206 queue.put(&mut task).unwrap();
7207 let request = TaskWorker {
7208 opts: Opts::default(),
7209 queue: home.path().join("queue"),
7210 task: task.id.clone(),
7211 lane: PermitKind::Ordinary,
7212 standalone: false,
7213 };
7214 let job = starting_task_reservation(home.path(), &request);
7215 let claims = current_work(home.path(), Timestamp::now());
7216 assert_eq!(claims.len(), 1);
7217 assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
7218 assert_eq!(claims[0].run, "previous");
7219 assert!(other_claims_run(&claims, "previous", None));
7220 assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
7223 assert!(is_working_on(home.path(), "previous", Timestamp::now()));
7224 }
7225
7226 #[test]
7227 fn admission_excludes_only_the_callers_exact_reservation() {
7228 let own = Current {
7229 worker: Some("own".into()),
7230 task: "same-task".into(),
7231 run: "previous".into(),
7232 };
7233 assert!(!other_claims_run(
7234 std::slice::from_ref(&own),
7235 "previous",
7236 Some("own")
7237 ));
7238 assert!(other_claims_run(
7239 std::slice::from_ref(&own),
7240 "previous",
7241 None
7242 ));
7243 for worker in [None, Some("other".into())] {
7244 let other = Current {
7245 worker,
7246 ..own.clone()
7247 };
7248 assert!(other_claims_run(
7249 &[own.clone(), other],
7250 "previous",
7251 Some("own")
7252 ));
7253 }
7254 let legacy: Current =
7255 serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
7256 assert!(other_claims_run(&[legacy], "previous", Some("own")));
7257 }
7258
7259 #[test]
7260 fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
7261 let mut task = task();
7262 let mut run = run_state(RunStatus::Reviewing);
7263 run.task_instruction = Some(task.instruction.clone());
7264 run.reviewed_commits = Some(vec!["committed-fix".into()]);
7265 let branch = "magi/test/B";
7266 run.candidates.push(crate::run::Candidate {
7267 branch: branch.into(),
7268 ..candidate('B', "preserved work", false, None)
7269 });
7270 task.runs = vec![run.id.clone()];
7271 let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
7272 assert_eq!(
7273 review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
7274 Starter::Resume(run.id.clone())
7275 );
7276 assert!(matches!(
7277 review_retry_starter(
7278 &task,
7279 Some(&run),
7280 Some("different"),
7281 true,
7282 unfinished.as_deref()
7283 ),
7284 Starter::Review(_)
7285 ));
7286 assert_eq!(
7287 review_retry_starter(
7288 &task,
7289 Some(&run),
7290 Some(branch),
7291 false,
7292 unfinished.as_deref()
7293 ),
7294 Starter::Start
7295 );
7296 task.instruction.push_str(" changed criteria");
7297 assert!(matches!(
7298 review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
7299 Starter::Review(_)
7300 ));
7301 assert!(matches!(
7302 review_retry_starter(&task, Some(&run), Some(branch), true, None),
7303 Starter::Review(_)
7304 ));
7305 }
7306
7307 #[test]
7308 fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
7309 let dir = tempfile::tempdir().unwrap();
7310 let queue = Queue::at(dir.path().join("queue"));
7311 let mut task = task();
7312 task.status = TaskStatus::Running;
7313 task.attempts = 1;
7314 queue.put(&mut task).unwrap();
7315 let live = std::collections::BTreeSet::from([task.id.clone()]);
7316 assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
7317 drop(queue.claim(&task.id).unwrap());
7318 let saved = queue.get(&task.id).unwrap();
7319 assert_eq!(saved.status, TaskStatus::Running);
7320 assert_eq!(saved.attempts, 1);
7321 assert!(saved.last_error.is_none());
7322 }
7323
7324 #[test]
7325 fn standalone_workers_do_not_consume_scheduler_lanes() {
7326 let request = |task: &str, lane, standalone| TaskWorker {
7327 opts: Opts::default(),
7328 queue: PathBuf::from("/queue"),
7329 task: task.to_owned(),
7330 lane,
7331 standalone,
7332 };
7333 let mut jobs = vec![
7334 request("ordinary", PermitKind::Ordinary, false),
7335 request("standalone-urgent", PermitKind::Urgent, true),
7336 request("standalone-ordinary", PermitKind::Ordinary, true),
7337 request("decision", PermitKind::None, false),
7338 ];
7339 assert_eq!(available_slots(&jobs, 2), (1, 1));
7340 jobs.push(request("urgent", PermitKind::Urgent, false));
7341 assert_eq!(available_slots(&jobs, 2), (1, 0));
7342 assert_eq!(available_slots(&jobs, 0), (0, 0));
7343 }
7344
7345 #[test]
7346 fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
7347 let now = Timestamp::now();
7348 let mut reading = Reading {
7349 pid: Some(std::process::id()),
7350 updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
7351 ..Reading::default()
7352 };
7353 assert!(!reading.running(now));
7354 assert!(legacy_scheduler_running(&reading, now, 0));
7355 reading.worker_protocol = Some(1);
7356 assert!(!legacy_scheduler_running(&reading, now, 0));
7357 }
7358
7359 #[test]
7360 fn selected_public_head_overrides_historical_resume_and_pin() {
7361 let mut t = task();
7362 let mut old = run_state(RunStatus::Blocked);
7363 let selection = crate::pr_recovery::Selection {
7364 url: "url".into(),
7365 branch: format!("magi/task-{}", t.id),
7366 head: "a".repeat(40),
7367 source_head: None,
7368 source_run: None,
7369 source_proof: None,
7370 disposition: Some(crate::pr_recovery::Disposition::Review),
7371 instruction: t.instruction.clone(),
7372 approved_at: Timestamp::now(),
7373 };
7374 t.resume_override = Some(crate::queue::OperatorResume {
7375 pinned_run: Some(old.id.clone()),
7376 question_id: "choice".into(),
7377 at: Timestamp::now(),
7378 conductor_rehold: None,
7379 forced: false,
7380 });
7381 assert_eq!(
7382 selected_starter(&selection, Some(&old), Some(&old.id)),
7383 Starter::Review(selection.branch.clone())
7384 );
7385 old.pr_recovery = Some(selection.clone());
7386 assert_eq!(
7387 selected_starter(&selection, Some(&old), Some(&old.id)),
7388 Starter::Review(selection.branch.clone())
7389 );
7390 old.reviewed_commits = Some(vec!["implementation".into()]);
7391 assert_eq!(
7392 selected_starter(&selection, Some(&old), Some(&old.id)),
7393 Starter::Resume(old.id.clone())
7394 );
7395 let mut changed = selection.clone();
7396 changed.head = "b".repeat(40);
7397 assert_eq!(
7398 selected_starter(&changed, Some(&old), Some(&old.id)),
7399 Starter::Review(changed.branch)
7400 );
7401 }
7402
7403 #[test]
7404 fn candidate_transplant_failure_is_one_actionable_hold() {
7405 let dir = tempfile::tempdir().unwrap();
7406 let q = Queue::at(dir.path().join("queue"));
7407 let mut t = task();
7408 let mut state = run_state(RunStatus::Blocked);
7409 state.event("prep", "cannot apply referenced commit: conflict");
7410 state.prep_failure = Some("conflict".into());
7411 t.start(state.id.clone());
7412 finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
7413 assert_eq!(t.attempts, 1);
7414 assert_eq!(t.status, TaskStatus::Held);
7415 assert!(t.operator_held());
7416 assert!(!t.status.runnable());
7417 assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
7418 let first = t.chat_notice_key().unwrap();
7419 t.chat_notices.push(first.clone());
7420 t.release_operator("test", None);
7421 state.id = "another-unprepared-run".into();
7422 t.start(state.id.clone());
7423 finish_attempt(
7424 3,
7425 &q,
7426 &mut t,
7427 &state,
7428 &[],
7429 Err(anyhow::anyhow!("still conflicts")),
7430 );
7431 assert_eq!(
7432 t.chat_notice_key().as_ref(),
7433 Some(&first),
7434 "no work happened"
7435 );
7436 t.release_operator("test", None);
7437 state.prep_failure = None;
7438 state.status = RunStatus::Failed;
7439 state.begin_pass();
7440 t.start(state.id.clone());
7441 finish_attempt(
7442 1,
7443 &q,
7444 &mut t,
7445 &state,
7446 &[],
7447 Err(anyhow::anyhow!("new gate failure")),
7448 );
7449 let failure = t.chat_notice_key().unwrap();
7450 assert_ne!(failure, first, "approved recovery reached a real failure");
7451 t.release_operator("test", None);
7452 state.begin_pass();
7453 t.start(state.id.clone());
7454 finish_attempt(
7455 1,
7456 &q,
7457 &mut t,
7458 &state,
7459 &[],
7460 Err(anyhow::anyhow!("new failure on resume")),
7461 );
7462 assert_ne!(
7463 t.chat_notice_key().as_ref(),
7464 Some(&failure),
7465 "a new settled pass"
7466 );
7467 }
7468
7469 #[test]
7470 fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
7471 for source in ["cli", "web"] {
7472 let mut t = task();
7473 let mut run = run_state(RunStatus::Blocked);
7474 run.instruction = "Run A original criteria".into();
7475 run.task_instruction = Some(run.instruction.clone());
7476 t.start(run.id.clone());
7477 t.release_operator("choice", Some("resume-question"));
7478 t.resume_override = Some(crate::queue::OperatorResume {
7479 question_id: "resume-question".into(),
7480 at: Timestamp::now(),
7481 conductor_rehold: None,
7482 forced: true,
7483 pinned_run: Some(run.id.clone()),
7484 });
7485 t.hold_machine(Some("not enough free space to start a run".into()));
7486 let mut unchanged = t.clone();
7487 unchanged
7488 .edit("title changed".into(), unchanged.instruction.clone())
7489 .unwrap();
7490 unchanged.release_operator(source, None);
7491 assert_eq!(
7492 unchanged
7493 .resume_override
7494 .as_ref()
7495 .unwrap()
7496 .pinned_run
7497 .as_deref(),
7498 Some(run.id.as_str())
7499 );
7500 assert!(!compatible_run_instruction(&run, &unchanged));
7501 assert!(may_resume_run(&run, &unchanged));
7502
7503 t.edit(
7504 "approved recovery".into(),
7505 "Reuse measured PR head B; fix Clippy; review".into(),
7506 )
7507 .unwrap();
7508 assert!(t.resume_override.is_none());
7509 t.release_operator(source, None);
7510 let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
7511 assert!(reloaded.resume_override.is_none());
7512 assert!(!may_resume_run(&run, &reloaded));
7513 let unfinished =
7514 unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
7515 .filter(|_| may_resume_run(&run, &reloaded));
7516 assert_eq!(
7517 choose_starter(None, false, unfinished.as_deref()),
7518 Starter::Start
7519 );
7520 assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
7521 assert_eq!(
7522 reloaded.resumption_history[0].question_id.as_deref(),
7523 Some("resume-question")
7524 );
7525
7526 unchanged.instruction = "Reuse measured PR head B".into();
7529 unchanged.hold_machine(Some("disk hold".into()));
7530 unchanged.release_operator(source, None);
7531 assert!(unchanged.resume_override.is_none());
7532 assert!(!may_resume_run(&run, &unchanged));
7533 }
7534 }
7535
7536 #[test]
7537 fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
7538 let mut t = task();
7539 let mut run = run_state(RunStatus::Blocked);
7540 t.review_of = Some("approved-head".into());
7541 t.instruction =
7542 "Review the branch `approved-head` (review-only: no implementation, no judging)."
7543 .into();
7544 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();
7545 run.reviewed_commits = Some(vec!["Commit log".into()]);
7546 t.start(run.id.clone());
7547 t.hold_machine(Some("interrupted review".into()));
7548 t.release_operator("cli", None);
7549 assert!(
7550 compatible_run_instruction(&run, &t),
7551 "legacy explicit review remains resumable"
7552 );
7553 let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
7554 .filter(|_| compatible_run_instruction(&run, &t));
7555 assert_eq!(
7556 choose_starter(None, false, unfinished.as_deref()),
7557 Starter::Resume(run.id.clone())
7558 );
7559 run.task_instruction = Some(t.instruction.clone());
7560 assert!(compatible_run_instruction(&run, &t));
7561 let reloaded: RunState =
7562 serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
7563 assert!(compatible_run_instruction(&reloaded, &t));
7564 t.edit(
7565 "new approved head".into(),
7566 "Reuse measured PR head B".into(),
7567 )
7568 .unwrap();
7569 assert!(!compatible_run_instruction(&run, &t));
7570
7571 t.review_of = None;
7573 t.instruction = "Fix Clippy on approved head".into();
7574 run.task_instruction = None;
7575 run.instruction = format!(
7576 "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
7577 t.instruction
7578 );
7579 assert!(compatible_run_instruction(&run, &t));
7580 t.instruction.push('\n');
7581 assert!(
7582 compatible_run_instruction(&run, &t),
7583 "legacy generated review trimmed the original criteria"
7584 );
7585 t.hold_for_handover(Some("approved-head".into()), "refused".into());
7586 assert_eq!(review_branch_for(&t, Some(&run)), Some("approved-head"));
7587 t.edit("new plan".into(), "Reuse measured PR head B".into())
7588 .unwrap();
7589 assert!(review_branch_for(&t, Some(&run)).is_none());
7590 assert!(!compatible_run_instruction(&run, &t));
7591 t.review_branch = Some("approved-head".into());
7592 t.review_instruction = None;
7593 assert!(
7594 review_branch_for(&t, Some(&run)).is_none(),
7595 "legacy retained candidate cannot replace a revised approved head"
7596 );
7597 }
7598
7599 #[test]
7600 fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
7601 let home = crate::run::test_home();
7602 crate::run::pin_test_home();
7603 let dir = tempfile::tempdir().unwrap();
7604 let queue = Queue::at(dir.path().join("queue"));
7605 for resume in [true, false] {
7606 let state = run_state(RunStatus::Blocked);
7607 let mut t = task();
7608 t.start(state.id.clone());
7609 let action = if resume {
7610 ask::ChoiceAction::Resume {
7611 run: state.id.clone(),
7612 }
7613 } else {
7614 ask::ChoiceAction::Requeue
7615 };
7616 let mut q = action_question(&state.id, action);
7617 q.status = ask::QuestionStatus::Open;
7618 q.answer = None;
7619 q.answered_at = None;
7620 t.fail("run stopped with a question", 3);
7621 hold_if_runnable(&queue, &mut t);
7622 assert!(t.operator_decided_at.is_none());
7623 assert!(t.operator_held());
7624 q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
7625 let expected = if resume {
7626 ActionDecision::Resume(state.id.clone())
7627 } else {
7628 ActionDecision::Requeue
7629 };
7630 assert_eq!(
7631 decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
7632 expected
7633 );
7634 t.hold_manual(Some("later explicit hold".into()));
7635 assert_eq!(
7636 decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
7637 ActionDecision::Stale
7638 );
7639 }
7640 }
7641
7642 #[test]
7643 fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
7644 let mut t = task();
7645 t.answers.push(crate::queue::AnsweredQuestion {
7646 question: "Inspect the remote?".into(),
7647 answer: "Inspect then wait".into(),
7648 });
7649 let old = instruction_for(&t);
7650 assert!(compatible_instruction(&old, &t));
7651 t.instruction = "Reuse approved PR head and review".into();
7652 t.release_operator("cli", None);
7653 assert!(!compatible_instruction(&old, &t));
7654 let approved = instruction_for(&t);
7655 assert!(approved.contains("waiting premises are superseded"));
7656 assert!(compatible_instruction(&approved, &t));
7657 assert_eq!(resumed_instruction(&approved, &t), approved);
7658 t.release_operator("web", None);
7659 assert!(compatible_instruction(&approved, &t));
7660 assert_eq!(t.resumption_history.len(), 1);
7661 t.start("run".into());
7662 assert!(instruction_for(&t).contains("Explicit operator resumption"));
7663 }
7664
7665 #[test]
7669 fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
7670 let mut state = RunState::new(
7671 PathBuf::from("/repo"),
7672 "main".into(),
7673 "base".into(),
7674 "task".into(),
7675 Config::default(),
7676 );
7677 state.status = RunStatus::Landing;
7678 state.parked = true;
7679 state.pr_pushed_head = Some("head".into());
7680 state.land_unrelated = Some(
7681 serde_json::from_value(serde_json::json!({
7682 "head": "head", "question": "ci-question",
7683 "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
7684 }))
7685 .unwrap(),
7686 );
7687 let mut t = task();
7688 t.start(state.id.clone());
7689 let verdict = Verdict {
7690 status: RunStatus::Landing,
7691 left_pr: true,
7692 quota_hit: false,
7693 parked: true,
7694 no_viable_candidates: false,
7695 };
7696 settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
7697 assert_eq!(t.attempts, 0);
7698 assert_eq!(t.status, TaskStatus::Held);
7699 assert!(!t.operator_held());
7700 assert!(
7701 t.hold_reason
7702 .as_deref()
7703 .unwrap()
7704 .starts_with("[ci-unrelated]")
7705 );
7706 t.attempts = 1;
7708 settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
7709 assert_eq!(t.attempts, 1);
7710 assert_eq!(t.passes.len(), 1);
7711 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
7712 state.pr_pushed_head = Some("new-head".into());
7713 state.parked = false;
7714 state.status = RunStatus::Blocked;
7715 let stale = Verdict {
7716 status: RunStatus::Blocked,
7717 parked: false,
7718 ..verdict
7719 };
7720 settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
7721 assert_eq!(t.attempts, 1);
7722 state.begin_pass();
7724 state.begin_pass();
7725 state.status = RunStatus::Landing;
7726 state.parked = true;
7727 state.pr_pushed_head = Some("head".into());
7728 settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
7729 assert_eq!(t.attempts, 0);
7730 assert_eq!(t.passes.len(), 2);
7731 }
7732
7733 #[test]
7734 fn orphan_recovery_does_not_refund_a_previous_pass_loss() {
7735 let mut state = run_state(RunStatus::Failed);
7736 state
7737 .quota
7738 .push(loss("advisor-1", "2026-10-22T14:38:00Z", None));
7739 state.begin_pass();
7740 let mut t = task();
7741 t.start(state.id.clone());
7742 reclaim(&mut t, Some(state), 2, "en");
7743 assert_eq!(t.attempts, 1);
7744 }
7745
7746 #[test]
7747 fn an_all_seats_unauthenticated_node_refunds_and_holds_without_retry() {
7748 let mut state = run_state(RunStatus::Blocked);
7749 let losses: Vec<_> = ["alpha", "beta"]
7750 .into_iter()
7751 .enumerate()
7752 .map(|(i, agent)| {
7753 QuotaLoss::from_report(
7754 format!("advisor-{i}"),
7755 "advise",
7756 Some(&crate::agent::Quota {
7757 cause: crate::agent::QuotaCause::Authentication,
7758 agent: agent.to_owned(),
7759 reset: None,
7760 }),
7761 )
7762 })
7763 .collect();
7764 crate::graph::block_machine_outage(&mut state, "advise", &losses);
7765 state.quota = losses;
7766 let mut t = task();
7767 t.start(state.id.clone());
7768 let verdict = Verdict {
7769 status: state.status,
7770 left_pr: false,
7771 quota_hit: true,
7772 parked: false,
7773 no_viable_candidates: true,
7774 };
7775 settle_and_diagnose(&mut t, verdict, "authentication unavailable", 2, &state);
7776 assert_eq!(t.attempts, 0);
7777 assert_eq!(t.status, TaskStatus::Held);
7778 assert!(!t.operator_held());
7779 let reason = t.hold_reason.as_deref().unwrap();
7780 assert!(reason.starts_with("[authentication]"));
7781 assert!(
7782 reason.contains("alpha")
7783 && reason.contains("beta")
7784 && reason.contains("re-authenticate")
7785 );
7786 assert!(cooldown_until(&state.quota, Timestamp::now()).is_none());
7787 let mut orphan = task();
7789 orphan.start(state.id.clone());
7790 reclaim(&mut orphan, Some(state), 2, "en");
7791 assert_eq!(orphan.attempts, 0);
7792 assert_eq!(orphan.status, TaskStatus::Held);
7793 }
7794
7795 #[test]
7796 fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
7797 let mut state = RunState::new(
7798 PathBuf::from("/repo"),
7799 "main".to_owned(),
7800 "abc1234".to_owned(),
7801 "task".to_owned(),
7802 Config::default(),
7803 );
7804 state.status = RunStatus::Blocked;
7805 state.resource_block = Some(crate::run::ResourceBlock {
7806 cause: crate::run::ResourceBlockCause::Other,
7807 node: "graft".to_owned(),
7808 kind: "shared build cache".to_owned(),
7809 detail: "timed out".to_owned(),
7810 at: jiff::Timestamp::now(),
7811 });
7812 let mut t = task();
7813 t.start("20260902-000000-aaaa".to_owned());
7814 assert_eq!(t.attempts, 1);
7815 let verdict = Verdict {
7816 status: RunStatus::Blocked,
7817 left_pr: false,
7818 quota_hit: false,
7819 parked: false,
7820 no_viable_candidates: false,
7821 };
7822 settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
7823 assert_eq!(t.status, TaskStatus::Held);
7824 assert_eq!(t.attempts, 0, "the attempt is refunded");
7825 assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
7826 assert!(
7827 !t.operator_held(),
7828 "a machine hold, released without a human"
7829 );
7830
7831 let mut selected = task();
7832 selected.start("20260902-000000-cccc".into());
7833 selected.replacement = Some(crate::merge_decision::Replacement {
7834 question: "fixture".into(),
7835 run: "earlier".into(),
7836 pr: "https://example.invalid/pr/1".into(),
7837 agent: "selected".into(),
7838 context: "fixture".into(),
7839 });
7840 state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
7841 settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
7842 assert_eq!(selected.attempts, 0);
7843 assert!(
7844 !selected.operator_held(),
7845 "a selected agent also retains a machine resource hold"
7846 );
7847 assert!(
7848 selected
7849 .hold_reason
7850 .as_deref()
7851 .unwrap()
7852 .starts_with("[resource] ")
7853 );
7854
7855 let mut p = task();
7857 p.start("20260902-000000-bbbb".to_owned());
7858 settle_and_diagnose(
7859 &mut p,
7860 Verdict {
7861 parked: true,
7862 ..verdict
7863 },
7864 "parked",
7865 2,
7866 &state,
7867 );
7868 assert_eq!(p.status, TaskStatus::Parked);
7869 assert_eq!(
7870 p.attempts, 0,
7871 "parking refunds once rather than also settling the resource hold"
7872 );
7873 }
7874
7875 #[test]
7876 fn record_failure_notice_links_the_task() {
7877 let dir = tempfile::tempdir().unwrap();
7878 std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
7881 let queue = Queue::at(dir.path().join("queue"));
7882 let mut t = interrupt_task("rec-fail-1");
7883 record(&queue, &mut t);
7884
7885 let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
7886 assert_eq!(found.len(), 1);
7887 assert_eq!(found[0].key, "loop:record");
7888 assert_eq!(
7889 found[0].link,
7890 Some(Link::Task {
7891 id: "rec-fail-1".to_owned()
7892 })
7893 );
7894 }
7895
7896 fn interrupt_task(id: &str) -> Task {
7899 let mut t = task();
7900 t.id = id.to_owned();
7901 t.interrupt = true;
7902 t
7903 }
7904
7905 fn task_with_id(id: &str) -> Task {
7907 let mut t = task();
7908 t.id = id.to_owned();
7909 t
7910 }
7911
7912 fn urgent_task(id: &str) -> Task {
7914 let mut t = task();
7915 t.id = id.to_owned();
7916 t.urgent = true;
7917 t
7918 }
7919
7920 #[test]
7921 fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
7922 let dir = tempfile::tempdir().unwrap();
7923 let queue = Queue::at(dir.path().join("queue"));
7924 let mut parked = task_with_id("parked");
7925 parked.start("run".into());
7926 parked.park("upgrade");
7927 parked.record_pass_at(
7928 "run",
7929 0,
7930 Some(Timestamp::now()),
7931 1,
7932 Some(crate::run::ParkCause::Upgrade {
7933 from: "old".into(),
7934 to: None,
7935 }),
7936 );
7937 let mut fresh = task_with_id("fresh");
7938 fresh.priority = 100;
7939 let mut urgent_task = urgent_task("urgent");
7940 for t in [&mut parked, &mut fresh, &mut urgent_task] {
7941 queue.put(t).unwrap();
7942 }
7943 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7944 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7945 let candidates = runnable(&queue);
7946 assert_eq!(candidates[0].id, parked.id);
7947 let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
7948 assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_err());
7949 assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_ok());
7950 drop(first);
7951 let claimed_elsewhere = queue.claim(&parked.id).unwrap();
7952 let next = runnable(&queue)
7953 .into_iter()
7954 .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent).ok())
7955 .unwrap();
7956 assert_eq!(next.task.id, fresh.id);
7957 assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
7958 drop(claimed_elsewhere);
7959 drop(next);
7960 assert!(matches!(
7961 claim_dispatch(&queue, &parked, true, &ordinary, &urgent),
7962 Err(SkipReason::CoolingDown)
7963 ));
7964 }
7965
7966 #[test]
7967 fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
7968 let dir = tempfile::tempdir().unwrap();
7969 let queue = Queue::at(dir.path().join("queue"));
7970 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7971 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7972 let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
7973 let mut first = task();
7974 queue.put(&mut first).unwrap();
7975 let stale_plain = queue.get(&first.id).unwrap();
7976 first.set_urgent(true).unwrap();
7977 queue.put(&mut first).unwrap();
7978 let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
7979 let mut second = urgent_task("second");
7980 queue.put(&mut second).unwrap();
7981 assert!(matches!(
7982 claim_dispatch(&queue, &second, false, &ordinary, &urgent),
7983 Err(SkipReason::UrgentCapacity)
7984 ));
7985 drop(queue.claim(&second.id).unwrap());
7986 assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
7987 drop(dispatched);
7988 let stale_urgent = queue.get(&first.id).unwrap();
7989 first.set_urgent(false).unwrap();
7990 queue.put(&mut first).unwrap();
7991 assert!(matches!(
7992 claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent),
7993 Err(SkipReason::OrdinaryCapacity)
7994 ));
7995 assert_eq!(urgent.available_permits(), 1);
7996 drop(queue.claim(&first.id).unwrap());
7997 drop(occupied);
7998 }
7999
8000 #[test]
8001 fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
8002 let dir = tempfile::tempdir().unwrap();
8003 let queue = Queue::at(dir.path().join("queue"));
8004 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
8005 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
8006 let mut t = task();
8007 queue.put(&mut t).unwrap();
8008 for enabled in [true, false] {
8009 let stale = queue.get(&t.id).unwrap();
8010 t.set_urgent(enabled).unwrap();
8011 queue.put(&mut t).unwrap();
8012 assert_ne!(stale.urgent, enabled);
8013 let DispatchClaim {
8014 task: fresh,
8015 claim,
8016 permit,
8017 } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
8018 assert_eq!(fresh.urgent, enabled);
8019 assert_eq!(ordinary.available_permits(), usize::from(enabled));
8020 assert_eq!(urgent.available_permits(), usize::from(!enabled));
8021 assert!(queue.claim(&t.id).is_err());
8022 assert_eq!(fresh.attempts, stale.attempts);
8023 drop((claim, permit));
8024 assert_eq!(ordinary.available_permits(), 1);
8025 assert_eq!(urgent.available_permits(), 1);
8026 }
8027 t.set_urgent(true).unwrap();
8028 queue.put(&mut t).unwrap();
8029 let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
8030 assert!(matches!(
8031 claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8032 Err(SkipReason::UrgentCapacity)
8033 ));
8034 assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
8035 drop(queue.claim(&t.id).unwrap());
8036 assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
8037 drop(occupied);
8038 assert!(matches!(
8039 claim_dispatch(&queue, &t, true, &ordinary, &urgent),
8040 Err(SkipReason::CoolingDown)
8041 ));
8042 drop(queue.claim(&t.id).unwrap());
8043 let held = queue.claim(&t.id).unwrap();
8044 assert!(matches!(
8045 claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8046 Err(SkipReason::ClaimUnavailable)
8047 ));
8048 drop(held);
8049 t.status = TaskStatus::Held;
8050 queue.put(&mut t).unwrap();
8051 assert!(matches!(
8052 claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8053 Err(SkipReason::NoLongerRunnable)
8054 ));
8055 drop(queue.claim(&t.id).unwrap());
8056 std::fs::remove_file(queue.path_of(&t.id)).unwrap();
8057 assert!(matches!(
8058 claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8059 Err(SkipReason::RereadFailed)
8060 ));
8061 drop(queue.claim(&t.id).unwrap());
8062 assert_eq!(urgent.available_permits(), 1);
8063 }
8064
8065 #[test]
8070 fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
8071 assert_eq!(permit_kind(true, false), PermitKind::None);
8072 assert_eq!(permit_kind(true, true), PermitKind::None);
8073 }
8074
8075 #[test]
8080 fn permit_kind_separates_urgent_from_ordinary() {
8081 assert_eq!(permit_kind(false, true), PermitKind::Urgent);
8082 assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
8083 }
8084
8085 #[test]
8092 fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
8093 let cfg = Config::default();
8094 let repo = Path::new("/any/repo/path");
8095
8096 let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(1024))
8097 .expect("must hold below the threshold");
8098 assert!(reason.contains("1024"), "{reason}");
8099 assert!(
8100 reason.contains(&cfg.disk.min_free_bytes.to_string()),
8101 "{reason}"
8102 );
8103
8104 assert_eq!(
8105 disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(cfg.disk.min_free_bytes)),
8106 None,
8107 "exactly at the floor is open"
8108 );
8109 assert_eq!(
8110 disk_gate_with(
8111 repo,
8112 &cfg,
8113 PathBuf::new,
8114 |_| Ok(cfg.disk.min_free_bytes + 1)
8115 ),
8116 None,
8117 "comfortably above the floor is open"
8118 );
8119 }
8120
8121 #[test]
8122 fn disk_gate_with_checks_cache_and_worktree_volumes_and_measurement_errors() {
8123 let dir = tempfile::tempdir().unwrap();
8124 let repo = dir.path().join("repo");
8125 let cache = dir.path().join("cache");
8126 let worktrees = dir.path().join("worktrees");
8127 for path in [&repo, &cache, &worktrees] {
8128 std::fs::create_dir(path).unwrap();
8129 }
8130 let mut cfg = Config::default();
8131 cfg.graph.worktree_root = Some(worktrees.clone());
8132 cfg.verify.gate = vec![format!(
8133 "CARGO_TARGET_DIR='{}' cargo build",
8134 cache.display()
8135 )];
8136 for blocked in [&cache, &worktrees] {
8137 for unmeasured in [false, true] {
8138 assert!(
8139 disk_gate_with(&repo, &cfg, PathBuf::new, |path| {
8140 if path == blocked {
8141 if unmeasured {
8142 Err(anyhow::anyhow!("measurement failed"))
8143 } else {
8144 Ok(0)
8145 }
8146 } else {
8147 Ok(u64::MAX)
8148 }
8149 })
8150 .is_some(),
8151 "a blocked secondary output volume must close admission"
8152 );
8153 }
8154 }
8155 assert!(disk_gate_with(&repo, &cfg, PathBuf::new, |_| Ok(u64::MAX)).is_none());
8156 }
8157
8158 #[test]
8159 fn isolated_admission_measures_the_run_home_instead_of_the_shared_cache() {
8160 let dir = tempfile::tempdir().unwrap();
8161 let repo = dir.path().join("repo");
8162 let cache = dir.path().join("cache");
8163 let home_parent = dir.path().join("run-volume");
8164 let home = home_parent.join("new-home");
8165 for path in [&repo, &cache, &home_parent] {
8166 std::fs::create_dir(path).unwrap();
8167 }
8168 let mut cfg = Config::default();
8169 cfg.graph.worktree_root = Some(repo.clone());
8170 cfg.verify.gate = vec![format!(
8171 "CARGO_TARGET_DIR='{}' cargo build",
8172 cache.display()
8173 )];
8174 cfg.verify.build_cache = BuildCache::Isolated;
8175 let denied = |blocked: &Path| {
8176 disk_gate_with(
8177 &repo,
8178 &cfg,
8179 || home.clone(),
8180 |path| Ok(if path == blocked { 0 } else { u64::MAX }),
8181 )
8182 .is_some()
8183 };
8184 assert!(!denied(&cache));
8185 assert!(denied(&home_parent));
8186 }
8187
8188 #[test]
8189 fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
8190 let mut cfg = Config::default();
8191 cfg.disk.min_free_bytes = 0;
8192 let repo = Path::new("/any/repo/path");
8193 assert_eq!(
8194 disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(0)),
8195 None,
8196 "a zero floor never measures at all"
8197 );
8198 }
8199
8200 #[test]
8201 fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
8202 let cfg = Config::default();
8203 let repo = Path::new("/any/repo/path");
8204 let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| {
8205 Err(anyhow::anyhow!("no df on this box"))
8206 })
8207 .expect("a measurement failure must close the gate, not open it");
8208 assert!(reason.contains("could not measure"), "{reason}");
8209 }
8210
8211 #[test]
8212 fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
8213 let ordinary = task();
8214 let next = advance_interrupt(
8215 Interrupt::Idle,
8216 std::slice::from_ref(&ordinary.id),
8217 std::slice::from_ref(&ordinary),
8218 );
8219 assert_eq!(next, Interrupt::Idle);
8220 }
8221
8222 #[test]
8223 fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
8224 let marked = interrupt_task("marked");
8227 let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
8228 assert_eq!(next, Interrupt::Idle);
8229 }
8230
8231 #[test]
8232 fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
8233 let marked = interrupt_task("marked");
8234 let next = advance_interrupt(
8235 Interrupt::Idle,
8236 &["running".to_owned()],
8237 std::slice::from_ref(&marked),
8238 );
8239 assert_eq!(
8240 next,
8241 Interrupt::Parking {
8242 parked: vec!["running".to_owned()],
8243 interrupt_task: "marked".to_owned(),
8244 }
8245 );
8246 }
8247
8248 #[test]
8257 fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
8258 let marked = interrupt_task("marked");
8259
8260 let two = advance_interrupt(
8261 Interrupt::Idle,
8262 &["a".to_owned(), "b".to_owned()],
8263 std::slice::from_ref(&marked),
8264 );
8265 assert_eq!(two, Interrupt::Idle);
8266
8267 let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
8268 assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
8269 }
8270
8271 #[test]
8272 fn parking_holds_until_every_parked_id_has_actually_left_flight() {
8273 let state = Interrupt::Parking {
8274 parked: vec!["running".to_owned()],
8275 interrupt_task: "marked".to_owned(),
8276 };
8277 let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
8279 assert_eq!(still_going, state);
8280
8281 let stopped_but_not_yet_dispatched =
8285 advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
8286 assert_eq!(stopped_but_not_yet_dispatched, state);
8287
8288 let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
8290 assert_eq!(
8291 dispatched,
8292 Interrupt::Running {
8293 parked: vec!["running".to_owned()],
8294 interrupt_task: "marked".to_owned(),
8295 }
8296 );
8297 }
8298
8299 #[test]
8300 fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
8301 let state = Interrupt::Running {
8302 parked: vec!["running".to_owned()],
8303 interrupt_task: "marked".to_owned(),
8304 };
8305 let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
8306 assert_eq!(still_running, state);
8307
8308 let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
8315 assert_eq!(
8316 ended,
8317 Interrupt::Resuming {
8318 parked: vec!["running".to_owned()]
8319 }
8320 );
8321 }
8322
8323 #[test]
8324 fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
8325 let state = Interrupt::Resuming {
8326 parked: vec!["running".to_owned()],
8327 };
8328 let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
8329 assert_eq!(still_waiting, state);
8330
8331 let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
8332 assert_eq!(dispatched, Interrupt::Idle);
8333 }
8334
8335 #[test]
8341 fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
8342 {
8343 let state = Interrupt::Parking {
8344 parked: vec!["running".to_owned()],
8345 interrupt_task: "marked".to_owned(),
8346 };
8347 let next = advance_interrupt(state, &[], &[]);
8350 assert_eq!(
8351 next,
8352 Interrupt::Resuming {
8353 parked: vec!["running".to_owned()]
8354 },
8355 "abandoning the interrupt must not abandon the resume it owes"
8356 );
8357 }
8358
8359 #[test]
8362 fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
8363 let state = Interrupt::Resuming {
8364 parked: vec!["running".to_owned()],
8365 };
8366 let next = advance_interrupt(state, &[], &[]);
8367 assert_eq!(
8368 next,
8369 Interrupt::Idle,
8370 "nothing is left to wait for; the loop must not stay wedged"
8371 );
8372 }
8373
8374 #[test]
8375 fn disabled_by_config_the_sequence_can_never_leave_idle() {
8376 let marked = interrupt_task("marked");
8377 let next = advance_interrupt_tick(
8378 false,
8379 Interrupt::Idle,
8380 &["running".to_owned()],
8381 std::slice::from_ref(&marked),
8382 );
8383 assert_eq!(
8384 next,
8385 Interrupt::Idle,
8386 "an unmarked, unconfigured daemon must behave exactly as before"
8387 );
8388 }
8389
8390 #[test]
8391 fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
8392 let state = Interrupt::Parking {
8393 parked: vec!["running".to_owned()],
8394 interrupt_task: "marked".to_owned(),
8395 };
8396 let candidates = vec![interrupt_task("marked"), task()];
8397 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
8398 assert!(
8399 allowed.is_empty(),
8400 "nothing may dispatch - not even the interrupt task itself - \
8401 until the parked run has actually stopped"
8402 );
8403 }
8404
8405 #[test]
8419 fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
8420 for state in [
8421 Interrupt::Parking {
8422 parked: vec!["running".to_owned()],
8423 interrupt_task: "marked".to_owned(),
8424 },
8425 Interrupt::Running {
8426 parked: vec!["running".to_owned()],
8427 interrupt_task: "marked".to_owned(),
8428 },
8429 Interrupt::Resuming {
8430 parked: vec!["running".to_owned()],
8431 },
8432 ] {
8433 let candidates = vec![
8434 interrupt_task("marked"),
8435 urgent_task("hot"),
8436 task_with_id("ordinary"),
8437 ];
8438 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
8439 assert!(
8440 !allowed.iter().any(|t| t.id == "hot"),
8441 "an urgent candidate must wait out the same gate as anything \
8442 else while the run it would run alongside has not actually \
8443 left flight, for state {state:?}: {allowed:?}"
8444 );
8445 }
8446 }
8447
8448 #[test]
8454 fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
8455 let state = Interrupt::Resuming {
8456 parked: vec!["hot".to_owned()],
8457 };
8458 let candidates = vec![urgent_task("hot"), task()];
8459 let allowed = interrupt_gate(&state, &[], candidates);
8460 assert_eq!(
8461 allowed.iter().filter(|t| t.id == "hot").count(),
8462 1,
8463 "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
8464 );
8465 }
8466
8467 #[test]
8468 fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
8469 let state = Interrupt::Parking {
8470 parked: vec!["running".to_owned()],
8471 interrupt_task: "marked".to_owned(),
8472 };
8473 let other = task();
8474 let candidates = vec![interrupt_task("marked"), other.clone()];
8475 let allowed = interrupt_gate(&state, &[], candidates);
8476 assert_eq!(allowed.len(), 1);
8477 assert_eq!(allowed[0].id, "marked");
8478 }
8479
8480 #[test]
8481 fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
8482 let state = Interrupt::Running {
8483 parked: vec!["running".to_owned()],
8484 interrupt_task: "marked".to_owned(),
8485 };
8486 let candidates = vec![task(), task()];
8487 let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
8488 assert!(allowed.is_empty());
8489 }
8490
8491 #[test]
8498 fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
8499 let state = Interrupt::Resuming {
8500 parked: vec!["a".to_owned(), "c".to_owned()],
8501 };
8502 let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
8503 let allowed = interrupt_gate(&state, &[], candidates);
8504 assert_eq!(
8505 allowed.len(),
8506 1,
8507 "at most one candidate may be offered while resuming: {allowed:?}"
8508 );
8509 assert_eq!(allowed[0].id, "a");
8510 }
8511
8512 #[test]
8513 fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
8514 let state = Interrupt::Resuming {
8515 parked: vec!["a".to_owned()],
8516 };
8517 let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
8518 assert!(allowed.is_empty());
8519 }
8520
8521 #[test]
8527 fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
8528 let running = task(); let marked = interrupt_task("marked");
8530
8531 let mut state = Interrupt::Idle;
8532 let in_flight = vec![running.id.clone()];
8534 state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
8535 let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
8536 assert!(gated.is_empty(), "still waiting on `running` to park");
8537
8538 state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
8540 let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
8541 assert_eq!(
8542 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8543 vec!["marked"],
8544 "only the interrupt task may be offered to the dispatcher now"
8545 );
8546
8547 state = advance_interrupt_tick(
8549 true,
8550 state,
8551 &["marked".to_owned()],
8552 std::slice::from_ref(&running),
8553 );
8554 let gated = interrupt_gate(
8555 &state,
8556 &["marked".to_owned()],
8557 vec![marked.clone(), running.clone()],
8558 );
8559 assert!(
8560 gated.is_empty(),
8561 "the parked run must not be offered back while the interrupt \
8562 task is still running"
8563 );
8564
8565 let other = task_with_id("other");
8569 state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
8570 assert_eq!(
8571 state,
8572 Interrupt::Resuming {
8573 parked: vec![running.id.clone()]
8574 }
8575 );
8576 let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
8577 assert_eq!(
8578 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8579 vec![running.id.as_str()],
8580 "exactly the parked run resumes - not the unrelated task, even \
8581 though it was offered first"
8582 );
8583
8584 state = advance_interrupt_tick(
8588 true,
8589 state,
8590 std::slice::from_ref(&running.id),
8591 std::slice::from_ref(&other),
8592 );
8593 assert_eq!(state, Interrupt::Idle);
8594 let gated = interrupt_gate(
8595 &state,
8596 std::slice::from_ref(&running.id),
8597 vec![other.clone()],
8598 );
8599 assert_eq!(
8600 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8601 vec![other.id.as_str()],
8602 "ordinary dispatch is unrestricted again"
8603 );
8604 }
8605
8606 #[test]
8607 fn every_run_status_settles_the_task_it_came_from() {
8608 let table = [
8610 (RunStatus::Merged, TaskStatus::Done, 1),
8611 (RunStatus::Ready, TaskStatus::Done, 1),
8612 (RunStatus::Stalled, TaskStatus::Failed, 0),
8613 (RunStatus::Blocked, TaskStatus::Failed, 1),
8614 (RunStatus::Failed, TaskStatus::Failed, 1),
8615 (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
8616 (RunStatus::Prep, TaskStatus::Failed, 1),
8617 (RunStatus::Implementing, TaskStatus::Failed, 1),
8618 (RunStatus::Judging, TaskStatus::Failed, 1),
8619 (RunStatus::Deliberating, TaskStatus::Failed, 1),
8620 (RunStatus::Voting, TaskStatus::Failed, 1),
8621 (RunStatus::Reviewing, TaskStatus::Failed, 1),
8622 (RunStatus::Gating, TaskStatus::Failed, 1),
8623 ];
8624 for (run, want, attempts) in table {
8625 let mut t = task();
8626 t.start("20260902-000000-aaaa".to_owned());
8627 settle(
8628 &mut t,
8629 Verdict {
8630 status: run,
8631 left_pr: false,
8632 parked: false,
8633 quota_hit: matches!(run, RunStatus::Stalled),
8634 no_viable_candidates: false,
8635 },
8636 "why",
8637 2,
8638 );
8639 assert_eq!(t.status, want, "task status after {}", label(run));
8640 assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
8641 }
8642 }
8643
8644 #[test]
8645 fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
8646 let mut stalled = task();
8647 stalled.start("20260902-000000-aaaa".to_owned());
8648 settle(
8649 &mut stalled,
8650 Verdict {
8651 status: RunStatus::Stalled,
8652 left_pr: false,
8653 parked: false,
8654 quota_hit: true,
8655 no_viable_candidates: false,
8656 },
8657 "quota",
8658 1,
8659 );
8660 assert_eq!(stalled.attempts, 0);
8661 assert!(
8662 stalled.status.runnable(),
8663 "a machine problem must leave the task in line"
8664 );
8665
8666 let mut blocked = task();
8667 blocked.start("20260902-000000-aaaa".to_owned());
8668 settle(
8669 &mut blocked,
8670 Verdict {
8671 status: RunStatus::Blocked,
8672 left_pr: false,
8673 parked: false,
8674 quota_hit: false,
8675 no_viable_candidates: false,
8676 },
8677 "findings open",
8678 1,
8679 );
8680 assert_eq!(blocked.attempts, 1);
8681 assert_eq!(
8682 blocked.status,
8683 TaskStatus::Held,
8684 "the last attempt hands the task to a human"
8685 );
8686 }
8687
8688 #[test]
8689 fn a_run_that_opened_a_pull_request_is_never_re_competed() {
8690 let mut delivered = task();
8693 delivered.start("20260903-080619-01c2".to_owned());
8694 settle(
8695 &mut delivered,
8696 Verdict {
8697 status: RunStatus::Blocked,
8698 left_pr: true,
8699 parked: false,
8700 quota_hit: false,
8701 no_viable_candidates: false,
8702 },
8703 "no check status",
8704 4,
8705 );
8706 assert_eq!(
8707 delivered.status,
8708 TaskStatus::Held,
8709 "a pull request waiting on CI or a person is not a retryable failure"
8710 );
8711 assert!(
8712 !delivered.status.runnable(),
8713 "the loop must not pick this task up again"
8714 );
8715 assert_eq!(
8716 delivered.last_error.as_deref(),
8717 Some("no check status"),
8718 "the operator needs to be told what the gate was waiting for"
8719 );
8720
8721 let mut empty_handed = task();
8724 empty_handed.start("20260903-080619-01c2".to_owned());
8725 settle(
8726 &mut empty_handed,
8727 Verdict {
8728 status: RunStatus::Blocked,
8729 left_pr: false,
8730 parked: false,
8731 quota_hit: false,
8732 no_viable_candidates: false,
8733 },
8734 "findings open",
8735 4,
8736 );
8737 assert_eq!(empty_handed.status, TaskStatus::Failed);
8738 assert!(empty_handed.status.runnable());
8739 }
8740
8741 #[test]
8742 fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
8743 let mut noop = task();
8749 noop.start("20260912-131304-391f".to_owned());
8750 settle(
8751 &mut noop,
8752 Verdict {
8753 status: RunStatus::VerifiedNoop,
8754 left_pr: false,
8755 parked: false,
8756 quota_hit: false,
8757 no_viable_candidates: true,
8758 },
8759 "candidate A: already fixed by b32cfc4, on main",
8760 4,
8761 );
8762 assert_eq!(
8763 noop.status,
8764 TaskStatus::Held,
8765 "an unverified claim is a request for a human, not a failure"
8766 );
8767 assert!(
8768 !noop.status.runnable(),
8769 "the loop must not requeue this on the same unverified claim"
8770 );
8771 assert_eq!(noop.attempts, 1);
8776 }
8777
8778 #[test]
8779 fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
8780 let mut parked = task();
8785 parked.start("20260903-183634-2d98".to_owned());
8786 settle(
8787 &mut parked,
8788 Verdict {
8789 status: RunStatus::Implementing,
8790 left_pr: false,
8791 quota_hit: false,
8792 parked: true,
8793 no_viable_candidates: false,
8794 },
8795 "parked after `implementing`",
8796 2,
8797 );
8798 assert_eq!(parked.attempts, 0, "a park is refunded");
8799 assert!(
8800 parked.status.runnable(),
8801 "and the task stays in line so the next loop resumes its run"
8802 );
8803 assert_eq!(parked.status, TaskStatus::Parked);
8804 assert_eq!(
8805 parked.park_reason.as_deref(),
8806 Some("parked after `implementing`"),
8807 "the card says where it stopped"
8808 );
8809 assert_eq!(parked.last_error, None, "nothing failed");
8810
8811 let mut broken = task();
8815 broken.start("20260903-183634-2d98".to_owned());
8816 settle(
8817 &mut broken,
8818 Verdict {
8819 status: RunStatus::Implementing,
8820 left_pr: false,
8821 quota_hit: false,
8822 parked: false,
8823 no_viable_candidates: false,
8824 },
8825 "returned mid-flight",
8826 2,
8827 );
8828 assert_eq!(broken.attempts, 1);
8829 }
8830
8831 #[test]
8832 fn only_a_rate_limit_buys_the_task_its_attempt_back() {
8833 let mut flaky = task();
8838 flaky.start("20260903-123023-e633".to_owned());
8839 settle(
8840 &mut flaky,
8841 Verdict {
8842 status: RunStatus::Stalled,
8843 left_pr: false,
8844 parked: false,
8845 quota_hit: false,
8846 no_viable_candidates: false,
8847 },
8848 "verdict rests on 1 of 3 judges",
8849 2,
8850 );
8851 assert_eq!(
8852 flaky.attempts, 1,
8853 "flakiness spends an attempt, so `max_attempts` still bounds it"
8854 );
8855 assert!(flaky.status.runnable(), "and it is still worth retrying");
8856
8857 let mut limited = task();
8859 limited.start("20260903-123023-e633".to_owned());
8860 settle(
8861 &mut limited,
8862 Verdict {
8863 status: RunStatus::Stalled,
8864 left_pr: false,
8865 parked: false,
8866 quota_hit: true,
8867 no_viable_candidates: false,
8868 },
8869 "judge-2, judge-3 out of quota",
8870 2,
8871 );
8872 assert_eq!(limited.attempts, 0, "a quota window is refunded");
8873 assert!(limited.status.runnable());
8874
8875 let mut worn = task();
8878 for _ in 0..2 {
8879 worn.release();
8880 }
8881 worn.start("20260903-123023-e633".to_owned());
8882 worn.attempts = 2;
8883 settle(
8884 &mut worn,
8885 Verdict {
8886 status: RunStatus::Stalled,
8887 left_pr: false,
8888 parked: false,
8889 quota_hit: false,
8890 no_viable_candidates: false,
8891 },
8892 "no quorum again",
8893 2,
8894 );
8895 assert_eq!(worn.status, TaskStatus::Held);
8896 assert!(!worn.status.runnable());
8897 }
8898
8899 #[test]
8900 fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
8901 let mut wiped_out = task();
8908 wiped_out.start("20260907-025000-a1b2".to_owned());
8909 settle(
8910 &mut wiped_out,
8911 Verdict {
8912 status: RunStatus::Failed,
8913 left_pr: false,
8914 parked: false,
8915 quota_hit: true,
8916 no_viable_candidates: true,
8917 },
8918 "no candidate produced a change; nothing to judge",
8919 2,
8920 );
8921 assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
8922 assert!(
8923 wiped_out.status.runnable(),
8924 "a machine problem must leave the task in line"
8925 );
8926
8927 let mut partial_progress = task();
8933 partial_progress.start("20260907-025500-c3d4".to_owned());
8934 settle(
8935 &mut partial_progress,
8936 Verdict {
8937 status: RunStatus::Failed,
8938 left_pr: false,
8939 parked: false,
8940 quota_hit: true,
8941 no_viable_candidates: false,
8942 },
8943 "gate failed on the winning candidate",
8944 2,
8945 );
8946 assert_eq!(
8947 partial_progress.attempts, 1,
8948 "a candidate that actually produced a change spends the attempt \
8949 even though some other seat hit its quota"
8950 );
8951 assert!(partial_progress.status.runnable());
8952 }
8953
8954 #[test]
8955 fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
8956 let mut t = task();
8962 t.start("20260907-025000-a1b2".to_owned());
8963 let mut state = run_state(RunStatus::Failed);
8964 state.quota.push(QuotaLoss {
8965 cause: crate::agent::QuotaCause::UsageLimit,
8966 agent: String::new(),
8967 seat: "cand-a".to_owned(),
8968 node: "implement".to_owned(),
8969 at: Timestamp::now(),
8970 reset: None,
8971 });
8972 assert!(
8973 state.viable().is_empty(),
8974 "no candidate was added, so nothing is viable"
8975 );
8976 reclaim(&mut t, Some(state), 2, "en");
8977 assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
8978 assert!(t.status.runnable());
8979 }
8980
8981 #[test]
8982 fn a_held_task_is_never_offered_to_the_loop() {
8983 let dir = tempfile::tempdir().unwrap();
8984 let queue = Queue::at(dir.path().to_path_buf());
8985 for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
8986 let mut t = task();
8987 t.id = format!("2026090{n}-000000-000{n}");
8988 t.priority = priority;
8989 queue.put(&mut t).unwrap();
8990 }
8991 let mut held = task();
8992 held.id = "20260909-000000-9999".to_owned();
8993 held.priority = 99;
8994 held.hold_machine(None);
8995 queue.put(&mut held).unwrap();
8996
8997 let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
8998 assert_eq!(order.len(), 3);
8999 assert!(!order.contains(&held.id));
9000 assert_eq!(
9001 order.first().cloned(),
9002 queue.next_runnable().map(|t| t.id),
9003 "the loop's first candidate is exactly what the queue offers"
9004 );
9005 assert_eq!(
9006 order,
9007 vec![
9008 "20260902-000000-0002".to_owned(),
9009 "20260903-000000-0003".to_owned(),
9010 "20260901-000000-0001".to_owned(),
9011 ],
9012 "priority first, then oldest, so nothing starves"
9013 );
9014 }
9015
9016 #[test]
9017 fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
9018 let dir = tempfile::tempdir().unwrap();
9019 let queue = Queue::at(dir.path().to_path_buf());
9020 let mut old = task();
9021 old.id = "20260101-000000-old0".to_owned();
9022 queue.put(&mut old).unwrap();
9023 let mut fresh = task();
9024 fresh.id = "20260101-000000-new0".to_owned();
9025 queue.put(&mut fresh).unwrap();
9026
9027 std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
9031 std::thread::sleep(Duration::from_millis(60));
9032 let live = queue.claim(&fresh.id).unwrap();
9033
9034 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
9035 assert_eq!(swept, vec![old.id.clone()]);
9036 assert!(
9037 queue.claim(&old.id).is_ok(),
9038 "an unparseable lock older than the threshold is swept"
9039 );
9040 assert!(
9041 queue.claim(&fresh.id).is_err(),
9042 "a live pid protects its lock regardless of age"
9043 );
9044 drop(live);
9045 }
9046
9047 #[test]
9048 fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
9049 let dir = tempfile::tempdir().unwrap();
9052 let queue = Queue::at(dir.path().to_path_buf());
9053 let mut t = task();
9054 t.id = "20260101-000000-live".to_owned();
9055 queue.put(&mut t).unwrap();
9056
9057 let claim = queue.claim(&t.id).unwrap();
9058 std::thread::sleep(Duration::from_millis(60));
9059
9060 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
9061 assert!(
9062 swept.is_empty(),
9063 "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
9064 );
9065 assert!(
9066 queue.claim(&t.id).is_err(),
9067 "the lock still protects its task"
9068 );
9069 drop(claim);
9070 }
9071
9072 fn injected_dead_pid() -> u32 {
9075 std::process::id().checked_add(1).unwrap_or(1)
9076 }
9077
9078 #[test]
9079 fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
9080 let dir = tempfile::tempdir().unwrap();
9081 let queue = Queue::at(dir.path().to_path_buf());
9082 let mut t = task();
9083 t.id = "20260101-000000-dead".to_owned();
9084 queue.put(&mut t).unwrap();
9085 let dead_pid = injected_dead_pid();
9086
9087 std::fs::write(
9092 dir.path().join(format!("{}.lock", t.id)),
9093 dead_pid.to_string(),
9094 )
9095 .unwrap();
9096
9097 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
9098 pid != dead_pid
9099 });
9100 assert_eq!(
9101 swept,
9102 vec![t.id.clone()],
9103 "a dead owner is reclaimed immediately, not after STALE_CLAIM"
9104 );
9105 assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
9106 }
9107
9108 #[test]
9109 fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
9110 let dir = tempfile::tempdir().unwrap();
9111 let queue = Queue::at(dir.path().to_path_buf());
9112 let mut t = task();
9113 t.id = "20260101-000000-late".to_owned();
9114 queue.put(&mut t).unwrap();
9115 let dead_pid = injected_dead_pid();
9116
9117 assert!(
9120 sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
9121 "nothing has claimed the task yet"
9122 );
9123
9124 std::fs::write(
9127 dir.path().join(format!("{}.lock", t.id)),
9128 dead_pid.to_string(),
9129 )
9130 .unwrap();
9131
9132 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
9136 pid != dead_pid
9137 });
9138 assert_eq!(swept, vec![t.id.clone()]);
9139 }
9140
9141 #[test]
9142 fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
9143 crate::run::pin_test_home();
9148 let dir = tempfile::tempdir().unwrap();
9149 let queue = Queue::at(dir.path().to_path_buf());
9150 let mut t = task();
9151 t.id = "20260101-000000-crsh".to_owned();
9152 t.status = TaskStatus::Running;
9153 t.attempts = 1;
9154 t.runs.push("20260904-000000-4043".to_owned());
9158 queue.put(&mut t).unwrap();
9159 let dead_pid = injected_dead_pid();
9160
9161 std::fs::write(
9164 dir.path().join(format!("{}.lock", t.id)),
9165 dead_pid.to_string(),
9166 )
9167 .unwrap();
9168
9169 assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
9175 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
9176
9177 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
9178 pid != dead_pid
9179 });
9180 assert_eq!(swept, vec![t.id.clone()]);
9181
9182 let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
9183 assert_eq!(reclaimed, vec![t.id.clone()]);
9184 let after = queue.get(&t.id).unwrap();
9185 assert_eq!(
9186 after.status,
9187 TaskStatus::Held,
9188 "no run.json to recover from, so a human is asked"
9189 );
9190 assert_eq!(
9191 after.runs,
9192 vec!["20260904-000000-4043".to_owned()],
9193 "the crashed run's id is kept as evidence, not discarded"
9194 );
9195 }
9196
9197 #[test]
9198 fn a_lock_is_kept_when_the_process_query_is_unavailable() {
9199 let dir = tempfile::tempdir().unwrap();
9200 let queue = Queue::at(dir.path().to_path_buf());
9201 let mut t = task();
9202 t.id = "20260101-000000-unknown".to_owned();
9203 queue.put(&mut t).unwrap();
9204 let dead_pid = injected_dead_pid();
9205 std::fs::write(
9206 dir.path().join(format!("{}.lock", t.id)),
9207 dead_pid.to_string(),
9208 )
9209 .unwrap();
9210
9211 let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
9212 assert!(swept.is_empty(), "an unknown pid must keep its lock");
9213 assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
9214 }
9215
9216 fn run_state_in(status: RunStatus, language: &str) -> RunState {
9217 let mut s = run_state(status);
9218 s.config.graph.language = language.to_owned();
9219 s
9220 }
9221
9222 fn unstarted_verdict(status: RunStatus) -> Verdict {
9223 Verdict {
9224 status,
9225 left_pr: false,
9226 quota_hit: false,
9227 parked: false,
9228 no_viable_candidates: false,
9229 }
9230 }
9231
9232 #[test]
9233 fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
9234 let mut t = task();
9235 t.attempts = 1;
9236 settle_in(
9237 &mut t,
9238 unstarted_verdict(RunStatus::AlreadyInBase),
9239 "already in main",
9240 1,
9241 phrases("en"),
9242 None,
9243 );
9244 assert_eq!(t.status, TaskStatus::Done);
9245 assert_eq!(t.attempts, 0);
9246 }
9247
9248 #[test]
9249 fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
9250 let reason = |language: &str| {
9251 let mut t = task();
9252 settle_in(
9253 &mut t,
9254 unstarted_verdict(RunStatus::Judging),
9255 "boom",
9256 1,
9257 phrases(language),
9258 None,
9259 );
9260 t.last_error.or(t.hold_reason).unwrap_or_default()
9261 };
9262 assert!(
9263 reason("en").starts_with("the graph stopped at `"),
9264 "{}",
9265 reason("en")
9266 );
9267 assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
9268 assert!(reason("日本語").contains("boom"));
9269 assert_eq!(reason("fr"), reason("en"));
9270 }
9271
9272 #[test]
9273 fn describe_follows_the_run_language_and_keeps_the_run_id() {
9274 let en = describe(&run_state_in(RunStatus::Stalled, "en"));
9275 assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
9276 let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
9277 assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
9278 assert!(ja.contains("[run "), "{ja}");
9279 let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
9280 assert!(ended.starts_with("run 終了: "), "{ended}");
9281 let mut de = run_state_in(RunStatus::Failed, "de");
9282 let mut en = run_state_in(RunStatus::Failed, "en");
9283 de.id = "same".to_owned();
9284 en.id = "same".to_owned();
9285 assert_eq!(describe(&de), describe(&en));
9286 }
9287
9288 #[test]
9289 fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
9290 use crate::handover::Refused;
9291 let cases = [
9292 Refused::Foreign {
9293 branch: "b".into(),
9294 path: "/w/x".into(),
9295 why: "made by hand".into(),
9296 },
9297 Refused::Unsafe {
9298 branch: "b".into(),
9299 path: "/w/x".into(),
9300 why: "its worktree has uncommitted changes (a.rs)".into(),
9301 },
9302 Refused::ReleaseFailed {
9303 branch: "b".into(),
9304 path: "/w/x".into(),
9305 run: "ab12".into(),
9306 },
9307 ];
9308 for r in &cases {
9309 let en = (phrases("en").handover_refused)(r);
9310 assert_eq!(en, r.to_string());
9311 let ja = (phrases("ja").handover_refused)(r);
9312 assert!(
9313 !ja.contains("is checked out") && !ja.contains("try again"),
9314 "{ja}"
9315 );
9316 assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
9317 if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
9318 assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
9319 }
9320 }
9321 assert!(phrases("en").handover_hint.contains("release the task"));
9322 assert!(phrases("ja").handover_hint.contains("解放"));
9323 }
9324
9325 #[test]
9326 fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
9327 let build = |lang: &str| {
9328 let mut s = run_state_in(RunStatus::Blocked, lang);
9329 s.id = "same".to_owned();
9330 s.config.graph.review_rounds = 3;
9331 let mut r = review_round(3);
9332 r.expected = 3;
9333 r.answered = 1;
9334 s.reviews.push(r);
9335 s.event(
9336 "review",
9337 "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
9338 );
9339 s
9340 };
9341 let en = describe(&build("en"));
9342 assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
9343 let ja = describe(&build("ja"));
9344 assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
9345 assert!(!ja.contains("never answered"), "{ja}");
9346 assert!(ja.contains("[run "), "{ja}");
9347
9348 let mut failed = build("ja");
9351 failed.reviews[0].e2e.push(crate::run::CommandOutcome {
9352 command: "cargo test".to_owned(),
9353 code: Some(1),
9354 output_tail: String::new(),
9355 duration_ms: 0,
9356 resource_blocked: false,
9357 });
9358 failed.event("review", "stopped; e2e failed: cargo test");
9359 let ja = describe(&failed);
9360 assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
9361 assert!(!ja.contains("席のレビュアー"), "{ja}");
9362 }
9363
9364 #[test]
9365 fn refusals_and_recovery_prose_follow_the_language() {
9366 let home = crate::run::test_home();
9367 let t = held_task_with("r1");
9368 let q = action_question(
9369 "r1",
9370 ask::ChoiceAction::Resume {
9371 run: "r1".to_owned(),
9372 },
9373 );
9374 let refuse = |p: &Phrases| match decide_action(&home, &t, &q, p, |_: &str| bail!("gone")) {
9375 ActionDecision::Refuse(s) => s,
9376 other => panic!("{other:?}"),
9377 };
9378 assert!(refuse(phrases("en")).contains("could not be read: gone"));
9379 assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
9380 assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
9381
9382 let mut held = task();
9383 reclaim(&mut held, None, 2, "ja");
9384 assert!(held.hold_reason.unwrap().contains("保留にしました"));
9385 let mut held = task();
9386 reclaim(&mut held, None, 2, "xx");
9387 assert!(held.hold_reason.unwrap().contains("held for a human"));
9388 }
9389
9390 fn run_state(status: RunStatus) -> RunState {
9391 let mut state = RunState::new(
9392 PathBuf::from("/repo"),
9393 "main".to_owned(),
9394 "abc1234def".to_owned(),
9395 "add retries".to_owned(),
9396 Config::default(),
9397 );
9398 state.status = status;
9399 state
9400 }
9401
9402 #[test]
9403 fn settlement_audits_the_loaded_run_instead_of_reloading_a_stale_snapshot() {
9404 crate::run::pin_test_home();
9405 let dir = tempfile::tempdir().unwrap();
9406 let mut state = run_state(RunStatus::Blocked);
9407 state.id = "20260101-000000-audit".into();
9408 state.save_under(dir.path()).unwrap();
9409 let mut t = task();
9410 t.start(state.id.clone());
9411 state.status = RunStatus::Ready;
9414 settle_and_diagnose(
9415 &mut t,
9416 unstarted_verdict(RunStatus::Ready),
9417 "Verified local delivery",
9418 2,
9419 &state,
9420 );
9421 let completion = t.completion_history.last().unwrap();
9422 assert_eq!(completion.actor, CompletionActor::DaemonSettle);
9423 assert_eq!(completion.prior_status, TaskStatus::Running);
9424 assert_eq!(
9425 completion.reason.as_deref(),
9426 Some("Verified local delivery")
9427 );
9428 let snapshot = completion.run.as_ref().unwrap();
9429 assert_eq!(snapshot.id, state.id);
9430 assert_eq!(snapshot.status, Some(RunStatus::Ready));
9431 assert_eq!(
9432 RunState::load_under(&state.id, dir.path()).unwrap().status,
9433 RunStatus::Blocked,
9434 "settlement records the actual outcome without rewriting run history"
9435 );
9436 }
9437
9438 fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
9439 Candidate {
9440 index: 0,
9441 label,
9442 agent: "claude".to_owned(),
9443 branch: format!("magi/x/{label}"),
9444 worktree: PathBuf::from("/repo"),
9445 summary: summary.to_owned(),
9446 stat: String::new(),
9447 files: 0,
9448 commits: usize::from(!empty),
9449 empty,
9450 failed: failed.map(str::to_owned),
9451 verified_noop: None,
9452 duration_ms: 0,
9453 folded: false,
9454 }
9455 }
9456
9457 #[test]
9458 fn diagnostic_names_the_failing_gate_checks_and_their_output() {
9459 let mut state = run_state(RunStatus::Blocked);
9460 state.gate = vec![
9461 CommandOutcome {
9462 command: "cargo make check".to_owned(),
9463 code: Some(0),
9464 output_tail: "ok".to_owned(),
9465 duration_ms: 0,
9466 resource_blocked: false,
9467 },
9468 CommandOutcome {
9469 command: "cargo test".to_owned(),
9470 code: Some(101),
9471 output_tail: "thread 'x' panicked: assertion failed".to_owned(),
9472 duration_ms: 0,
9473 resource_blocked: false,
9474 },
9475 ];
9476 let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
9477 assert!(d.contains("cargo test"), "{d}");
9478 assert!(
9479 !d.contains("cargo make check"),
9480 "a passing check is not a diagnostic: {d}"
9481 );
9482 assert!(d.contains("assertion failed"), "{d}");
9483 }
9484
9485 #[test]
9486 fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
9487 let mut state = run_state(RunStatus::Blocked);
9488 state.event(
9489 "land",
9490 "stopped: the fixer produced no commit while 2 check(s) were failing \
9491 (build, lint); stopping instead of looping on an unchanged tree",
9492 );
9493 let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
9494 assert!(d.contains("build"), "{d}");
9495 assert!(d.contains("lint"), "{d}");
9496 assert!(d.contains("fixer produced no commit"), "{d}");
9497 }
9498
9499 #[test]
9500 fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
9501 let state = run_state(RunStatus::VerifiedNoop);
9506 let d = describe(&state);
9507 assert!(
9508 d.contains("agent-verified no-op"),
9509 "expected the display label, not the wire spelling: {d}"
9510 );
9511 assert!(!d.contains("verified_noop"), "{d}");
9512 }
9513
9514 #[test]
9515 fn diagnostic_keeps_gate_panic_before_large_backtrace() {
9516 let mut state = run_state(RunStatus::Failed);
9517 state.gate.push(crate::run::CommandOutcome {
9518 command: "cargo test".into(),
9519 code: Some(101),
9520 output_tail: format!(
9521 "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
9522 " 41: 0x1234 - backtrace frame\n".repeat(10000)
9523 ),
9524 duration_ms: 1,
9525 resource_blocked: false,
9526 });
9527 let d = diagnostic(&state).unwrap();
9528 assert!(d.contains("panicked at widget.rs:12"), "{d}");
9529 assert!(d.contains("assertion failed: widget missing"));
9530 assert!(d.contains("widget log"));
9531 }
9532
9533 #[test]
9534 fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
9535 let mut state = run_state(RunStatus::Failed);
9541 state.candidates = vec![candidate(
9542 'A',
9543 "opened pull request #42, merged it, tagged v1.2.3 and published the release",
9544 true,
9545 None,
9546 )];
9547 let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
9548 assert!(d.contains("candidate A"), "{d}");
9549 assert!(d.contains("tagged v1.2.3"), "{d}");
9550 }
9551
9552 #[test]
9553 fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
9554 let mut state = run_state(RunStatus::Failed);
9555 state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
9556 let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
9557 assert!(d.contains("candidate A"), "{d}");
9558 assert!(d.contains("agent timed out"), "{d}");
9559 }
9560
9561 #[test]
9562 fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
9563 let mut state = run_state(RunStatus::Failed);
9566 state.candidates = vec![candidate('A', "did the work", false, None)];
9567 assert!(diagnostic(&state).is_none());
9568 }
9569
9570 #[test]
9571 fn diagnostic_is_bounded_however_much_a_run_printed() {
9572 let mut state = run_state(RunStatus::Blocked);
9573 state.gate = vec![
9574 CommandOutcome {
9575 command: "cargo test".to_owned(),
9576 code: Some(101),
9577 output_tail: "x".repeat(50_000),
9578 duration_ms: 0,
9579 resource_blocked: false,
9580 },
9581 CommandOutcome {
9582 command: "cargo clippy".to_owned(),
9583 code: Some(1),
9584 output_tail: "y".repeat(50_000),
9585 duration_ms: 0,
9586 resource_blocked: false,
9587 },
9588 ];
9589 state.candidates = vec![
9590 candidate('A', &"z".repeat(50_000), true, None),
9591 candidate('B', &"w".repeat(50_000), true, None),
9592 ];
9593 let d = diagnostic(&state).expect("plenty here to diagnose");
9594 assert!(
9595 d.len() <= DIAGNOSTIC_MAX,
9596 "diagnostic grew to {} bytes, unbounded",
9597 d.len()
9598 );
9599 }
9600
9601 #[test]
9602 fn selected_delivery_guards_survive_recovery_failure_accounting() {
9603 for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
9604 let mut t = task();
9605 let mut state = run_state(status);
9606 t.pr_recovery = Some(crate::pr_recovery::Selection {
9607 url: "url".into(),
9608 branch: format!("magi/task-{}", t.id),
9609 head: "a".repeat(40),
9610 source_head: None,
9611 source_run: None,
9612 source_proof: None,
9613 disposition: Some(crate::pr_recovery::Disposition::Land),
9614 instruction: t.instruction.clone(),
9615 approved_at: Timestamp::now(),
9616 });
9617 state.pr_recovery = t.pr_recovery.clone();
9618 t.start(state.id.clone());
9619 settle_and_diagnose(
9620 &mut t,
9621 Verdict {
9622 status,
9623 left_pr: false,
9624 quota_hit: false,
9625 parked: false,
9626 no_viable_candidates: false,
9627 },
9628 "delivery stopped",
9629 5,
9630 &state,
9631 );
9632 assert_eq!(t.status, TaskStatus::Held);
9633 let reason = t.hold_reason.as_deref().unwrap();
9634 if status == RunStatus::Ready {
9635 assert!(reason.contains("Selected PR delivery is incomplete"));
9636 assert!(t.recovery_budget.is_none());
9637 } else {
9638 assert!(reason.contains("Selected recovery stopped"));
9639 assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
9640 }
9641 assert!(t.pr_recovery.is_some());
9642 }
9643 }
9644
9645 #[test]
9646 fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
9647 let mut state = run_state(RunStatus::Voting);
9648 state.base_sync = Some(crate::run::BaseSync {
9649 tip: "base-tip".into(),
9650 behind: 3,
9651 attempts: 4,
9652 conflict: Some("base stopped".into()),
9653 already_in: None,
9654 });
9655 state.record_base_sync_stop("candidate-head");
9656 let mut t = task();
9657 t.start(state.id.clone());
9658 let verdict = Verdict {
9659 status: RunStatus::Blocked,
9660 left_pr: false,
9661 quota_hit: false,
9662 parked: false,
9663 no_viable_candidates: false,
9664 };
9665 settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
9666 assert_eq!(
9667 t.status,
9668 TaskStatus::Held,
9669 "unspent task attempts cannot start another competition"
9670 );
9671 let at = t.held_at;
9672 let cause = t.hold_notice_cause.clone();
9673 state.begin_pass();
9674 t.release_operator("test-resume", None);
9675 t.start(state.id.clone());
9676 settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
9677 assert_eq!(t.status, TaskStatus::Held);
9678 assert_eq!(t.held_at, at);
9679 assert_eq!(t.hold_notice_cause, cause);
9680 }
9681
9682 #[test]
9683 fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
9684 let mut state = run_state(RunStatus::Blocked);
9685 state.gate = vec![CommandOutcome {
9686 command: "cargo test".to_owned(),
9687 code: Some(101),
9688 output_tail: "assertion failed".to_owned(),
9689 duration_ms: 0,
9690 resource_blocked: false,
9691 }];
9692 let verdict = Verdict {
9693 status: RunStatus::Blocked,
9694 left_pr: false,
9695 quota_hit: false,
9696 parked: false,
9697 no_viable_candidates: false,
9698 };
9699
9700 let mut t = task();
9703 t.start("run-1".to_owned());
9704 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
9705 assert_eq!(t.status, TaskStatus::Failed);
9706 assert!(t.diagnostic.is_none());
9707
9708 t.start("run-2".to_owned());
9711 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
9712 assert_eq!(t.status, TaskStatus::Held);
9713 let d = t.diagnostic.expect("a held task must carry its diagnostic");
9714 assert!(d.contains("cargo test"), "{d}");
9715 }
9716
9717 #[test]
9718 fn a_held_task_names_the_open_question_it_is_waiting_on() {
9719 crate::run::pin_test_home();
9724 let home = crate::run::home();
9725 let state = run_state(RunStatus::VerifiedNoop);
9726 let mut q = ask::Question::new(
9727 state.id.clone(),
9728 "implement".to_owned(),
9729 "impl-A".to_owned(),
9730 "is this really a no-op?".to_owned(),
9731 String::new(),
9732 Vec::new(),
9733 );
9734 Questions::at(home.join("questions")).put(&mut q).unwrap();
9735
9736 let verdict = Verdict {
9737 status: RunStatus::VerifiedNoop,
9738 left_pr: false,
9739 quota_hit: false,
9740 parked: false,
9741 no_viable_candidates: false,
9742 };
9743 let mut t = task();
9744 t.start(state.id.clone());
9745 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
9746
9747 assert_eq!(t.status, TaskStatus::Held);
9748 let reason = t.hold_reason.expect("a held task must record why");
9749 assert!(
9750 reason.starts_with("run ended agent-verified no-op"),
9751 "the original settle reason must survive unchanged: {reason}"
9752 );
9753 assert!(
9754 reason.contains(q.short()),
9755 "the open question's id must be named so the notice is actionable: {reason}"
9756 );
9757 }
9758
9759 #[test]
9760 fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
9761 crate::run::pin_test_home();
9762 let state = run_state(RunStatus::VerifiedNoop);
9763
9764 let verdict = Verdict {
9765 status: RunStatus::VerifiedNoop,
9766 left_pr: false,
9767 quota_hit: false,
9768 parked: false,
9769 no_viable_candidates: false,
9770 };
9771 let mut t = task();
9772 t.start(state.id.clone());
9773 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
9774
9775 assert_eq!(t.status, TaskStatus::Held);
9776 assert_eq!(
9777 t.hold_reason.as_deref(),
9778 Some("run ended agent-verified no-op"),
9779 "nothing to append when the question was already answered or never asked"
9780 );
9781 }
9782
9783 #[test]
9784 fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
9785 crate::run::pin_test_home();
9786 let mut first = run_state(RunStatus::Blocked);
9787 first.id = "20260101-000000-sup1".to_owned();
9788 first.save().unwrap();
9789 let mut second = run_state(RunStatus::Merged);
9790 second.id = "20260101-000000-sup2".to_owned();
9791 second.save().unwrap();
9792
9793 let mut t = task();
9794 t.runs = vec![first.id.clone(), second.id.clone()];
9795 t.status = TaskStatus::Done;
9796
9797 supersede_prior_runs(&t, &crate::run::home());
9798
9799 assert_eq!(
9800 RunState::load(&first.id).unwrap().status,
9801 RunStatus::Superseded,
9802 "the first attempt's Blocked no longer needs anyone's attention"
9803 );
9804 assert_eq!(
9805 RunState::load(&second.id).unwrap().status,
9806 RunStatus::Merged,
9807 "the run that actually succeeded is left exactly as it was"
9808 );
9809 }
9810
9811 #[test]
9812 fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
9813 crate::run::pin_test_home();
9819 let mut first = run_state(RunStatus::Blocked);
9820 first.id = "20260101-000000-sup9".to_owned();
9821 first.driver_pid = Some(std::process::id());
9824 first.driver_started_at = Some(
9825 crate::proc::process_started_at(std::process::id())
9826 .expect("this test process's own start time must be queryable"),
9827 );
9828 first.save().unwrap();
9829 let mut second = run_state(RunStatus::Merged);
9830 second.id = "20260101-000000-supa".to_owned();
9831 second.save().unwrap();
9832
9833 let mut t = task();
9834 t.runs = vec![first.id.clone(), second.id.clone()];
9835 t.status = TaskStatus::Done;
9836
9837 supersede_prior_runs(&t, &crate::run::home());
9838
9839 assert_eq!(
9840 RunState::load(&first.id).unwrap().status,
9841 RunStatus::Blocked,
9842 "a live driver_pid means something is still actually working this run, \
9843 even though no daemon claims it - rewriting under it would just be \
9844 undone the next time that process saves"
9845 );
9846 }
9847
9848 #[test]
9849 fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
9850 let dir = tempfile::tempdir().unwrap();
9856 let home = dir.path().to_path_buf();
9857 let queue = Queue::at(dir.path().join("queue"));
9858
9859 let mut first = run_state(RunStatus::Blocked);
9860 first.id = "20260101-000000-supd".to_owned();
9861 first.driver_pid = Some(std::process::id());
9862 first.driver_started_at = Some(
9863 crate::proc::process_started_at(std::process::id())
9864 .expect("this test process's own start time must be queryable"),
9865 );
9866 first.save_under(&home).unwrap();
9867 let mut second = run_state(RunStatus::Merged);
9868 second.id = "20260101-000000-supe".to_owned();
9869 second.save_under(&home).unwrap();
9870
9871 let mut t = task();
9872 t.runs = vec![first.id.clone(), second.id.clone()];
9873 t.status = TaskStatus::Done;
9874 queue.put(&mut t).unwrap();
9875
9876 resweep_superseded_attempts(&queue, &home);
9877 assert_eq!(
9878 RunState::load_under(&first.id, &home).unwrap().status,
9879 RunStatus::Blocked,
9880 "still live on the first pass, so still untouched"
9881 );
9882
9883 let mut stale = RunState::load_under(&first.id, &home).unwrap();
9889 stale.driver_started_at = Some("1".to_owned());
9890 stale.save_under(&home).unwrap();
9891
9892 resweep_superseded_attempts(&queue, &home);
9893 assert_eq!(
9894 RunState::load_under(&first.id, &home).unwrap().status,
9895 RunStatus::Superseded,
9896 "the second pass catches up what the first one correctly skipped"
9897 );
9898 }
9899
9900 #[test]
9901 fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
9902 crate::run::pin_test_home();
9903 let mut first = run_state(RunStatus::Blocked);
9904 first.id = "20260101-000000-sup3".to_owned();
9905 first.save().unwrap();
9906 let mut second = run_state(RunStatus::Blocked);
9907 second.id = "20260101-000000-sup4".to_owned();
9908 second.save().unwrap();
9909
9910 let mut t = task();
9911 t.runs = vec![first.id.clone(), second.id.clone()];
9912 t.status = TaskStatus::Failed;
9916
9917 supersede_prior_runs(&t, &crate::run::home());
9918
9919 assert_eq!(
9920 RunState::load(&first.id).unwrap().status,
9921 RunStatus::Blocked
9922 );
9923 assert_eq!(
9924 RunState::load(&second.id).unwrap().status,
9925 RunStatus::Blocked
9926 );
9927 }
9928
9929 #[test]
9930 fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
9931 crate::run::pin_test_home();
9935 let mut first = run_state(RunStatus::Blocked);
9936 first.id = "20260101-000000-sup5".to_owned();
9937 first.save().unwrap();
9938
9939 let mut t = task();
9940 t.runs = vec![first.id.clone()];
9941 t.status = TaskStatus::Done;
9942
9943 supersede_prior_runs(&t, &crate::run::home());
9944
9945 assert_eq!(
9946 RunState::load(&first.id).unwrap().status,
9947 RunStatus::Blocked,
9948 "a single-attempt task has no earlier run to supersede"
9949 );
9950 }
9951
9952 #[test]
9953 fn supersede_prior_runs_preserves_blocked_work_after_an_audited_manual_close() {
9954 for status in [
9955 RunStatus::Blocked,
9956 RunStatus::Stalled,
9957 RunStatus::Failed,
9958 RunStatus::Ready,
9959 RunStatus::Merged,
9960 ] {
9961 let dir = tempfile::tempdir().unwrap();
9962 let home = dir.path();
9963 let mut first = run_state(RunStatus::Blocked);
9964 first.id = "20260101-000000-supb".to_owned();
9965 first.save_under(home).unwrap();
9966 let mut second = run_state(status);
9967 second.id = "20260101-000000-supc".to_owned();
9968 second.save_under(home).unwrap();
9969
9970 let mut t = task();
9971 t.runs = vec![first.id.clone(), second.id.clone()];
9972 t.hold_manual(Some("Unmerged work remains".into()));
9973 let mut context = CompletionContext::new(
9974 CompletionActor::Cli,
9975 Some("Discard the unmerged attempts".into()),
9976 home,
9977 &t,
9978 );
9979 context.discard = true;
9980 t.succeed(context);
9981 assert_eq!(t.completion_history.len(), 1);
9982
9983 supersede_prior_runs(&t, home);
9984
9985 assert_eq!(
9986 RunState::load_under(&first.id, home).unwrap().status,
9987 RunStatus::Blocked,
9988 "an audited manual close is not proof the earlier work landed"
9989 );
9990 assert_eq!(
9991 RunState::load_under(&second.id, home).unwrap().status,
9992 status,
9993 "the latest attempt retains its actual outcome"
9994 );
9995 }
9996 }
9997
9998 #[test]
9999 fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
10000 crate::run::pin_test_home();
10004 let mut failed = run_state(RunStatus::Failed);
10005 failed.id = "20260101-000000-sup6".to_owned();
10006 failed.save().unwrap();
10007 let mut noop = run_state(RunStatus::VerifiedNoop);
10008 noop.id = "20260101-000000-sup7".to_owned();
10009 noop.save().unwrap();
10010 let mut winner = run_state(RunStatus::Ready);
10011 winner.id = "20260101-000000-sup8".to_owned();
10012 winner.save().unwrap();
10013
10014 let mut t = task();
10015 t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
10016 t.status = TaskStatus::Done;
10017
10018 supersede_prior_runs(&t, &crate::run::home());
10019
10020 assert_eq!(
10021 RunState::load(&failed.id).unwrap().status,
10022 RunStatus::Failed
10023 );
10024 assert_eq!(
10025 RunState::load(&noop.id).unwrap().status,
10026 RunStatus::VerifiedNoop
10027 );
10028 }
10029
10030 fn approval_question(run: &str) -> ask::Question {
10031 ask::Question::new(
10032 run.to_owned(),
10033 land::APPROVAL_NODE.to_owned(),
10034 "land".to_owned(),
10035 "merge?".to_owned(),
10036 String::new(),
10037 vec!["merge".to_owned(), "hold".to_owned()],
10038 )
10039 }
10040
10041 #[test]
10042 fn land_resume_state_leaves_a_fresh_open_question_waiting() {
10043 crate::run::pin_test_home();
10044 let mut state = run_state(RunStatus::Landing);
10045 state.id = "20260101-000000-fre1".to_owned();
10046 state.parked = true;
10047 state.save().unwrap();
10048 ask::Questions::open()
10049 .put(&mut approval_question(&state.id))
10050 .unwrap();
10051
10052 let mut t = task();
10053 t.runs.push(state.id.clone());
10054 assert_eq!(
10055 land_resume_state(&t),
10056 LandResume::StillWaiting,
10057 "nobody has answered and the timeout has not passed"
10058 );
10059 }
10060
10061 #[test]
10062 fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
10063 crate::run::pin_test_home();
10064 let mut state = run_state(RunStatus::Gating);
10065 state.id = "20260101-000000-gt01".to_owned();
10066 state.parked = true;
10067 state.config.graph.answer_timeout = 60;
10068 state.github_text = Some(crate::run::GithubTextAsk {
10069 rewrite: None,
10070 fingerprint: "f".into(),
10071 title: true,
10072 body: false,
10073 categories: vec!["title-language".into()],
10074 question: None,
10075 asks: 1,
10076 resolved: false,
10077 chosen_title: None,
10078 choice: None,
10079 publication: None,
10080 });
10081 state.save().unwrap();
10082 let store = ask::Questions::open();
10083 let mut q = ask::Question::new(
10084 state.id.clone(),
10085 crate::github_text::ASK_NODE.to_owned(),
10086 crate::github_text::ASK_SEAT.to_owned(),
10087 "s".into(),
10088 String::new(),
10089 vec!["use fallback".into()],
10090 );
10091 store.put(&mut q).unwrap();
10092 let mut t = task();
10093 t.runs.push(state.id.clone());
10094 assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
10095 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
10096 store.put(&mut q).unwrap();
10097 assert_eq!(land_resume_state(&t), LandResume::Ready);
10098 assert!(!store.get(&q.id).unwrap().status.open());
10099 state.github_text.as_mut().unwrap().resolved = true;
10101 state.save().unwrap();
10102 assert_eq!(land_resume_state(&t), LandResume::NotLanding);
10103 }
10104
10105 #[test]
10106 fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
10107 crate::run::pin_test_home();
10112 let mut state = run_state(RunStatus::Landing);
10113 state.id = "20260101-000000-exp1".to_owned();
10114 state.parked = true;
10115 state.config.graph.answer_timeout = 60;
10116 state.save().unwrap();
10117
10118 let store = ask::Questions::open();
10119 let mut q = approval_question(&state.id);
10120 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
10121 store.put(&mut q).unwrap();
10122
10123 let mut t = task();
10124 t.runs.push(state.id.clone());
10125 assert_eq!(
10126 land_resume_state(&t),
10127 LandResume::Ready,
10128 "an expired question must not be waited on forever"
10129 );
10130
10131 let after = store.get(&q.id).unwrap();
10132 assert!(
10133 !after.status.open(),
10134 "the question is abandoned, not silently ignored"
10135 );
10136 assert!(
10137 after.resolution().is_none(),
10138 "an abandoned question is not read as a decision"
10139 );
10140 }
10141
10142 #[test]
10143 fn reclaim_settles_a_running_task_against_its_last_run() {
10144 let mut t = task();
10145 t.start("20260904-000000-4043".to_owned());
10146 reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
10147 assert_eq!(
10148 t.status,
10149 TaskStatus::Done,
10150 "a run that actually finished must not stay `running` forever"
10151 );
10152 }
10153
10154 #[test]
10155 fn reclaim_preserves_dispatched_inquiries_until_a_committed_pass() {
10156 let dir = tempfile::tempdir().unwrap();
10157 let queue = Queue::at(dir.path().join("queue"));
10158 let mut task = task();
10159 let mut run = run_state(RunStatus::Blocked);
10160 run.reserve_under(dir.path()).unwrap();
10161 run.driver_exited = true;
10162 run.save_under(dir.path()).unwrap();
10163 queue.put(&mut task).unwrap();
10164 let stale = task.clone();
10165 task.resume_override = Some(crate::queue::OperatorResume {
10166 question_id: "pending-resume".into(),
10167 at: Timestamp::now(),
10168 conductor_rehold: None,
10169 forced: true,
10170 pinned_run: Some(run.id.clone()),
10171 });
10172 task.start(run.id.clone());
10173 queue.put(&mut task).unwrap();
10174 let mut recovered = queue.get(&task.id).unwrap();
10176 let disk = RunState::load_under(&run.id, dir.path()).unwrap();
10177 reclaim(&mut recovered, Some(disk), 2, "en");
10178 queue.put(&mut recovered).unwrap();
10179 assert!(recovered.resume_override.is_none());
10180 assert_eq!(
10181 recovered.dispatched_resumes.get("pending-resume"),
10182 Some(&run.id)
10183 );
10184 let mut stale = stale;
10185 queue.put(&mut stale).unwrap();
10186 assert_eq!(
10187 stale.dispatched_resumes, recovered.dispatched_resumes,
10188 "a stale task writer cannot erase dispatch ownership"
10189 );
10190 let mut resumed = RunState::load_under(&run.id, dir.path()).unwrap();
10191 assert!(resumed.decision_starts.is_empty());
10192 resumed.carry_dispatched_resumes(&queue.get(&task.id).unwrap());
10193 assert!(
10194 resumed.decision_starts.is_empty(),
10195 "handoff is not execution proof"
10196 );
10197 resumed.begin_pass();
10198 resumed.save_under(dir.path()).unwrap();
10199 let mut disk = RunState::load_under(&run.id, dir.path()).unwrap();
10200 assert_eq!(disk.decision_starts.get("pending-resume"), Some(&0));
10201 disk.carry_dispatched_resumes(&recovered);
10202 disk.begin_pass();
10203 assert_eq!(
10204 disk.decision_starts.get("pending-resume"),
10205 Some(&0),
10206 "later execution must preserve the original pass receipt"
10207 );
10208 }
10209
10210 #[test]
10211 fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
10212 let mut t = task();
10213 t.start("20260904-000000-4043".to_owned());
10214 t.last_error = Some("earlier trouble".to_owned());
10215 let mut state = run_state(RunStatus::Judging);
10216 state.parked = true;
10217 reclaim(&mut t, Some(state), 1, "en");
10218 assert_eq!(t.status, TaskStatus::Parked);
10219 assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
10220 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
10221 assert!(t.park_reason.is_some());
10222 assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
10223 assert!(!t.fresh_start);
10224 assert!(t.status.runnable());
10225 }
10226
10227 #[test]
10228 fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
10229 let mut t = task();
10230 t.start("20260904-000000-4043".to_owned());
10231 t.last_error = Some("earlier trouble".to_owned());
10232 settle(
10233 &mut t,
10234 Verdict {
10235 status: RunStatus::Judging,
10236 left_pr: false,
10237 quota_hit: false,
10238 parked: true,
10239 no_viable_candidates: false,
10240 },
10241 "parked after `judging`",
10242 1,
10243 );
10244 assert_eq!(t.status, TaskStatus::Parked);
10245 assert_eq!(t.attempts, 0);
10246 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
10247 assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
10248 assert_eq!(t.schema, crate::queue::SCHEMA);
10249 assert!(
10250 crate::notices::task_held(&t).is_none(),
10251 "a park is not news"
10252 );
10253 t.start("20260904-000000-4043".to_owned());
10254 assert_eq!(t.park_reason, None);
10255 }
10256
10257 #[test]
10258 fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
10259 let mut t = task();
10263 t.start("20260904-000000-4043".to_owned());
10264 reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
10265 assert_eq!(t.status, TaskStatus::Failed);
10266 assert!(t.status.runnable());
10267 }
10268
10269 #[test]
10270 fn a_settled_parked_pass_records_its_cause_and_the_refund() {
10271 let mut t = task();
10272 t.start("20260904-000000-4043".to_owned());
10273 assert_eq!(t.attempts, 1);
10274 let mut run = run_state(RunStatus::Implementing);
10275 run.id = "20260904-000000-4043".to_owned();
10276 run.begin_pass();
10277 let cause = crate::run::ParkCause::Upgrade {
10278 from: "0.121.0".to_owned(),
10279 to: Some("0.121.1".to_owned()),
10280 };
10281 run.end_pass_parked(cause.clone());
10282 run.parked = true;
10283 let verdict = Verdict {
10284 status: run.status,
10285 left_pr: false,
10286 quota_hit: false,
10287 parked: true,
10288 no_viable_candidates: false,
10289 };
10290 let mut orphan = t.clone();
10293 reclaim(&mut orphan, Some(run.clone()), 2, "en");
10294 assert_eq!(orphan.status, TaskStatus::Parked);
10295 assert_eq!(orphan.attempts, 0);
10296 assert_eq!(
10297 orphan.upgrade_resume_key(),
10298 Some((run.passes[0].started_at, orphan.id.as_str()))
10299 );
10300 settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
10301 assert_eq!(t.attempts, 0);
10302 assert_eq!(t.passes.len(), 1);
10303 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
10304 assert_eq!(t.passes[0].parked, Some(cause));
10305 assert_eq!(t.passes[0].pass_index, 0);
10306 assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
10307 assert!(t.upgrade_resume_key().is_some());
10308
10309 t.start("20260904-000000-4043".to_owned());
10312 run.begin_pass();
10313 run.status = RunStatus::Failed;
10314 let verdict = Verdict {
10315 status: RunStatus::Failed,
10316 left_pr: false,
10317 quota_hit: false,
10318 parked: false,
10319 no_viable_candidates: false,
10320 };
10321 settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
10322 assert_eq!(t.passes.len(), 2);
10323 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
10324 assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
10325 assert_eq!(t.passes[1].pass_index, 1);
10326 assert_eq!(t.attempts, 1);
10327 }
10328
10329 #[test]
10330 fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
10331 let mut t = task();
10332 t.start("20260904-000000-4043".to_owned());
10333 reclaim(&mut t, None, 2, "en");
10334 assert_eq!(t.status, TaskStatus::Held);
10335 assert!(
10336 t.last_error
10337 .as_deref()
10338 .is_some_and(|e| e.contains("running")),
10339 "the operator needs to know why this task was held"
10340 );
10341 }
10342
10343 #[test]
10344 fn sync_base_only_orphan_holds_without_replay_or_attempt_change() {
10345 let dir = tempfile::tempdir().unwrap();
10346 let queue = Queue::at(dir.path().to_path_buf());
10347 let mut task = task();
10348 let run = "20261124-000000-dead";
10349 task.link_run(run);
10350 task.attempts = 2;
10351 task.status = TaskStatus::Running;
10352 task.sync_only = Some(crate::base_sync_only::Request {
10353 run: run.into(),
10354 at: Timestamp::now(),
10355 });
10356 queue.put(&mut task).unwrap();
10357 assert_eq!(
10358 reclaim_orphaned_running(&queue, 3, &Default::default()),
10359 vec![task.id.clone()]
10360 );
10361 let saved = queue.get(&task.id).unwrap();
10362 assert_eq!(saved.status, TaskStatus::Held);
10363 assert_eq!(saved.attempts, 2);
10364 assert_eq!(saved.execution_runs(), [run]);
10365 assert!(
10366 saved
10367 .last_error
10368 .unwrap()
10369 .contains("verification was not allowed")
10370 );
10371 assert!(reclaim_orphaned_running(&queue, 3, &Default::default()).is_empty());
10372 }
10373
10374 #[test]
10375 fn sync_base_only_completed_orphan_holds_without_charging_or_double_refunding() {
10376 use crate::base_sync_only::{Outcome, Pass, Request};
10377
10378 let mut state = run_state(RunStatus::Blocked);
10379 let mut task = task();
10380 let request = Request {
10381 run: state.id.clone(),
10382 at: Timestamp::now(),
10383 };
10384 task.start(state.id.clone());
10385 task.sync_only = Some(request.clone());
10386 task.attempts = 2;
10388 let mut pass = Pass::new(request, &state);
10389 pass.result = Outcome::AlreadyCurrent;
10390 state.sync_only_passes.push(pass);
10391 state.begin_pass();
10392
10393 reclaim(&mut task, Some(state), 3, "en");
10394
10395 assert_eq!(task.status, TaskStatus::Held);
10396 assert_eq!(task.attempts, 2);
10397 assert!(task.sync_only.is_none());
10398 let detail = task.hold_reason.unwrap();
10399 assert!(detail.contains("HEAD already contains the base"));
10400 assert!(detail.contains("verification was not allowed"));
10401 }
10402
10403 #[test]
10404 fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
10405 let dir = tempfile::tempdir().unwrap();
10406 let queue = Queue::at(dir.path().to_path_buf());
10407
10408 let mut orphaned = task();
10410 orphaned.id = "20260904-000000-orph".to_owned();
10411 orphaned.status = TaskStatus::Running;
10412 orphaned.attempts = 1;
10413 queue.put(&mut orphaned).unwrap();
10414
10415 let mut alive = task();
10416 alive.id = "20260904-000000-live".to_owned();
10417 alive.status = TaskStatus::Running;
10418 alive.attempts = 1;
10419 queue.put(&mut alive).unwrap();
10420 let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
10421
10422 let mut queued = task();
10423 queued.id = "20260904-000000-wait".to_owned();
10424 queue.put(&mut queued).unwrap();
10425
10426 let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
10427 assert_eq!(reclaimed, vec![orphaned.id.clone()]);
10428
10429 assert_eq!(
10430 queue.get(&orphaned.id).unwrap().status,
10431 TaskStatus::Held,
10432 "nothing was driving it and there was no run to recover"
10433 );
10434 assert_eq!(
10435 queue.get(&alive.id).unwrap().status,
10436 TaskStatus::Running,
10437 "a live claim must protect the task it belongs to"
10438 );
10439 assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
10440 }
10441
10442 fn read_run_under(home: &Path, id: &str) -> RunState {
10448 let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
10449 serde_json::from_str(&body).unwrap()
10450 }
10451
10452 #[test]
10453 fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
10454 let dir = tempfile::tempdir().unwrap();
10455 let home = dir.path().to_path_buf();
10456 let now = Timestamp::now();
10457 let overrun_seat = || crate::run::ActiveSeat {
10458 node: "implement".to_owned(),
10459 started_at: now - jiff::SignedDuration::new(21_000, 0),
10460 timeout_secs: 3_600,
10461 attempt: 0,
10462 task: None,
10463 command: None,
10464 index: None,
10465 total: None,
10466 };
10467
10468 let mut dead = run_state(RunStatus::Implementing);
10469 dead.id = "20260101-000000-dead".to_owned();
10470 dead.active.insert("impl-A".to_owned(), overrun_seat());
10471 dead.driver_pid = Some(4242);
10474 dead.save_under(&home).unwrap();
10475
10476 let mut alive = run_state(RunStatus::Implementing);
10479 alive.id = "20260101-000000-aliv".to_owned();
10480 alive.active.insert("impl-A".to_owned(), overrun_seat());
10481 alive.save_under(&home).unwrap();
10482 let mut status = Status::new();
10483 status.current = vec![Current {
10484 worker: None,
10485 task: "20260101-000000-task".to_owned(),
10486 run: alive.id.clone(),
10487 }];
10488 write_status_to(&home.join("daemon.json"), &status).unwrap();
10489
10490 let questions = Questions::at(home.join("questions"));
10494 let mut q = ask::Question::new(
10495 dead.id.clone(),
10496 "implement".to_owned(),
10497 "impl-A".to_owned(),
10498 "Which storage backend?".to_owned(),
10499 String::new(),
10500 vec!["SQLite".to_owned(), "Redis".to_owned()],
10501 );
10502 questions.put(&mut q).unwrap();
10503
10504 let abandoned = reclaim_abandoned_runs_with(
10505 &home,
10506 now,
10507 |pid| if pid == 4242 { Some(false) } else { None },
10508 |_| panic!("a query answering Dead outright needs no identity corroboration"),
10509 );
10510 assert_eq!(abandoned, vec![dead.id.clone()]);
10511
10512 let reloaded = read_run_under(&home, &dead.id);
10513 assert_eq!(reloaded.status, RunStatus::Failed);
10514 assert!(reloaded.active.is_empty());
10515 assert!(
10516 !questions.get(&q.id).unwrap().status.open(),
10517 "the failed run's own open question must be settled in the same pass"
10518 );
10519
10520 let still_alive = read_run_under(&home, &alive.id);
10521 assert_eq!(
10522 still_alive.status,
10523 RunStatus::Implementing,
10524 "a live daemon's claim protects it"
10525 );
10526 assert!(!still_alive.active.is_empty());
10527 }
10528
10529 #[test]
10539 fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
10540 let dir = tempfile::tempdir().unwrap();
10541 let home = dir.path().to_path_buf();
10542 let now = Timestamp::now();
10543
10544 let mut manual = run_state(RunStatus::Reviewing);
10545 manual.id = "20260101-000000-manl".to_owned();
10546 manual.active.insert(
10547 "review-1".to_owned(),
10548 crate::run::ActiveSeat {
10549 node: "review".to_owned(),
10550 started_at: now - jiff::SignedDuration::new(21_000, 0),
10551 timeout_secs: 3_600,
10552 attempt: 0,
10553 task: None,
10554 command: None,
10555 index: None,
10556 total: None,
10557 },
10558 );
10559 manual.driver_pid = Some(4242);
10563 manual.driver_started_at = Some("1790000000".to_owned());
10564 manual.save_under(&home).unwrap();
10565
10566 let abandoned = reclaim_abandoned_runs_with(
10567 &home,
10568 now,
10569 |pid| if pid == 4242 { Some(true) } else { None },
10570 |pid| {
10571 if pid == 4242 {
10572 Some("1790000000".to_owned())
10573 } else {
10574 None
10575 }
10576 },
10577 );
10578 assert!(
10579 abandoned.is_empty(),
10580 "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
10581 );
10582
10583 let reloaded = read_run_under(&home, &manual.id);
10584 assert_eq!(reloaded.status, RunStatus::Reviewing);
10585 assert!(!reloaded.active.is_empty());
10586 }
10587
10588 #[test]
10589 fn an_already_claimed_task_is_skipped_rather_than_failed() {
10590 let dir = tempfile::tempdir().unwrap();
10591 let queue = Queue::at(dir.path().to_path_buf());
10592 let mut only = task();
10593 queue.put(&mut only).unwrap();
10594
10595 let _elsewhere = queue.claim(&only.id).unwrap();
10596 let candidates = runnable(&queue);
10597 assert_eq!(candidates.len(), 1, "the task is still runnable");
10598 assert!(
10599 queue.claim(&candidates[0].id).is_err(),
10600 "the loop cannot take a claim somebody else holds"
10601 );
10602
10603 let after = queue.get(&only.id).unwrap();
10604 assert_eq!(after.status, TaskStatus::Queued);
10605 assert_eq!(
10606 after.attempts, 0,
10607 "losing the race is not an attempt at the task"
10608 );
10609 assert_eq!(after.last_error, None);
10610 }
10611
10612 #[test]
10613 fn the_status_file_round_trips_and_its_heartbeat_advances() {
10614 let dir = tempfile::tempdir().unwrap();
10615 let path = dir.path().join("daemon.json");
10616
10617 let mut status = Status::new();
10618 status.idle = false;
10619 status.completed = 7;
10620 status.current = vec![Current {
10621 worker: None,
10622 task: "20260902-000000-t111".to_owned(),
10623 run: "20260902-000001-r111".to_owned(),
10624 }];
10625 write_status_to(&path, &status).unwrap();
10626 let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
10627 assert_eq!(first.schema, SCHEMA);
10628 assert_eq!(first.pid, std::process::id());
10629 assert!(!first.idle);
10630 assert_eq!(first.completed, 7);
10631 assert_eq!(first.current, status.current);
10632 assert!(
10633 !path.with_extension("json.tmp").exists(),
10634 "the temp file is renamed, not left behind"
10635 );
10636
10637 std::thread::sleep(Duration::from_millis(5));
10638 status.updated_at = Timestamp::now();
10639 status.polls = 3;
10640 write_status_to(&path, &status).unwrap();
10641 let second: Status =
10642 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
10643 assert!(
10644 second.updated_at > first.updated_at,
10645 "a reader can only detect staleness if the heartbeat moves"
10646 );
10647 assert_eq!(
10648 second.started_at, first.started_at,
10649 "the start time is not a heartbeat"
10650 );
10651 assert_eq!(second.polls, 3);
10652 }
10653
10654 #[test]
10655 fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
10656 let dir = tempfile::tempdir().unwrap();
10657
10658 assert!(read_status(dir.path()).is_none(), "no file, no daemon");
10659
10660 let mut status = Status::new();
10661 status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
10662 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10663 let stale = read_status(dir.path()).unwrap();
10664 assert!(
10665 !stale.running(Timestamp::now()),
10666 "a minute without a heartbeat is a dead daemon, not a busy one"
10667 );
10668 assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
10669
10670 status.updated_at = Timestamp::now();
10671 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10672 let fresh = read_status(dir.path()).unwrap();
10673 assert!(fresh.running(Timestamp::now()));
10674 }
10675
10676 #[test]
10677 fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
10678 let dir = tempfile::tempdir().unwrap();
10679 let now = Timestamp::now();
10680 let mine = "20260903-080619-01c2";
10681
10682 assert!(
10683 !is_working_on(dir.path(), mine, now),
10684 "no status file means nobody is working on anything"
10685 );
10686
10687 let mut status = Status::new();
10688 status.current = vec![Current {
10689 worker: None,
10690 task: "20260903-080340-0167".to_owned(),
10691 run: mine.to_owned(),
10692 }];
10693 status.updated_at = now;
10694 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10695 assert!(is_working_on(dir.path(), mine, now));
10696 assert!(
10697 !is_working_on(dir.path(), "20260903-105039-3cbf", now),
10698 "a daemon busy with one run is not working on another"
10699 );
10700
10701 status.updated_at = now - jiff::SignedDuration::from_secs(600);
10704 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10705 assert!(
10706 !is_working_on(dir.path(), mine, now),
10707 "a stale heartbeat is a dead daemon, so its run is a leftover"
10708 );
10709 }
10710
10711 #[test]
10712 fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
10713 let dir = tempfile::tempdir().unwrap();
10714 let now = Timestamp::now();
10715
10716 assert!(
10717 !is_working_on_short(dir.path(), "01c2", now),
10718 "no status file means nobody is working on anything"
10719 );
10720
10721 let mut status = Status::new();
10722 status.current = vec![Current {
10723 worker: None,
10724 task: "20260903-080340-0167".to_owned(),
10725 run: "20260903-080619-01c2".to_owned(),
10726 }];
10727 status.updated_at = now;
10728 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10729 assert!(
10730 is_working_on_short(dir.path(), "01c2", now),
10731 "the run's short id is the last block of its full id"
10732 );
10733 assert!(
10734 !is_working_on_short(dir.path(), "3cbf", now),
10735 "a daemon busy with one worktree bay is not working on another"
10736 );
10737 }
10738
10739 #[test]
10740 fn a_newer_status_file_still_yields_a_reading() {
10741 let dir = tempfile::tempdir().unwrap();
10742 std::fs::write(
10745 dir.path().join("daemon.json"),
10746 serde_json::json!({
10747 "schema": 2,
10748 "updated_at": Timestamp::now().to_string(),
10749 "idle": true,
10750 "surprise": { "nested": [1, 2, 3] },
10751 })
10752 .to_string(),
10753 )
10754 .unwrap();
10755
10756 let reading = read_status(dir.path()).expect("a forward-compatible read");
10757 assert!(reading.running(Timestamp::now()));
10758 assert!(reading.idle);
10759 assert!(reading.current.is_empty());
10760 }
10761
10762 #[test]
10763 fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
10764 let dir = tempfile::tempdir().unwrap();
10770 std::fs::write(
10771 dir.path().join("daemon.json"),
10772 serde_json::json!({
10773 "schema": 1,
10774 "pid": 4242,
10775 "updated_at": Timestamp::now().to_string(),
10776 "idle": false,
10777 "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
10778 "completed": 3,
10779 "polls": 9,
10780 })
10781 .to_string(),
10782 )
10783 .unwrap();
10784
10785 let reading = read_status(dir.path()).expect("an older shape must still parse");
10786 assert!(reading.running(Timestamp::now()));
10787 assert_eq!(
10788 reading.current,
10789 vec![Current {
10790 worker: None,
10791 task: "20260902-140501-aaaa".to_owned(),
10792 run: "20260902-140502-bbbb".to_owned(),
10793 }]
10794 );
10795 }
10796
10797 #[test]
10798 fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
10799 let dir = tempfile::tempdir().unwrap();
10800 std::fs::write(
10801 dir.path().join("daemon.json"),
10802 serde_json::json!({
10803 "schema": 1,
10804 "updated_at": Timestamp::now().to_string(),
10805 "idle": true,
10806 "current": null,
10807 })
10808 .to_string(),
10809 )
10810 .unwrap();
10811 let with_null = read_status(dir.path()).expect("null must still parse");
10812 assert!(with_null.current.is_empty());
10813
10814 std::fs::write(
10815 dir.path().join("daemon.json"),
10816 serde_json::json!({
10817 "schema": 1,
10818 "updated_at": Timestamp::now().to_string(),
10819 "idle": true,
10820 })
10821 .to_string(),
10822 )
10823 .unwrap();
10824 let absent = read_status(dir.path()).expect("a missing field must still parse");
10825 assert!(absent.current.is_empty());
10826 }
10827
10828 #[test]
10829 fn a_task_without_a_repository_runs_in_the_daemons_default() {
10830 let fallback = Path::new("/default");
10831 let mut blank = task();
10832 blank.repo = PathBuf::new();
10833 assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
10834 let mut dot = task();
10835 dot.repo = PathBuf::from(".");
10836 assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
10837 assert_eq!(
10838 repo_for(&task(), fallback),
10839 PathBuf::from("/repo"),
10840 "a task that names a repository keeps it"
10841 );
10842 }
10843
10844 #[test]
10845 fn new_tasks_inherit_the_daemon_build_cache_but_historical_tasks_remain_shared() {
10846 let dir = tempfile::tempdir().unwrap();
10847 let repo = dir.path();
10848 let path = repo.join("explicit.toml");
10849 std::fs::write(
10850 &path,
10851 "[verify]\nbuild_cache = 'isolated'\n[graph]\njudges = 1\n",
10852 )
10853 .unwrap();
10854 let opts = Opts {
10855 config: Some(path),
10856 ..Opts::default()
10857 };
10858 let queue = Queue::at(repo.join("queue"));
10859 let mut new = task();
10860 queue.put(&mut new).unwrap();
10861 let resolved = |task: &Task| prepare_for(repo, &opts, task).unwrap();
10862 assert_eq!(
10863 resolved(&queue.get(&new.id).unwrap()).verify.build_cache,
10864 BuildCache::Isolated
10865 );
10866
10867 let mut old = task();
10868 old.schema = 22;
10869 queue.put(&mut old).unwrap();
10870 let mut old = queue.get(&old.id).unwrap();
10871 let config = resolved(&old);
10872 assert_eq!(config.verify.build_cache, BuildCache::Shared);
10873 assert_eq!(config.graph.judges, 1, "preserve daemon config inheritance");
10874 old.hold_manual(Some("wait".into()));
10875 queue.put(&mut old).unwrap();
10876
10877 let mut saved = queue.get(&old.id).unwrap();
10878 assert_eq!(resolved(&saved).verify.build_cache, BuildCache::Shared);
10879 saved
10880 .overrides
10881 .as_mut()
10882 .unwrap()
10883 .merge_over(&crate::queue::RunOverrides {
10884 build_cache: Some(BuildCache::Isolated),
10885 ..Default::default()
10886 });
10887 queue.put(&mut saved).unwrap();
10888 assert_eq!(
10889 resolved(&queue.get(&saved.id).unwrap()).verify.build_cache,
10890 BuildCache::Isolated
10891 );
10892 }
10893
10894 #[test]
10895 fn urgent_build_cache_precedes_config_but_not_an_explicit_choice() {
10896 let dir = tempfile::tempdir().unwrap();
10897 let path = dir.path().join("explicit.toml");
10898 let write = |verify: &str| {
10899 std::fs::write(&path, format!("[verify]\nbuild_cache = 'shared'\n{verify}")).unwrap();
10900 };
10901 write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test\"]\n");
10902 let opts = Opts {
10903 config: Some(path.clone()),
10904 ..Opts::default()
10905 };
10906 let mut task = task();
10907 task.set_urgent(true).unwrap();
10908 let resolved = |task: &Task| {
10909 prepare_for(dir.path(), &opts, task)
10910 .unwrap()
10911 .verify
10912 .build_cache
10913 };
10914 assert_eq!(resolved(&task), BuildCache::Isolated);
10915 task.change_build_cache(Some(BuildCache::Shared)).unwrap();
10916 assert_eq!(resolved(&task), BuildCache::Shared);
10917 task.change_build_cache(None).unwrap();
10918 assert_eq!(resolved(&task), BuildCache::Isolated);
10919 task.set_urgent(false).unwrap();
10920 assert_eq!(resolved(&task), BuildCache::Shared);
10921
10922 task.set_urgent(true).unwrap();
10926 write("e2e = [\"npm test\"]\n");
10927 assert_eq!(resolved(&task), BuildCache::Shared);
10928 write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test | tee log\"]\n");
10929 assert_eq!(resolved(&task), BuildCache::Shared);
10930 task.change_build_cache(Some(BuildCache::Isolated)).unwrap();
10932 assert_eq!(resolved(&task), BuildCache::Isolated);
10933 }
10934
10935 #[test]
10936 fn task_implementers_edit_inherits_daemon_config_and_merge() {
10937 let dir = tempfile::tempdir().unwrap();
10938 let path = dir.path().join("explicit.toml");
10939 std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
10940 let opts = Opts {
10941 config: Some(path),
10942 merge: Some("none".into()),
10943 ..Default::default()
10944 };
10945 let mut t = task();
10946 t.set_implementers(
10947 2,
10948 &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10949 .unwrap(),
10950 )
10951 .unwrap();
10952 let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
10953 assert_eq!(cfg.graph.implementers, 2);
10954 assert_eq!(cfg.graph.judges, 1);
10955 assert_eq!(cfg.merge.mode, MergeMode::None);
10956 t.set_implementers(1, &cfg).unwrap();
10957 let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
10958 apply_task_implementers(&mut cfg, &t);
10959 assert_eq!(cfg.graph.implementers, 1);
10960 assert_eq!(cfg.graph.judges, 1);
10961 assert_eq!(cfg.merge.mode, MergeMode::None);
10962 }
10963
10964 #[test]
10965 fn task_implementers_direct_overrides_stay_isolated_after_edits() {
10966 let dir = tempfile::tempdir().unwrap();
10967 let repo = dir.path().join("repo");
10968 std::fs::create_dir(&repo).unwrap();
10969 std::fs::write(
10970 repo.join("magi.toml"),
10971 "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
10972 )
10973 .unwrap();
10974 let daemon_config = dir.path().join("daemon.toml");
10975 std::fs::write(
10976 &daemon_config,
10977 "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
10978 )
10979 .unwrap();
10980 let opts = Opts {
10981 config: Some(daemon_config),
10982 merge: Some("pr".into()),
10983 ..Default::default()
10984 };
10985 let q = Queue::at(dir.path().join("queue"));
10986 let validation: Config =
10987 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10988 .unwrap();
10989 for record in ["{}", r#"{"candidates":2}"#] {
10991 let overrides = serde_json::from_str(record).unwrap();
10992 let filing = crate::direct::Filing {
10993 instruction: "work".into(),
10994 title: "direct".into(),
10995 repo: repo.clone(),
10996 source: crate::queue::Source::Human,
10997 solo: false,
10998 overrides,
10999 review_of: None,
11000 sources: Default::default(),
11001 };
11002 let filed =
11003 crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
11004 let crate::direct::Filed::Standalone {
11005 mut task,
11006 claim: _claim,
11007 } = filed
11008 else {
11009 panic!("local filing")
11010 };
11011 let before = prepare_for(&repo, &opts, &task).unwrap();
11012 assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
11013 assert_eq!(
11014 before.merge.mode,
11015 MergeMode::None,
11016 "daemon --merge must not leak"
11017 );
11018 for n in [2, 1, 2] {
11019 task.set_implementers(n, &validation).unwrap();
11020 q.put(&mut task).unwrap();
11021 task = q.get(&task.id).unwrap();
11022 assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
11023 let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
11024 apply_task_implementers(&mut cfg, &task);
11025 assert_eq!(cfg.graph.implementers, usize::from(n));
11026 assert_eq!(cfg.graph.judges, 2);
11027 assert_eq!(cfg.merge.mode, MergeMode::None);
11028 }
11029 }
11030 }
11031
11032 #[test]
11033 fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
11034 let cfg: Config =
11035 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
11036 .unwrap();
11037 let mut t = task();
11038 t.review_of = Some("review-target".into());
11039 t.hold_manual(Some("retry".into()));
11040 let mut previous = RunState::new(
11041 PathBuf::from("/repo"),
11042 "main".into(),
11043 "abc1234".into(),
11044 "review".into(),
11045 cfg.clone(),
11046 );
11047 previous.config.graph.implementers = 2;
11048 for count in [1, 3] {
11049 t.set_implementers(count, &cfg).unwrap();
11050 t.release();
11051 assert_eq!(t.review_of.as_deref(), Some("review-target"));
11052 for proposed in [
11053 Starter::Resume(previous.id.clone()),
11054 Starter::Review("recovery-target".into()),
11055 ] {
11056 assert_eq!(
11057 starter_with_implementers(&t, Some(&previous), proposed),
11058 Starter::Review("review-target".into())
11059 );
11060 }
11061 let mut configured = cfg.clone();
11062 apply_task_implementers(&mut configured, &t);
11063 assert_eq!(configured.graph.implementers, usize::from(count));
11064 assert_eq!(previous.config.graph.implementers, 2);
11065 }
11066 }
11067
11068 #[test]
11069 fn task_implementers_dispatch_and_resume_agree() {
11070 let mut t = task();
11071 let cfg: crate::config::Config =
11072 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
11073 .unwrap();
11074 let mut run = RunState::new(
11075 PathBuf::from("/repo"),
11076 "main".into(),
11077 "abc1234".into(),
11078 "work".into(),
11079 cfg.clone(),
11080 );
11081 run.config.graph.implementers = 2;
11082 for n in [2, 1, 3, 2] {
11083 t.set_implementers(n, &cfg).unwrap();
11084 let mut dispatched = cfg.clone();
11085 apply_task_implementers(&mut dispatched, &t);
11086 assert_eq!(dispatched.graph.implementers, usize::from(n));
11087 assert_eq!(implementers_match(&t, &run), n == 2);
11088 for proposed in [
11089 Starter::Resume(run.id.clone()),
11090 Starter::Review("old-branch".into()),
11091 ] {
11092 let expected = if n == 2 {
11093 proposed.clone()
11094 } else {
11095 Starter::Start
11096 };
11097 assert_eq!(
11098 starter_with_implementers(&t, Some(&run), proposed),
11099 expected
11100 );
11101 }
11102 assert_eq!(
11103 run.config.graph.implementers, 2,
11104 "history must not be rewritten"
11105 );
11106 }
11107 t.solo = false;
11108 t.overrides = None;
11109 assert!(implementers_match(&t, &run));
11110 }
11111
11112 #[test]
11113 fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
11114 let mut solo_cfg = Config::default();
11120 solo_cfg.graph.implementers = 3;
11121 let mut solo_task = task();
11122 solo_task.solo = true;
11123 apply_task_implementers(&mut solo_cfg, &solo_task);
11124 assert_eq!(solo_cfg.graph.implementers, 1);
11125
11126 let mut plain_cfg = Config::default();
11127 plain_cfg.graph.implementers = 3;
11128 let plain_task = task();
11129 assert!(!plain_task.solo);
11130 apply_task_implementers(&mut plain_cfg, &plain_task);
11131 assert_eq!(
11132 plain_cfg.graph.implementers, 3,
11133 "a task that did not ask to run alone keeps the config's candidates"
11134 );
11135 }
11136
11137 fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
11138 QuotaLoss {
11139 cause: crate::agent::QuotaCause::UsageLimit,
11140 agent: String::new(),
11141 seat: seat.into(),
11142 node: "judge".into(),
11143 at: at.parse().unwrap(),
11144 reset: reset.map(str::to_string),
11145 }
11146 }
11147
11148 #[test]
11149 fn authentication_losses_never_arm_a_cooldown_even_with_reset_hints() {
11150 let now = Timestamp::now();
11151 for reset in [None, Some("in 1h")] {
11152 let auth = crate::agent::Quota {
11153 cause: crate::agent::QuotaCause::Authentication,
11154 agent: "alpha".into(),
11155 reset: reset.map(str::to_owned),
11156 };
11157 let loss = QuotaLoss::from_report("advisor-1".into(), "advise", Some(&auth));
11158 assert_eq!(cooldown_until(&[loss], now), None);
11159 }
11160 }
11161
11162 #[test]
11163 fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
11164 let old: Vec<QuotaLoss> = (1..=4)
11165 .map(|i| {
11166 loss(
11167 &format!("judge-{i}"),
11168 "2026-09-23T05:23:00Z",
11169 Some("2:40pm (Asia/Tokyo)"),
11170 )
11171 })
11172 .collect();
11173 let fresh = losses_this_attempt(&old, &old);
11174 assert!(fresh.is_empty());
11175 assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
11176 }
11178
11179 #[test]
11180 fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
11181 let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
11182 let now = Timestamp::now();
11183 let mut after = old.clone();
11184 after.push(loss("judge-2", &now.to_string(), None));
11185 let fresh = losses_this_attempt(&old, &after);
11186 assert_eq!(fresh, vec![after[1].clone()]);
11187 let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
11188 assert_eq!(
11189 until,
11190 now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
11191 );
11192 }
11193
11194 #[test]
11195 fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
11196 let before = vec![
11199 loss("judge-1", "2026-09-23T05:23:00Z", None),
11200 loss("judge-2", "2026-09-23T05:24:00Z", None),
11201 ];
11202 let after = vec![
11203 loss("judge-2", "2026-09-23T05:24:00Z", None),
11204 loss("judge-1", "2026-09-24T01:00:00Z", None),
11205 ];
11206 assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
11207 }
11208
11209 #[test]
11210 fn merge_overrides_are_parsed_or_refused() {
11211 assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
11212 assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
11213 assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
11214 assert!(merge_mode("squash").is_err());
11215 }
11216
11217 #[test]
11218 fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
11219 let now = Timestamp::now();
11220 let fallback = Duration::from_secs(300);
11221 let cap = Duration::from_secs(1800);
11222
11223 assert_eq!(quota_wait(None, now, fallback, cap), fallback);
11225
11226 let soon = now + jiff::SignedDuration::from_secs(600);
11228 assert_eq!(
11229 quota_wait(Some(soon), now, fallback, cap),
11230 Duration::from_secs(600)
11231 );
11232
11233 let past = now - jiff::SignedDuration::from_secs(60);
11236 assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
11237
11238 let far = now + jiff::SignedDuration::from_secs(3 * 3600);
11241 assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
11242 }
11243
11244 #[test]
11245 fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
11246 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
11247
11248 let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
11249 assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
11250
11251 let already_past =
11255 parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
11256 assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
11257
11258 assert!(
11259 parse_reset_hint("session limit reached", now, now).is_none(),
11260 "free text with no recognised shape is not guessed at"
11261 );
11262 assert!(
11263 parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
11264 "an unresolvable zone name is not guessed at either"
11265 );
11266 }
11267
11268 #[test]
11269 fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
11270 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
11271
11272 let at = parse_reset_hint(
11273 "You've hit your usage limit. Visit \
11274 https://chatgpt.com/codex/settings/usage to purchase more \
11275 credits or try again at Sep 19th, 2026 5:10 PM.",
11276 now,
11277 now,
11278 )
11279 .expect("the codex reset wording is a recognised shape");
11280 assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
11281
11282 let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
11287 .expect("an explicit year needs no rollover");
11288 assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
11289
11290 assert!(
11291 parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
11292 "a two-digit year is not the documented shape and is not guessed at"
11293 );
11294 assert!(
11295 parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
11296 "a four-letter month name is not the documented three-letter abbreviation"
11297 );
11298 assert!(
11299 parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
11300 "an explicit zone on the dated shape is a format nobody has \
11301 documented, and is refused rather than guessed at as UTC"
11302 );
11303 }
11304
11305 #[test]
11306 fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
11307 let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
11308 let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
11309
11310 let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
11311 assert_eq!(at.as_second() - recorded.as_second(), 3769);
11312
11313 let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
11314 assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
11315
11316 for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
11317 assert!(
11318 parse_reset_hint(bad, now, recorded).is_none(),
11319 "{bad:?} must not be guessed at"
11320 );
11321 }
11322 }
11323
11324 fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
11328 let config = dir.join("magi.toml");
11329 std::fs::write(
11330 &config,
11331 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
11332 )
11333 .unwrap();
11334 let opts = Opts {
11335 poll: Duration::from_secs(30),
11336 config: Some(config),
11337 repo: dir.join("repo"),
11341 ..Opts::default()
11342 };
11343 let home = dir.join("home");
11352 let stamps = home.join("service-ticks");
11355 std::fs::create_dir_all(&stamps).unwrap();
11356 for service in ["waiter", "deputies", "release-watch"] {
11357 std::fs::write(
11358 stamps.join(service),
11359 Timestamp::now().as_second().to_string(),
11360 )
11361 .unwrap();
11362 }
11363 for operation in [
11364 "conductor",
11365 "maintenance",
11366 "housekeeping",
11367 "disk-pressure",
11368 "cache",
11369 "fetch",
11370 "chat-goals",
11371 ] {
11372 std::fs::write(
11373 stamps.join(format!("daemon-{operation}")),
11374 serde_json::to_vec(&Timestamp::now()).unwrap(),
11375 )
11376 .unwrap();
11377 }
11378 let worktrees = dir.join("wt");
11379 (
11380 opts,
11381 Queue::at(dir.join("queue")),
11382 home.join("daemon.json"),
11383 home,
11384 worktrees,
11385 )
11386 }
11387
11388 #[tokio::test]
11389 async fn disk_wait_maintenance_recovers_while_another_task_is_running() {
11390 let dir = tempfile::tempdir().unwrap();
11391 let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
11392 let mut waiting = task();
11393 waiting.repo = opts.repo.clone();
11394 waiting.hold_machine(crate::disk::gate(1, 100));
11395 waiting.mark_disk_capacity();
11396 waiting.attempts = 2;
11397 queue.put(&mut waiting).unwrap();
11398 let mut busy = task();
11399 busy.status = TaskStatus::Running;
11400 queue.put(&mut busy).unwrap();
11401 let payload = serde_json::to_value(ServiceWorker {
11402 opts,
11403 queue: queue.root().to_owned(),
11404 worktrees_root: worktrees,
11405 operation: "maintenance".into(),
11406 })
11407 .unwrap();
11408 run_service_worker(&home, payload.clone()).await.unwrap();
11409 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Queued);
11410 assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
11411 assert_eq!(queue.get(&busy.id).unwrap().status, TaskStatus::Running);
11412 run_service_worker(&home, payload).await.unwrap();
11413 assert!(
11414 crate::worker::active(&home).unwrap().is_empty(),
11415 "monitoring only queues; normal dispatch owns launches"
11416 );
11417 assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
11418 }
11419
11420 #[tokio::test]
11421 async fn source_eviction_service_receipts_explain_idle_and_active_skips() {
11422 let dir = tempfile::tempdir().unwrap();
11423 let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
11424 let cfg = Config::default();
11425 start_service(
11426 &home,
11427 &opts,
11428 &queue,
11429 &worktrees,
11430 "housekeeping",
11431 Some(&cfg),
11432 true,
11433 )
11434 .await
11435 .unwrap();
11436 let receipt = home.join("source-eviction-housekeeping-dispatch.json");
11437 let read = |path: &Path| -> serde_json::Value {
11438 serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap()
11439 };
11440 assert_eq!(read(&receipt)["detail"], "cadence not due");
11441 std::fs::remove_file(home.join("service-ticks/daemon-housekeeping")).unwrap();
11442 start_service(
11443 &home,
11444 &opts,
11445 &queue,
11446 &worktrees,
11447 "housekeeping",
11448 Some(&cfg),
11449 true,
11450 )
11451 .await
11452 .unwrap();
11453 assert_eq!(
11454 read(&receipt)["detail"],
11455 "active work or runnable task queue"
11456 );
11457 assert_eq!(read(&receipt)["version"], env!("CARGO_PKG_VERSION"));
11458 assert_eq!(read(&receipt)["auto_fold"], cfg.disk.auto_fold);
11459 std::fs::remove_file(home.join("service-ticks/daemon-disk-pressure")).unwrap();
11460 start_service(
11461 &home,
11462 &opts,
11463 &queue,
11464 &worktrees,
11465 "disk-pressure",
11466 Some(&cfg),
11467 false,
11468 )
11469 .await
11470 .unwrap();
11471 assert_eq!(
11472 read(&home.join("source-eviction-disk-pressure-dispatch.json"))["detail"],
11473 "no active work; idle housekeeping owns scan"
11474 );
11475 assert!(crate::worker::active(&home).unwrap().is_empty());
11476 }
11477
11478 #[tokio::test]
11479 async fn goal_observation_service_does_not_block_scheduler_decisions() {
11480 let dir = tempfile::tempdir().unwrap();
11481 let (opts, _, _, home, worktrees) = idle_loop(dir.path());
11482 let queue = Queue::at(home.join("queue"));
11483 let mut task = task();
11484 task.repo = opts.repo.clone();
11485 task.chat = Some("decision-chat".into());
11486 task.hold_machine(Some("waiting for a decision".into()));
11487 queue.put(&mut task).unwrap();
11488 let questions = Questions::at(home.join("questions"));
11489 let mut question = action_question(&task.id, ask::ChoiceAction::Done);
11490 question.node = crate::conduct::NODE.into();
11491 question.status = ask::QuestionStatus::Open;
11492 question.answer = None;
11493 question.answered_at = None;
11494 questions.put(&mut question).unwrap();
11495 questions
11496 .update(&question.id, |q| {
11497 q.answer(ask::Answer::Choice("resume で続行する".into()))
11498 })
11499 .unwrap();
11500
11501 let talks = crate::talk::Talks::at(home.join("talks"));
11502 let mut decision_chat = crate::talk::seeded_for_test("decision-chat", opts.repo.clone());
11503 decision_chat.pending = "Keep this unsent status question".into();
11504 talks.put(&mut decision_chat).unwrap();
11505 let mut talk = crate::talk::seeded_for_test("observing-chat", opts.repo.clone());
11506 talk.goals.push(serde_json::from_value(serde_json::json!({
11507 "id":"goal","purpose":"follow the retained job","scope":"one task",
11508 "condition":{"description":"land the result","kind":"runs_merged"},
11509 "state":"runnable","step":"reading the forge","source_turn":0,"owner_input":"land this job",
11510 "tasks":[],"runs":[],"watches":[],"evidence":"","wake":1,"handled":0,
11511 "started":1,"wakes":1,"last_checked":null,"fingerprint":""
11512 })).unwrap());
11513 talks.put(&mut talk).unwrap();
11514
11515 let directory = home.join("workers/jobs/abcdef");
11518 std::fs::create_dir_all(&directory).unwrap();
11519 let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
11520 crate::pr_head::try_lock_file(&lease).unwrap();
11521 let mut job = crate::worker::Job {
11522 id: "abcdef".into(),
11523 sequence: 1,
11524 kind: "daemon-service".into(),
11525 key: "service:daemon-chat-goals".into(),
11526 payload: serde_json::Value::Null,
11527 generation: "fixture".into(),
11528 version: None,
11529 status: crate::worker::Status::Running,
11530 result: None,
11531 pid: Some(std::process::id()),
11532 created_at: Timestamp::now().as_second() as u64,
11533 finished_at: None,
11534 };
11535 let record = directory.join("job.json");
11536 std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11537 let status = Arc::new(Mutex::new(Status::new()));
11538 let stop = Stop::new();
11539 let mut dispatch = Box::pin(poll(
11540 &opts,
11541 &queue,
11542 &status,
11543 &home,
11544 &worktrees,
11545 &stop,
11546 DispatchLimits {
11547 max_concurrent: 1,
11548 pause_for_interrupts: false,
11549 recovery_cfg: None,
11550 },
11551 ));
11552 std::future::poll_fn(|cx| {
11553 assert!(dispatch.as_mut().poll(cx).is_pending());
11554 std::task::Poll::Ready(())
11555 })
11556 .await;
11557 assert!(lock(&status).polls > 0);
11558 let saved = queue.get(&task.id).unwrap();
11559 assert_eq!(saved.status, TaskStatus::Done);
11560 assert!(saved.action_applied(&question.id));
11561 assert!(
11562 talks
11563 .get("decision-chat")
11564 .unwrap()
11565 .pending
11566 .contains("Keep this unsent status question")
11567 );
11568 let goal = talks.get(&talk.id).unwrap().goals.remove(0);
11569 assert_eq!(goal.state, crate::chat_goal::State::Runnable);
11570 assert_eq!(
11571 goal.started,
11572 Some(1),
11573 "only the observation worker may reconcile its goal"
11574 );
11575 assert_eq!(crate::worker::active(&home).unwrap()[0].id, job.id);
11576
11577 stop.stop();
11578 dispatch.await.unwrap();
11579 job.status = crate::worker::Status::Finished;
11580 std::fs::write(record, serde_json::to_vec(&job).unwrap()).unwrap();
11581 drop(lease);
11582 }
11583
11584 #[test]
11585 fn a_stop_is_idempotent_and_once_set_stays_set() {
11586 let stop = Stop::new();
11587 assert!(!stop.stopped());
11588
11589 stop.stop();
11590 assert!(stop.stopped());
11591 stop.stop();
11592 assert!(stop.stopped(), "a second stop is not a toggle");
11593
11594 let shared = stop.clone();
11595 assert!(
11596 shared.stopped(),
11597 "a clone is the same stop; that is how the loop and its caller share one"
11598 );
11599 }
11600
11601 #[tokio::test]
11602 async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
11603 for operation in ["conductor", "maintenance", "housekeeping"] {
11604 let dir = tempfile::tempdir().unwrap();
11605 let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
11606 opts.once = true;
11607 opts.poll = Duration::from_millis(1);
11608 let mut state = run_state(RunStatus::Ready);
11611 state.reserve_under(&home).unwrap();
11612 state.save_under(&home).unwrap();
11613 let mut task = task();
11614 task.runs.push(state.id.clone());
11615 queue.put(&mut task).unwrap();
11616 let claim = queue.claim(&task.id).unwrap();
11617
11618 let directory = home.join("workers/jobs/abcdef");
11621 std::fs::create_dir_all(&directory).unwrap();
11622 let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
11623 crate::pr_head::try_lock_file(&lease).unwrap();
11624 let mut job = crate::worker::Job {
11625 id: "abcdef".into(),
11626 sequence: 1,
11627 kind: "daemon-service".into(),
11628 key: format!("service:daemon-{operation}"),
11629 payload: serde_json::Value::Null,
11630 generation: "fixture".into(),
11631 version: None,
11632 status: crate::worker::Status::Running,
11633 result: None,
11634 pid: Some(std::process::id()),
11635 created_at: Timestamp::now().as_second() as u64,
11636 finished_at: None,
11637 };
11638 let record = directory.join("job.json");
11639 std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11640
11641 let status = Arc::new(Mutex::new(Status::new()));
11642 let stop = Stop::new();
11643 let mut drain = Box::pin(poll(
11644 &opts,
11645 &queue,
11646 &status,
11647 &home,
11648 &worktrees,
11649 &stop,
11650 DispatchLimits {
11651 max_concurrent: 1,
11652 pause_for_interrupts: false,
11653 recovery_cfg: None,
11654 },
11655 ));
11656 std::future::poll_fn(|cx| {
11657 use std::future::Future;
11658 assert!(
11659 drain.as_mut().poll(cx).is_pending(),
11660 "--once must wait for {operation} to release its queue claim"
11661 );
11662 std::task::Poll::Ready(())
11663 })
11664 .await;
11665 assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
11666
11667 let questions = Questions::at(home.join("questions"));
11670 let mut q = action_question(&state.id, ask::ChoiceAction::Done);
11671 questions.put(&mut q).unwrap();
11672 drop(claim);
11673 let expired =
11677 serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
11678 for service in [operation, "housekeeping"] {
11679 std::fs::write(
11680 home.join("service-ticks").join(format!("daemon-{service}")),
11681 &expired,
11682 )
11683 .unwrap();
11684 }
11685 job.status = crate::worker::Status::Finished;
11686 std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11687 drop(lease);
11688 tokio::time::timeout(Duration::from_secs(2), drain)
11689 .await
11690 .expect("the settled service must allow the drain to finish")
11691 .unwrap();
11692 let after = queue.get(&task.id).unwrap();
11693 assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
11694 assert!(after.action_applied(&q.id));
11695 for service in [operation, "housekeeping"] {
11696 assert_eq!(
11697 std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
11698 .unwrap(),
11699 expired,
11700 "the final once rescan must not restart {service}"
11701 );
11702 }
11703 }
11704 }
11705
11706 #[test]
11707 fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
11708 let stop = Stop::new();
11709 stop.busy.store(1, Ordering::SeqCst);
11710 assert!(
11711 !stop.finishing(),
11712 "a busy loop nobody has asked to stop is just running"
11713 );
11714
11715 stop.stop();
11716 assert!(
11717 stop.finishing(),
11718 "a stop asked for mid-run has not landed until the run is settled"
11719 );
11720
11721 stop.busy.store(0, Ordering::SeqCst);
11722 assert!(
11723 !stop.finishing(),
11724 "once the run is settled the stop has landed and there is nothing to finish"
11725 );
11726 }
11727
11728 #[test]
11729 fn finishing_stays_true_until_the_last_of_several_runs_exits() {
11730 let stop = Stop::new();
11731 stop.busy.store(2, Ordering::SeqCst);
11732 stop.stop();
11733 assert!(stop.finishing(), "two runs still in flight");
11734
11735 stop.busy.store(1, Ordering::SeqCst);
11736 assert!(
11737 stop.finishing(),
11738 "one run finished, but a sibling is still working"
11739 );
11740
11741 stop.busy.store(0, Ordering::SeqCst);
11742 assert!(
11743 !stop.finishing(),
11744 "the last run out is what actually lands the stop"
11745 );
11746 }
11747
11748 #[tokio::test]
11749 async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
11750 let dir = tempfile::tempdir().unwrap();
11751 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
11752 let stop = Stop::new();
11753 stop.stop();
11754
11755 let began = std::time::Instant::now();
11756 tokio::time::timeout(
11757 Duration::from_secs(2),
11758 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
11759 )
11760 .await
11761 .expect("a stopped loop must return, not sit out its poll interval")
11762 .expect("the loop's own setup and teardown must not fail");
11763 assert!(
11764 began.elapsed() < opts.poll,
11765 "returned only after {:?}, which is a poll interval, not a stop",
11766 began.elapsed()
11767 );
11768 }
11769
11770 #[tokio::test]
11771 async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
11772 let dir = tempfile::tempdir().unwrap();
11773 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
11774 let stop = Stop::new();
11775
11776 let asker = {
11779 let stop = stop.clone();
11780 tokio::spawn(async move {
11781 tokio::time::sleep(Duration::from_millis(20)).await;
11782 stop.stop();
11783 })
11784 };
11785
11786 let began = std::time::Instant::now();
11787 tokio::time::timeout(
11788 Duration::from_secs(2),
11789 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
11790 )
11791 .await
11792 .expect("a stop asked for while idle must wake the wait")
11793 .expect("the loop's own setup and teardown must not fail");
11794 asker.await.unwrap();
11795 assert!(
11796 began.elapsed() < opts.poll,
11797 "returned only after {:?}, so the stop waited on the sleep",
11798 began.elapsed()
11799 );
11800 }
11801
11802 #[tokio::test]
11803 async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
11804 let dir = tempfile::tempdir().unwrap();
11805 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
11806 let stop = Stop::new();
11807 stop.stop();
11808
11809 tokio::time::timeout(
11810 Duration::from_secs(2),
11811 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
11812 )
11813 .await
11814 .expect("a stopped loop must return")
11815 .expect("the loop's own setup and teardown must not fail");
11816
11817 assert!(
11818 home.is_dir(),
11819 "the loop did publish a status file, so its removal is the teardown and not an absence"
11820 );
11821 assert!(
11822 !status_file.exists(),
11823 "a stopped loop clears its status file"
11824 );
11825 assert!(
11826 read_status(&home).is_none(),
11827 "a reader must see no daemon at all, not a heartbeat that merely stopped"
11828 );
11829 }
11830
11831 #[tokio::test]
11832 async fn housekeeping_worker_settles_questions_without_a_scheduler() {
11833 let dir = tempfile::tempdir().unwrap();
11834 let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
11835
11836 let mut settled = RunState::new(
11837 dir.path().join("repo"),
11838 "main".to_owned(),
11839 "abc1234".to_owned(),
11840 "fixture".to_owned(),
11841 Config::default(),
11842 );
11843 settled.status = RunStatus::Ready;
11844 let run_dir = home.join("runs").join(&settled.id);
11845 std::fs::create_dir_all(&run_dir).unwrap();
11846 std::fs::write(
11847 run_dir.join("run.json"),
11848 serde_json::to_string_pretty(&settled).unwrap(),
11849 )
11850 .unwrap();
11851 let questions = Questions::at(home.join("questions"));
11852 let mut question = ask::Question::new(
11853 settled.id.clone(),
11854 "review".to_owned(),
11855 "reviewer-1".to_owned(),
11856 "Continue?".to_owned(),
11857 String::new(),
11858 Vec::new(),
11859 );
11860 questions.put(&mut question).unwrap();
11861
11862 run_service_worker(
11863 &home,
11864 serde_json::to_value(ServiceWorker {
11865 opts,
11866 queue: queue.root().to_path_buf(),
11867 worktrees_root: worktrees,
11868 operation: "housekeeping".to_owned(),
11869 })
11870 .unwrap(),
11871 )
11872 .await
11873 .unwrap();
11874
11875 assert_eq!(
11876 questions.get(&question.id).unwrap().status,
11877 ask::QuestionStatus::Abandoned,
11878 "the independent housekeeping worker settles ended-run questions"
11879 );
11880 }
11881
11882 #[test]
11883 fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
11884 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
11885
11886 assert!(
11887 cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
11888 "never checked before: due at once"
11889 );
11890
11891 let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
11892 assert!(
11893 !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
11894 "well inside the interval: not due yet"
11895 );
11896
11897 let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
11898 assert!(
11899 !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
11900 "exactly at the edge: not yet due, same convention as `clean::due`"
11901 );
11902
11903 let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
11904 assert!(
11905 cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
11906 "past the interval: due again"
11907 );
11908 }
11909
11910 fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
11915 let config = dir.join("magi.toml");
11916 std::fs::write(
11922 &config,
11923 format!(
11924 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
11925 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
11926 cache_dir.display()
11927 ),
11928 )
11929 .unwrap();
11930 Opts {
11931 config: Some(config),
11932 repo: dir.join("repo"),
11933 ..Opts::default()
11934 }
11935 }
11936
11937 #[tokio::test]
11938 async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
11939 let dir = tempfile::tempdir().unwrap();
11940 let home = dir.path().join("home");
11941 let cache_dir = dir.path().join("cache");
11942 std::fs::create_dir_all(&cache_dir).unwrap();
11943 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
11944 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
11945
11946 let running = Stop::new();
11949 let mut last_checked = None;
11950 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
11951 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
11952 .await;
11953 assert_eq!(
11954 crate::disk::dir_size(&cache_dir),
11955 0,
11956 "over the cap on the first check ever: pruned at once, no idle queue required"
11957 );
11958 assert_eq!(last_checked, Some(t0));
11959
11960 std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
11962 let too_soon = t0 + jiff::SignedDuration::from_secs(1);
11963 maybe_prune_cache_between_runs(
11964 &opts.repo,
11965 &opts,
11966 &home,
11967 &running,
11968 &mut last_checked,
11969 too_soon,
11970 )
11971 .await;
11972 assert_eq!(
11973 crate::disk::dir_size(&cache_dir),
11974 10,
11975 "too soon since the last check: left alone rather than rescanned every call"
11976 );
11977 assert_eq!(
11978 last_checked,
11979 Some(t0),
11980 "an idle check does not reset the clock"
11981 );
11982
11983 let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
11985 maybe_prune_cache_between_runs(
11986 &opts.repo,
11987 &opts,
11988 &home,
11989 &running,
11990 &mut last_checked,
11991 due_again,
11992 )
11993 .await;
11994 assert_eq!(
11995 crate::disk::dir_size(&cache_dir),
11996 0,
11997 "due again: pruned back under the cap"
11998 );
11999 }
12000
12001 #[tokio::test]
12009 async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
12010 let dir = tempfile::tempdir().unwrap();
12011 let home = dir.path().join("home");
12012 let cache_dir = dir.path().join("cache");
12013 std::fs::create_dir_all(&cache_dir).unwrap();
12014 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
12015 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
12016
12017 let stop = Stop::new();
12018 stop.stop();
12019 assert!(
12020 !stop.finishing(),
12021 "no run is in flight at a between-runs boundary, so nothing else \
12022 would tell the operator this stop had not taken effect yet"
12023 );
12024
12025 let mut last_checked = None;
12026 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
12027 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
12028 .await;
12029 assert_eq!(
12030 crate::disk::dir_size(&cache_dir),
12031 10,
12032 "over its cap, and due for the first check ever, but a stop outranks \
12033 it: the cap is a standing policy the next start measures again"
12034 );
12035 assert_eq!(
12036 last_checked, None,
12037 "a check that never happened must not claim the interval"
12038 );
12039 }
12040
12041 #[tokio::test]
12044 async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
12045 let dir = tempfile::tempdir().unwrap();
12046 let cache_dir = dir.path().join("cache");
12047 std::fs::create_dir_all(&cache_dir).unwrap();
12048 std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
12049
12050 let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
12051 opts.poll = Duration::from_millis(20);
12052 opts.max_attempts = 1_000;
12053
12054 let queue = Queue::at(dir.path().join("queue"));
12055 for i in 0..128 {
12056 let mut task = Task::new(
12057 format!("queued work {i}"),
12058 format!("queued work {i}"),
12059 opts.repo.clone(),
12060 Source::Human,
12061 );
12062 queue.put(&mut task).unwrap();
12063 }
12064
12065 let home = dir.path().join("home");
12066 let worktrees = dir.path().join("wt");
12067 run_service_worker(
12068 &home,
12069 serde_json::to_value(ServiceWorker {
12070 opts,
12071 queue: queue.root().to_path_buf(),
12072 worktrees_root: worktrees,
12073 operation: "cache".to_owned(),
12074 })
12075 .unwrap(),
12076 )
12077 .await
12078 .unwrap();
12079 let after = queue.list();
12080 assert_eq!(after.len(), 128);
12081 assert!(
12082 after
12083 .iter()
12084 .all(|task| task.status.runnable() && task.attempts == 0)
12085 );
12086
12087 assert_eq!(
12088 crate::disk::dir_size(&cache_dir),
12089 0,
12090 "an oversized cache must not be left to grow unboundedly just because the \
12091 queue kept the loop busy the whole time"
12092 );
12093 }
12094
12095 #[test]
12096 fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
12097 let dir = tempfile::tempdir().unwrap();
12098 let queue = Queue::at(dir.path().join("queue"));
12099 let questions = Questions::at(dir.path().join("questions"));
12100 let mut task = task();
12101 queue.put(&mut task).unwrap();
12102
12103 let mut task_question = ask::Question::new(
12104 task.id.clone(),
12105 crate::conduct::NODE.to_owned(),
12106 "conduct".to_owned(),
12107 "Which backend?".to_owned(),
12108 String::new(),
12109 Vec::new(),
12110 );
12111 questions.put(&mut task_question).unwrap();
12112 task.block(vec![task_question.id.clone()], None);
12113 queue.put(&mut task).unwrap();
12114
12115 let mut run_question = ask::Question::new(
12116 "20260101-000000-run1".to_owned(),
12117 "review".to_owned(),
12118 "reviewer-1".to_owned(),
12119 "Run question".to_owned(),
12120 String::new(),
12121 Vec::new(),
12122 );
12123 questions.put(&mut run_question).unwrap();
12124
12125 let mut coincidental = ask::Question::new(
12130 task.id.clone(),
12131 "review".to_owned(),
12132 "reviewer-1".to_owned(),
12133 "Unrelated review question".to_owned(),
12134 String::new(),
12135 Vec::new(),
12136 );
12137 questions.put(&mut coincidental).unwrap();
12138
12139 reconcile_task_questions(&queue, &questions);
12140 assert!(questions.get(&task_question.id).unwrap().status.open());
12141 assert!(questions.get(&run_question.id).unwrap().status.open());
12142 assert!(questions.get(&coincidental.id).unwrap().status.open());
12143
12144 task.release();
12145 queue.put(&mut task).unwrap();
12146 reconcile_task_questions(&queue, &questions);
12147 assert_eq!(
12148 questions.get(&task_question.id).unwrap().status,
12149 ask::QuestionStatus::Abandoned
12150 );
12151 assert!(
12152 questions.get(&run_question.id).unwrap().status.open(),
12153 "run questions remain the run janitor's responsibility"
12154 );
12155 assert!(
12156 questions.get(&coincidental.id).unwrap().status.open(),
12157 "a non-conductor question must not be abandoned just because its \
12158 run id coincides with a task id"
12159 );
12160 }
12161
12162 #[test]
12163 fn a_freshly_started_running_task_is_never_stalled() {
12164 let dir = tempfile::tempdir().unwrap();
12165 let mut t = task();
12166 t.start("run-1".to_owned());
12167 assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
12170 }
12171
12172 #[test]
12173 fn a_long_running_task_with_no_live_daemon_is_stalled() {
12174 let dir = tempfile::tempdir().unwrap();
12175 let mut t = task();
12176 t.start("run-1".to_owned());
12177 t.updated_at = Timestamp::now()
12178 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
12179 assert!(is_stalled(&t, dir.path(), Timestamp::now()));
12180 assert_eq!(
12181 stalled_tasks(
12182 &Queue::at(dir.path().join("q")),
12183 dir.path(),
12184 Timestamp::now()
12185 )
12186 .len(),
12187 0,
12188 "the task was never written to this queue"
12189 );
12190 }
12191
12192 #[test]
12193 fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
12194 let dir = tempfile::tempdir().unwrap();
12195 let mut t = task();
12196 t.id = "20260903-080340-0167".to_owned();
12197 t.start("20260903-080619-01c2".to_owned());
12198 t.updated_at = Timestamp::now()
12199 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
12200
12201 let mut status = Status::new();
12202 status.current = vec![Current {
12203 worker: None,
12204 task: t.id.clone(),
12205 run: "20260903-080619-01c2".to_owned(),
12206 }];
12207 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12208
12209 assert!(
12210 !is_stalled(&t, dir.path(), Timestamp::now()),
12211 "a live daemon's own heartbeat rules out stalled, however long the task has run"
12212 );
12213 }
12214
12215 fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
12219 let path = queue.path_of(id);
12220 let body = std::fs::read_to_string(&path).unwrap();
12221 let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
12222 let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
12223 v["updated_at"] = serde_json::Value::String(old.to_string());
12224 std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
12225 }
12226
12227 #[test]
12228 fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
12229 let dir = tempfile::tempdir().unwrap();
12242 let queue = Queue::at(dir.path().join("queue"));
12243 let home = dir.path().join("home");
12244
12245 let mut t = task();
12246 t.id = "20260101-000001-lock".to_owned();
12247 t.start("run-1".to_owned());
12248 queue.put(&mut t).unwrap();
12249 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
12250 std::fs::write(
12251 dir.path().join("queue").join(format!("{}.lock", t.id)),
12252 "not a pid",
12253 )
12254 .unwrap();
12255
12256 let now = Timestamp::now();
12257 assert!(
12258 reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
12259 "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
12260 and reclaim must leave the task alone"
12261 );
12262 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
12263
12264 let stalled = stalled_tasks(&queue, &home, now);
12265 assert_eq!(
12266 stalled.len(),
12267 1,
12268 "reclaim's inability to claim it yet must not hide it from the conductor"
12269 );
12270 assert_eq!(stalled[0].id, t.id);
12271 }
12272
12273 #[test]
12274 fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
12275 let dir = tempfile::tempdir().unwrap();
12276 crate::run::set_home(dir.path().join("run-home"));
12277 let queue = Queue::at(dir.path().join("queue"));
12278 let home = dir.path().join("home");
12279 let questions = Questions::at(dir.path().join("questions"));
12280
12281 let mut t = task();
12282 t.id = "20260101-000003-dead".to_owned();
12283 t.start("missing-run".to_owned());
12284 queue.put(&mut t).unwrap();
12285 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
12286
12287 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
12290 assert_eq!(
12291 stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
12292 [&t.id]
12293 );
12294 assert_eq!(
12295 reclaim_orphaned_running(&queue, 2, &Default::default()),
12296 [t.id.clone()]
12297 );
12298 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12299
12300 crate::conduct::apply(
12303 &queue,
12304 &questions,
12305 &crate::conduct::Verdict {
12306 decisions: vec![crate::conduct::Decision {
12307 id: t.id.clone(),
12308 recovery: Some(crate::conduct::Recovery::Requeue),
12309 ..crate::conduct::Decision::default()
12310 }],
12311 },
12312 )
12313 .unwrap();
12314 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
12315 }
12316
12317 #[test]
12318 fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
12319 let dir = tempfile::tempdir().unwrap();
12320 let queue = Queue::at(dir.path().join("queue"));
12321 let home = dir.path().join("home");
12322
12323 let mut fresh = task();
12324 fresh.id = "20260101-000001-aaaa".to_owned();
12325 fresh.start("run-1".to_owned());
12326 queue.put(&mut fresh).unwrap();
12327
12328 let mut old = task();
12329 old.id = "20260101-000002-bbbb".to_owned();
12330 old.start("run-2".to_owned());
12331 queue.put(&mut old).unwrap();
12332 backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
12333
12334 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
12335 assert_eq!(stalled.len(), 1);
12336 assert_eq!(stalled[0].id, old.id);
12337 }
12338
12339 #[test]
12340 fn queued_and_finished_task_views_partition_by_status() {
12341 let dir = tempfile::tempdir().unwrap();
12342 let queue = Queue::at(dir.path().join("queue"));
12343
12344 let mut queued = task();
12345 queued.id = "20260101-000001-aaaa".to_owned();
12346 queue.put(&mut queued).unwrap();
12347
12348 let mut failed = task();
12349 failed.id = "20260101-000002-bbbb".to_owned();
12350 failed.start("run-1".to_owned());
12351 failed.fail("gate red", 5);
12352 queue.put(&mut failed).unwrap();
12353
12354 let mut held = task();
12355 held.id = "20260101-000003-cccc".to_owned();
12356 held.hold_machine(None);
12357 queue.put(&mut held).unwrap();
12358
12359 let mut running = task();
12360 running.id = "20260101-000004-dddd".to_owned();
12361 running.start("run-2".to_owned());
12362 queue.put(&mut running).unwrap();
12363
12364 let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
12365 assert_eq!(queued_ids, [queued.id.clone()]);
12366
12367 let mut finished_ids: Vec<String> =
12368 finished_tasks(&queue).into_iter().map(|t| t.id).collect();
12369 finished_ids.sort_unstable();
12370 let mut want = vec![failed.id.clone(), held.id.clone()];
12371 want.sort_unstable();
12372 assert_eq!(finished_ids, want);
12373 }
12374
12375 #[test]
12376 fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
12377 for short in [false, true] {
12378 let dir = tempfile::tempdir().unwrap();
12379 let queue = Queue::at(dir.path().join("queue"));
12380 let questions = ask::Questions::at(dir.path().join("questions"));
12381 let mut running = task();
12382 running.id = "20261013-192213-feb2".into();
12383 running.start("existing-run".into());
12384 queue.put(&mut running).unwrap();
12385 let mut middle = task();
12386 middle.id = "20261013-193611-ca5b".into();
12387 middle.block(
12388 vec![if short {
12389 "feb2".into()
12390 } else {
12391 running.id.clone()
12392 }],
12393 None,
12394 );
12395 queue.put(&mut middle).unwrap();
12396 let mut waiting = task();
12397 waiting.id = "20261013-202849-ee37".into();
12398 waiting.block(
12399 vec![if short {
12400 "ca5b".into()
12401 } else {
12402 middle.id.clone()
12403 }],
12404 Some("wait for implementation".into()),
12405 );
12406 queue.put(&mut waiting).unwrap();
12407 assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
12408 let inv = crate::blockers::Inventory::load(&queue, &questions);
12409 assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
12410 assert!(inv.stuck().is_empty());
12411 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12412 assert!(report.quarantined.is_empty());
12413 assert!(report.asked.is_empty());
12414 resolve_blockers(&queue, &questions);
12415 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12416 assert!(questions.list().is_empty());
12417 running.succeed(CompletionContext::new(
12420 CompletionActor::DaemonSettle,
12421 None,
12422 dir.path(),
12423 &running,
12424 ));
12425 queue.put(&mut running).unwrap();
12426 resolve_blockers(&queue, &questions);
12427 assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
12428 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12429 middle = queue.get(&middle.id).unwrap();
12430 middle.succeed(CompletionContext::new(
12431 CompletionActor::DaemonSettle,
12432 None,
12433 dir.path(),
12434 &middle,
12435 ));
12436 queue.put(&mut middle).unwrap();
12437 resolve_blockers(&queue, &questions);
12438 let after = queue.get(&waiting.id).unwrap();
12439 assert_eq!(after.status, TaskStatus::Queued);
12440 assert!(after.blocked_by.is_empty());
12441 assert_eq!(after.instruction, waiting.instruction);
12442 }
12443 }
12444
12445 #[test]
12446 fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
12447 for future_schema in [false, true] {
12448 let name = "20261013-193611-ca5b";
12449 let mut future = task();
12450 future.id = name.into();
12451 future.schema = crate::queue::SCHEMA + 1;
12452 let contents = if future_schema {
12453 serde_json::to_string(&future).unwrap()
12454 } else {
12455 "corrupt".into()
12456 };
12457 let dir = tempfile::tempdir().unwrap();
12458 let queue = Queue::at(dir.path().join("queue"));
12459 let questions = ask::Questions::at(dir.path().join("questions"));
12460 let mut waiting = task();
12461 waiting.id = "20261013-202849-ee37".into();
12462 waiting.block(vec!["ca5b".into()], None);
12463 queue.put(&mut waiting).unwrap();
12464 std::fs::write(queue.path_of(name), contents).unwrap();
12465 assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
12466 assert!(
12467 crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
12468 );
12469 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12470 assert!(report.asked.is_empty());
12471 resolve_blockers(&queue, &questions);
12472 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12473 assert!(questions.list().is_empty());
12474 }
12475 let dir = tempfile::tempdir().unwrap();
12476 let queue = Queue::at(dir.path().join("queue"));
12477 let questions = ask::Questions::at(dir.path().join("questions"));
12478 let mut waiting = task();
12479 waiting.id = "20261013-202849-ee37".into();
12480 waiting.block(vec!["ca5b".into()], None);
12481 queue.put(&mut waiting).unwrap();
12482 let mut done = task();
12483 done.id = "20261013-193611-ca5b".into();
12484 done.succeed(CompletionContext::new(
12485 CompletionActor::Cli,
12486 None,
12487 dir.path(),
12488 &done,
12489 ));
12490 queue.put(&mut done).unwrap();
12491 std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
12494 assert!(queue.get("ca5b").is_err());
12495 assert_eq!(
12496 crate::queue::dependency(&queue, &questions, "ca5b"),
12497 crate::queue::Dependency::Ambiguous
12498 );
12499 resolve_blockers(&queue, &questions);
12500 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12501 assert!(report.asked.is_empty());
12502 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12503 assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
12504 }
12505
12506 #[test]
12507 fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
12508 for held in [false, true] {
12509 for question in [false, true] {
12510 for reference in ["ca5b", "20261013-193611-ca5b"] {
12511 let dir = tempfile::tempdir().unwrap();
12512 let queue = Queue::at(dir.path().join("queue"));
12513 let questions = ask::Questions::at(dir.path().join("questions"));
12514 let mut prerequisite = task();
12515 prerequisite.id = "20261013-193611-ca5b".into();
12516 prerequisite.start("existing-run".into());
12517 queue.put(&mut prerequisite).unwrap();
12518 let mut waiting = task();
12519 waiting.id = "20261013-202849-ee37".into();
12520 if held {
12521 waiting.hold_machine(Some("waiting for separate consent".into()));
12522 }
12523 queue.put(&mut waiting).unwrap();
12524 let reason = "Deleting saved data requires separate owner consent";
12525 crate::conduct::apply(
12526 &queue,
12527 &questions,
12528 &crate::conduct::Verdict {
12529 decisions: vec![crate::conduct::Decision {
12530 id: waiting.id.clone(),
12531 blocked_by: vec![reference.into()],
12532 question: question.then(|| "May the saved data be deleted?".into()),
12533 recovery: (!question).then_some(crate::conduct::Recovery::Hold),
12534 reason: Some(reason.into()),
12535 ..crate::conduct::Decision::default()
12536 }],
12537 },
12538 )
12539 .unwrap();
12540 let before = queue.get(&waiting.id).unwrap();
12541 if question {
12542 assert_eq!(before.status, TaskStatus::Blocked);
12543 let q = questions.get(&before.blocked_by[0]).unwrap();
12544 assert_eq!(q.summary, "May the saved data be deleted?");
12545 assert!(q.status.open());
12546 } else {
12547 assert_eq!(before.status, TaskStatus::Held);
12548 let recorded_reason = before.hold_reason.as_deref().unwrap();
12549 assert!(recorded_reason.starts_with(reason));
12550 if held {
12551 assert!(recorded_reason.contains("waiting for separate consent"));
12552 }
12553 }
12554 prerequisite.succeed(CompletionContext::new(
12555 CompletionActor::DaemonSettle,
12556 None,
12557 dir.path(),
12558 &prerequisite,
12559 ));
12560 queue.put(&mut prerequisite).unwrap();
12561 resolve_blockers(&queue, &questions);
12562 let after = queue.get(&waiting.id).unwrap();
12563 assert_eq!(after.status, before.status);
12564 assert_eq!(after.blocked_by, before.blocked_by);
12565 assert_eq!(after.hold_reason, before.hold_reason);
12566 assert_eq!(after.instruction, waiting.instruction);
12567 if question {
12568 assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
12569 }
12570 assert!(
12571 queue.next_runnable().is_none(),
12572 "dependency completion is not consent"
12573 );
12574 }
12575 }
12576 }
12577 }
12578
12579 #[test]
12580 fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
12581 let dir = tempfile::tempdir().unwrap();
12582 let queue = Queue::at(dir.path().join("queue"));
12583 let questions = ask::Questions::at(dir.path().join("questions"));
12584
12585 let mut dep = task();
12586 dep.id = "20260101-000001-dep0".to_owned();
12587 dep.succeed(CompletionContext::new(
12588 CompletionActor::DaemonSettle,
12589 None,
12590 dir.path(),
12591 &dep,
12592 ));
12593 queue.put(&mut dep).unwrap();
12594
12595 let mut still_going = task();
12596 still_going.id = "20260101-000002-dep1".to_owned();
12597 queue.put(&mut still_going).unwrap();
12598
12599 let mut blocked = task();
12600 blocked.id = "20260101-000003-main".to_owned();
12601 blocked.block(
12602 vec![dep.id.clone(), still_going.id.clone()],
12603 Some("waits on both".to_owned()),
12604 );
12605 queue.put(&mut blocked).unwrap();
12606
12607 resolve_blockers(&queue, &questions);
12608
12609 let after = queue.get(&blocked.id).unwrap();
12610 assert_eq!(
12611 after.status,
12612 TaskStatus::Blocked,
12613 "one dependency is still outstanding"
12614 );
12615 assert_eq!(after.blocked_by, [still_going.id.clone()]);
12616 }
12617
12618 #[test]
12619 fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
12620 let dir = tempfile::tempdir().unwrap();
12621 let queue = Queue::at(dir.path().join("queue"));
12622 let questions = ask::Questions::at(dir.path().join("questions"));
12623
12624 let mut q = crate::ask::Question::new(
12625 "20260101-000001-main".to_owned(),
12626 crate::conduct::NODE.to_owned(),
12627 "conduct".to_owned(),
12628 "Which backend?".to_owned(),
12629 String::new(),
12630 Vec::new(),
12631 );
12632 questions.put(&mut q).unwrap();
12633 q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
12634 .unwrap();
12635 questions.put(&mut q).unwrap();
12636
12637 let mut blocked = task();
12638 blocked.id = "20260101-000001-main".to_owned();
12639 blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
12640 queue.put(&mut blocked).unwrap();
12641
12642 resolve_blockers(&queue, &questions);
12643
12644 let after = queue.get(&blocked.id).unwrap();
12645 assert_eq!(
12646 after.status,
12647 TaskStatus::Queued,
12648 "the only blocker resolved"
12649 );
12650 assert_eq!(after.answers.len(), 1);
12651 assert_eq!(after.answers[0].question, "Which backend?");
12652 assert_eq!(after.answers[0].answer, "SQLite");
12653
12654 let instruction = instruction_for(&after);
12656 assert!(instruction.contains("Which backend?"));
12657 assert!(instruction.contains("SQLite"));
12658 }
12659
12660 #[test]
12661 fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
12662 let dir = tempfile::tempdir().unwrap();
12663 let queue = Queue::at(dir.path().join("queue"));
12664 let questions = ask::Questions::at(dir.path().join("questions"));
12665
12666 let mut q = crate::ask::Question::new(
12667 "20260101-000001-main".to_owned(),
12668 crate::conduct::NODE.to_owned(),
12669 "conduct".to_owned(),
12670 "Is the setup done?".to_owned(),
12671 String::new(),
12672 Vec::new(),
12673 );
12674 q.abandon("no answer within 60s of asking");
12675 questions.put(&mut q).unwrap();
12676
12677 let mut blocked = task();
12678 blocked.id = "20260101-000001-main".to_owned();
12679 blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
12680 queue.put(&mut blocked).unwrap();
12681
12682 resolve_blockers(&queue, &questions);
12683
12684 let after = queue.get(&blocked.id).unwrap();
12685 assert_eq!(
12686 after.status,
12687 TaskStatus::Held,
12688 "never left blocked on nothing"
12689 );
12690 assert!(!after.operator_held(), "a machine hold, for triage");
12691 assert!(
12692 after
12693 .hold_reason
12694 .as_deref()
12695 .unwrap_or_default()
12696 .contains("went unanswered")
12697 );
12698 }
12699
12700 #[test]
12701 fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
12702 let dir = tempfile::tempdir().unwrap();
12708 let queue = Queue::at(dir.path().join("queue"));
12709 let questions = ask::Questions::at(dir.path().join("questions"));
12710
12711 let mut q = crate::ask::Question::new(
12712 "20260101-000001-main".to_owned(),
12713 crate::conduct::NODE.to_owned(),
12714 "conduct".to_owned(),
12715 "How should this be handled?".to_owned(),
12716 String::new(),
12717 Vec::new(),
12718 );
12719 questions.put(&mut q).unwrap();
12720 q.answer(crate::ask::Answer::Text(
12721 "leave it held, a human will look at it later".to_owned(),
12722 ))
12723 .unwrap();
12724 questions.put(&mut q).unwrap();
12725
12726 let mut held = task();
12727 held.id = "20260101-000001-main".to_owned();
12728 held.hold_machine(Some("out of attempts".to_owned()));
12729 held.block(vec![q.id.clone()], Some("what now?".to_owned()));
12730 queue.put(&mut held).unwrap();
12731
12732 resolve_blockers(&queue, &questions);
12733
12734 let after = queue.get(&held.id).unwrap();
12735 assert_eq!(after.status, TaskStatus::Held);
12736 assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
12737 assert_eq!(
12738 after.answers[0].answer,
12739 "leave it held, a human will look at it later"
12740 );
12741 }
12742
12743 #[test]
12744 fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
12745 let dir = tempfile::tempdir().unwrap();
12746 let queue = Queue::at(dir.path().join("queue"));
12747 let questions = ask::Questions::at(dir.path().join("questions"));
12748 let mut dep = task();
12749 dep.id = "20260101-000001-gone".to_owned();
12750 queue.put(&mut dep).unwrap();
12751 let mut blocked = task();
12752 blocked.id = "20260101-000003-main".to_owned();
12753 blocked.block(vec![dep.id.clone()], None);
12754 queue.put(&mut blocked).unwrap();
12755
12756 let claim = queue.claim(&blocked.id).unwrap();
12758 queue.remove(&dep.id, false, &questions).unwrap();
12759 drop(claim);
12760 resolve_blockers(&queue, &questions);
12761
12762 let after = queue.get(&blocked.id).unwrap();
12763 assert_eq!(after.status, TaskStatus::Queued);
12764 assert!(after.blocked_by.is_empty());
12765 }
12766
12767 #[test]
12768 fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
12769 let dir = tempfile::tempdir().unwrap();
12775 let queue = Queue::at(dir.path().join("queue"));
12776 let questions = ask::Questions::at(dir.path().join("questions"));
12777
12778 let mut still_going = task();
12779 still_going.id = "20260101-000002-dep1".to_owned();
12780 queue.put(&mut still_going).unwrap();
12781
12782 let mut blocked = task();
12783 blocked.id = "20260101-000003-main".to_owned();
12784 blocked.block(
12785 vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
12786 Some("waits on both".to_owned()),
12787 );
12788 queue.put(&mut blocked).unwrap();
12789
12790 resolve_blockers(&queue, &questions);
12791
12792 let after = queue.get(&blocked.id).unwrap();
12793 assert_eq!(
12794 after.status,
12795 TaskStatus::Held,
12796 "a missing dependency must not leave the task blocked forever"
12797 );
12798 assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
12799 assert!(after.blocked_by.is_empty());
12800 let reason = after.hold_reason.as_deref().unwrap_or_default();
12801 assert!(
12802 reason.contains("20260101-000001-gone"),
12803 "the missing id must be named so an operator can tell what happened: {reason}"
12804 );
12805 assert!(
12806 reason.contains(&still_going.id),
12807 "the still-valid dependency must not silently vanish from the record: {reason}"
12808 );
12809 }
12810
12811 #[test]
12812 fn instruction_for_is_unchanged_without_any_answers() {
12813 let t = task();
12814 assert_eq!(instruction_for(&t), t.instruction);
12815 }
12816
12817 #[test]
12818 fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
12819 let dir = tempfile::tempdir().unwrap();
12820 let q = Queue::at(dir.path().join("queue"));
12821 let src = dir.path().join("shot.png");
12822 std::fs::write(&src, "x").unwrap();
12823 let mut t = task();
12824 q.attach(&mut t, &[src]).unwrap();
12825 let paths = task_attachments(&q, &t).unwrap();
12826 assert_eq!(paths.len(), 1);
12827 assert!(paths[0].is_absolute() && paths[0].is_file());
12828 std::fs::remove_file(&paths[0]).unwrap();
12829 let err = task_attachments(&q, &t).unwrap_err().to_string();
12830 assert!(err.contains("shot.png"), "{err}");
12831 }
12832
12833 #[tokio::test]
12834 async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
12835 let dir = tempfile::tempdir().unwrap();
12836 let queue_path = dir.path().join("queue");
12837 let queue = Queue::at(queue_path.clone());
12838 let mut t = task();
12839 t.source = Source::Agent {
12840 run: "originating-chat".into(),
12841 node: crate::queue::CHAT_NODE.into(),
12842 };
12843 let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
12844 stage: "config-fetch",
12845 target: "origin/main".into(),
12846 });
12847 record_config_failure(&mut t, &fetch);
12848 t.hold_machine(Some(format!("{fetch:#}")));
12849 let fetch_key = t.chat_notice_due().unwrap();
12850 t.chat_notices.push(fetch_key.clone());
12851 queue.put(&mut t).unwrap();
12852
12853 let queue = Queue::at(queue_path);
12854 let mut t = queue.get(&t.id).unwrap();
12855 let a = dir.path().join("a.toml");
12856 let b = dir.path().join("b.toml");
12857 for (path, text, new_cause) in [
12858 (&a, "[graph", true),
12859 (&a, "[verify", false),
12860 (&a, "[graph]\nimplementers = 'invalid-type'", true),
12861 (&b, "[graph]\nimplementers = 'invalid-type'", true),
12862 ] {
12863 t.release_operator("test", None);
12864 std::fs::write(path, text).unwrap();
12865 let error = Config::discover_fetched(dir.path(), Some(path))
12866 .await
12867 .unwrap_err();
12868 record_config_failure(&mut t, &error);
12869 t.hold_machine(Some(format!("{error:#}")));
12870 let due = t.chat_notice_due();
12871 assert_eq!(due.is_some(), new_cause, "{error:#}");
12872 if let Some(key) = due {
12873 assert_ne!(key, fetch_key);
12874 t.chat_notices.push(key);
12875 }
12876 }
12877 t.succeed(CompletionContext::new(
12878 CompletionActor::DaemonSettle,
12879 None,
12880 dir.path(),
12881 &t,
12882 ));
12883 assert_eq!(
12884 t.chat_notice_due(),
12885 Some(format!(
12886 "done:{}",
12887 t.completion_history.last().unwrap().occurrence
12888 ))
12889 );
12890 }
12891
12892 #[test]
12893 fn different_missing_attachments_have_distinct_persisted_notice_causes() {
12894 let dir = tempfile::tempdir().unwrap();
12895 let queue_path = dir.path().join("queue");
12896 let queue = Queue::at(queue_path.clone());
12897 let mut t = task();
12898 t.source = crate::queue::Source::Agent {
12899 run: "originating-chat".into(),
12900 node: crate::queue::CHAT_NODE.into(),
12901 };
12902 let a = dir.path().join("a.png");
12903 let b = dir.path().join("b.png");
12904 std::fs::write(&a, "a").unwrap();
12905 std::fs::write(&b, "b").unwrap();
12906 queue.attach(&mut t, &[a, b]).unwrap();
12907 let paths = task_attachments(&queue, &t).unwrap();
12908 for path in &paths {
12909 std::fs::remove_file(path).unwrap();
12910 }
12911 let missing = task_attachments(&queue, &t).unwrap_err();
12912 t.attempts += 1;
12913 let reason = missing.to_string();
12914 t.fail_startup_target("startup-attachments", missing.name, reason, 1);
12915 let first = t.chat_notice_due().expect("first attachment notice");
12916 t.chat_notices.push(first.clone());
12917 queue.put(&mut t).unwrap();
12918
12919 let queue = Queue::at(queue_path.clone());
12920 let mut t = queue.get(&t.id).unwrap();
12921 assert!(t.chat_notice_due().is_none(), "restart does not replay");
12922 t.release_operator("test", None);
12923 t.attempts += 1;
12924 let missing = task_attachments(&queue, &t).unwrap_err();
12925 t.fail_startup_target(
12926 "startup-attachments",
12927 missing.name,
12928 "same missing attachment with regenerated wording",
12929 1,
12930 );
12931 assert!(t.chat_notice_due().is_none(), "same object stays quiet");
12932
12933 std::fs::write(&paths[0], "restored").unwrap();
12934 t.release_operator("test", None);
12935 t.attempts += 1;
12936 let missing = task_attachments(&queue, &t).unwrap_err();
12937 let reason = missing.to_string();
12938 t.fail_startup_target("startup-attachments", missing.name, reason, 1);
12939 let second = t
12940 .chat_notice_due()
12941 .expect("different attachment must notify");
12942 assert_ne!(first, second);
12943 assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
12944 }
12945
12946 #[test]
12947 fn resumed_instruction_is_unchanged_without_any_answers() {
12948 let t = task();
12949 assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
12950 }
12951
12952 #[test]
12953 fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
12954 let mut t = task();
12955 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
12956 let old = t.instruction.clone();
12960
12961 let refreshed = resumed_instruction(&old, &t);
12962 assert!(refreshed.starts_with(&old), "the original text is kept");
12963 assert!(refreshed.contains("Which backend?"));
12964 assert!(refreshed.contains("SQLite"));
12965 }
12966
12967 #[test]
12968 fn resumed_instruction_keeps_an_original_answers_heading() {
12969 let mut t = task();
12970 t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
12971 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
12972
12973 let refreshed = resumed_instruction(&t.instruction, &t);
12974
12975 assert!(
12976 refreshed.starts_with(&t.instruction),
12977 "an answers heading in the original instruction is not the appended block"
12978 );
12979 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
12980 assert!(refreshed.contains("Which backend?"));
12981 assert!(refreshed.contains("SQLite"));
12982
12983 let repeated = resumed_instruction(&refreshed, &t);
12984 assert_eq!(
12985 repeated, refreshed,
12986 "only the final appended block is refreshed"
12987 );
12988 }
12989
12990 #[test]
12991 fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
12992 let mut t = task();
12993 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
12994
12995 let once = resumed_instruction(&t.instruction, &t);
12999 let twice = resumed_instruction(&once, &t);
13000 assert_eq!(once, twice);
13001 assert_eq!(once.matches("Which backend?").count(), 1);
13002
13003 t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
13005 let refreshed = resumed_instruction(&once, &t);
13006 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
13007 assert!(refreshed.contains("Which backend?"));
13008 assert!(refreshed.contains("Which cache?"));
13009 }
13010
13011 #[test]
13012 fn prepare_instruction_covers_all_three_starters() {
13013 let mut t = task();
13014 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
13015
13016 assert_eq!(
13019 prepare_instruction(&Starter::Start, None, &t),
13020 Some(instruction_for(&t))
13021 );
13022
13023 let old = t.instruction.clone();
13026 assert_eq!(
13027 prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
13028 Some(resumed_instruction(&old, &t))
13029 );
13030
13031 assert_eq!(
13035 prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
13036 None
13037 );
13038 }
13039
13040 #[test]
13041 fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
13042 assert_eq!(
13043 choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
13044 Starter::Review("magi/eba2/A".to_owned())
13045 );
13046 }
13047
13048 #[test]
13049 fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
13050 assert_eq!(
13051 choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
13052 Starter::Start,
13053 "a vanished review branch must not fall back to resuming the old run either"
13054 );
13055 }
13056
13057 #[test]
13058 fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
13059 let mut t = task();
13060 t.start("old-run".to_owned());
13061 t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
13062 t.release();
13063 let branch = t.review_branch.take();
13064 assert_eq!(
13065 choose_starter(branch.as_deref(), true, Some("old-run")),
13066 Starter::Review("magi/eba2/A".to_owned()),
13067 "a review wins over resuming the old run"
13068 );
13069 }
13070
13071 #[test]
13072 fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
13073 assert_eq!(
13074 choose_starter(None, false, Some("some-run")),
13075 Starter::Resume("some-run".to_owned())
13076 );
13077 assert_eq!(choose_starter(None, false, None), Starter::Start);
13078 }
13079
13080 #[test]
13081 fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
13082 let mut released = task();
13083 released.start("stalled-run".to_owned());
13084 released.requeue();
13085 let unfinished = (!released.fresh_start)
13086 .then(|| Some("stalled-run".to_owned()))
13087 .flatten();
13088 assert_eq!(
13089 choose_starter(None, false, unfinished.as_deref()),
13090 Starter::Start,
13091 "release keeps run history but must not resume it"
13092 );
13093 assert_eq!(released.runs, ["stalled-run"]);
13094 }
13095
13096 #[test]
13097 fn landing_hold_receipt_survives_release_retry_and_checkpoint_removal() {
13098 let dir = tempfile::tempdir().unwrap();
13099 let queue = Queue::at(dir.path().join("queue"));
13100 let mut state = run_state(RunStatus::Blocked);
13101 state.merge_decision = Some(crate::merge_decision::Decision {
13102 question: "hold-inquiry".into(),
13103 target: crate::merge_decision::Target {
13104 pr: "https://example.test/pull/1".into(),
13105 head: "reviewed-head".into(),
13106 language: "en".into(),
13107 },
13108 choice: land::HOLD.into(),
13109 closed: false,
13110 replacement_run: None,
13111 replacement_pr: None,
13112 });
13113 let mut t = task();
13114 t.start(state.id.clone());
13115 settle_and_diagnose(
13116 &mut t,
13117 Verdict {
13118 status: RunStatus::Blocked,
13119 left_pr: true,
13120 quota_hit: false,
13121 parked: false,
13122 no_viable_candidates: false,
13123 },
13124 "held",
13125 2,
13126 &state,
13127 );
13128 queue.put(&mut t).unwrap();
13129 t.release_operator("chat", None);
13130 t.edit("revised".into(), "revised instruction".into())
13131 .unwrap();
13132 queue.put(&mut t).unwrap();
13133 drop(state);
13134 assert_eq!(
13135 queue
13136 .get(&t.id)
13137 .unwrap()
13138 .decision_effects
13139 .get("hold-inquiry"),
13140 Some(&format!("decision: {}", land::HOLD))
13141 );
13142 }
13143
13144 fn stopped_public_run(status: RunStatus) -> RunState {
13145 let mut state = run_state(status);
13146 state.driver_exited = true;
13147 state.config.graph.land = true;
13148 state.config.graph.review_rounds = 1;
13149 state.reviews = vec![review_round(1)];
13150 state.merge = Some(crate::run::MergeOutcome {
13151 mode: MergeMode::Pr,
13152 ok: false,
13153 detail: "landing stopped".into(),
13154 empty: false,
13155 });
13156 state.pr = Some(crate::run::PrRecord {
13157 url: "https://example.test/pull/1".into(),
13158 number: 1,
13159 state: "open".into(),
13160 checks: "red".into(),
13161 round: 1,
13162 rounds: 1,
13163 red_at_merge: Vec::new(),
13164 });
13165 state
13166 }
13167
13168 #[test]
13169 fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
13170 for status in [RunStatus::Blocked, RunStatus::Gating] {
13171 let home = tempfile::tempdir().unwrap();
13172 let mut state = stopped_public_run(status);
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!(
13192 crate::resume::validate(home.path(), &state.id).unwrap().id,
13193 state.id
13194 );
13195 let queue = Queue::at(home.path().join("queue"));
13196 let mut controlled = Task::new(
13197 "resume land".into(),
13198 state.instruction.clone(),
13199 state.repo.clone(),
13200 Source::Agent {
13201 run: "talk".into(),
13202 node: crate::queue::CHAT_NODE.into(),
13203 },
13204 );
13205 controlled.runs.push(state.id.clone());
13206 controlled.hold_machine(Some("land stopped".into()));
13207 queue.put(&mut controlled).unwrap();
13208 let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
13209 assert_eq!(resumed.status, TaskStatus::Queued);
13210 assert_eq!(
13211 resumed.resume_override.unwrap().pinned_run,
13212 Some(state.id.clone())
13213 );
13214 assert_eq!(resumed.attempts, 0);
13215 }
13216 }
13217
13218 #[test]
13219 fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
13220 for review_rounds in [0, 1] {
13221 let home = tempfile::tempdir().unwrap();
13222 let mut state = run_state(RunStatus::Blocked);
13223 state.config.graph.review_rounds = review_rounds;
13224 if review_rounds > 0 {
13225 let mut review = review_round(1);
13226 review.clean = true;
13227 state.reviews = vec![review];
13228 }
13229 state.gate_ran = true;
13230 state.gate = vec![crate::run::CommandOutcome {
13231 command: "verify".into(),
13232 code: Some(1),
13233 output_tail: "gate failed after repair budget exhausted".into(),
13234 duration_ms: 0,
13235 resource_blocked: false,
13236 }];
13237 state.save_under(home.path()).unwrap();
13238 assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
13239 assert!(exhausted_review_budget(&state));
13240 let mut task = held_task_with(&state.id);
13241 task.release();
13242 assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
13243 let question = action_question(&state.id, resume_action(&state.id));
13244 assert_ne!(
13245 decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
13246 state.clone()
13247 )),
13248 ActionDecision::Resume(state.id.clone())
13249 );
13250 let error = crate::resume::validate(home.path(), &state.id)
13251 .unwrap_err()
13252 .to_string();
13253 assert!(!error.contains("review budget exhausted"), "{error}");
13254 assert!(
13255 error.contains(if review_rounds == 0 {
13256 "review is disabled"
13257 } else {
13258 "gate already ran"
13259 }),
13260 "{error}"
13261 );
13262
13263 state.gate_ran = false;
13265 state.gate.clear();
13266 assert!(!exhausted_review_budget(&state));
13267 assert_eq!(
13268 unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
13269 Some(state.id)
13270 );
13271 }
13272 }
13273
13274 #[test]
13275 fn resource_blocked_verification_resumes_the_same_run() {
13276 for (kind, stage) in [
13277 ("cache", "clean"),
13278 ("coordination", "clean"),
13279 ("cache", "review-e2e"),
13280 ("coordination", "no-reviews"),
13281 ("coordination", "handoff"),
13282 ] {
13283 let home = tempfile::tempdir().unwrap();
13284 let mut state = run_state(RunStatus::Blocked);
13285 state.config.graph.review_rounds = 1;
13286 let mut review = review_round(1);
13287 review.clean = true;
13288 state.reviews = vec![review];
13289 if stage == "review-e2e" {
13290 let review = &mut state.reviews[0];
13291 review.clean = false;
13292 review.blocking = 1;
13293 review.e2e = vec![crate::run::CommandOutcome {
13294 command: "verify".into(),
13295 code: None,
13296 output_tail: "resource wait expired".into(),
13297 duration_ms: 0,
13298 resource_blocked: true,
13299 }];
13300 } else if stage == "no-reviews" {
13301 state.config.graph.review_rounds = 0;
13302 state.reviews.clear();
13303 } else if stage == "handoff" {
13304 let review = &mut state.reviews[0];
13307 review.clean = false;
13308 review.blocking = 1;
13309 review.e2e = vec![crate::run::CommandOutcome {
13310 command: "verify".into(),
13311 code: Some(0),
13312 output_tail: String::new(),
13313 duration_ms: 0,
13314 resource_blocked: false,
13315 }];
13316 }
13317 state.gate_ran = false;
13318 state.resource_block = Some(crate::run::ResourceBlock {
13319 cause: crate::run::ResourceBlockCause::Other,
13320 node: if stage == "review-e2e" {
13321 "review"
13322 } else {
13323 "gate"
13324 }
13325 .into(),
13326 kind: kind.into(),
13327 detail: "resource wait expired".into(),
13328 at: jiff::Timestamp::now(),
13329 });
13330 state.save_under(home.path()).unwrap();
13331 assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
13332 assert!(!exhausted_review_budget(&state));
13333 let mut task = held_task_with(&state.id);
13334 task.release();
13335 let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
13336 assert_eq!(
13337 choose_starter(None, false, unfinished.as_deref()),
13338 Starter::Resume(state.id.clone())
13339 );
13340 let question = action_question(&state.id, resume_action(&state.id));
13341 assert_eq!(
13342 decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
13343 state.clone()
13344 )),
13345 ActionDecision::Resume(state.id.clone())
13346 );
13347 assert_eq!(
13348 crate::resume::validate(home.path(), &state.id).unwrap().id,
13349 state.id
13350 );
13351 let queue = Queue::at(home.path().join("queue"));
13352 let mut controlled = Task::new(
13353 "resume verification".into(),
13354 state.instruction.clone(),
13355 state.repo.clone(),
13356 Source::Agent {
13357 run: "talk".into(),
13358 node: crate::queue::CHAT_NODE.into(),
13359 },
13360 );
13361 controlled.runs.push(state.id.clone());
13362 controlled.hold_machine(Some("verification resource unavailable".into()));
13363 queue.put(&mut controlled).unwrap();
13364 let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
13365 assert_eq!(resumed.status, TaskStatus::Queued);
13366 assert_eq!(
13367 resumed.resume_override.unwrap().pinned_run,
13368 Some(state.id.clone())
13369 );
13370 assert_eq!(resumed.attempts, 0);
13371
13372 state.config.graph.review_rounds = 1;
13374 let mut unresolved = review_round(1);
13375 unresolved.blocking = 1;
13376 state.reviews = vec![unresolved];
13377 state.resource_block = None;
13378 state.save_under(home.path()).unwrap();
13379 assert!(exhausted_review_budget(&state));
13380 assert!(crate::resume::validate(home.path(), &state.id).is_err());
13381 }
13382 }
13383
13384 #[tokio::test]
13385 async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
13386 if !crate::standalone_test(
13387 "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
13388 ) {
13389 return;
13390 }
13391 let home = tempfile::tempdir().unwrap();
13392 let mut owner = stopped_public_run(RunStatus::Blocked);
13393 owner.save_under(home.path()).unwrap();
13394 let history = vec![owner.id.clone()];
13395 let repo = owner.repo.clone();
13396 let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
13397 let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
13398 let initial =
13399 std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
13400 assert!(
13401 initial.is_pending(),
13402 "a busy record must not hold or resume the task"
13403 );
13404 owner.retired_to = Some("20260101-000001-bbbb".into());
13405 owner.save_under(home.path()).unwrap();
13406 drop(lock);
13407 let result = tokio::time::timeout(Duration::from_secs(10), lookup)
13408 .await
13409 .expect("ownership lock released")
13410 .expect("read settled owner");
13411 assert!(
13412 result.is_none(),
13413 "the retired owner must not be resumed from a stale read"
13414 );
13415 }
13416
13417 #[tokio::test]
13418 async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
13419 if !crate::standalone_test(
13420 "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
13421 ) {
13422 return;
13423 }
13424 let home = tempfile::tempdir().unwrap();
13425 let mut owner = stopped_public_run(RunStatus::Blocked);
13426 let repo = tempfile::tempdir().unwrap();
13427 crate::git::git(repo.path(), &["init"]).await.unwrap();
13428 owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
13429 owner.id = "20260101-000000-aaaa".into();
13430 owner.save_under(home.path()).unwrap();
13431 let mut successor = run_state(RunStatus::Blocked);
13432 successor.id = "20260101-000001-bbbb".into();
13433 successor.save_under(home.path()).unwrap();
13434 let runs = vec![owner.id.clone(), successor.id.clone()];
13435 assert_eq!(
13436 public_resume_owner(home.path(), &runs, &owner.repo)
13437 .await
13438 .unwrap()
13439 .unwrap()
13440 .id,
13441 owner.id
13442 );
13443 let subdir = owner.repo.join("nested");
13444 std::fs::create_dir(&subdir).unwrap();
13445 assert_eq!(
13446 public_resume_owner(home.path(), &runs, &subdir)
13447 .await
13448 .unwrap()
13449 .unwrap()
13450 .id,
13451 owner.id
13452 );
13453 #[cfg(unix)]
13454 {
13455 let alias = home.path().join("repo-alias");
13456 std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
13457 assert_eq!(
13458 public_resume_owner(home.path(), &runs, &alias.join("nested"))
13459 .await
13460 .unwrap()
13461 .unwrap()
13462 .id,
13463 owner.id
13464 );
13465 }
13466 let different = tempfile::tempdir().unwrap();
13467 crate::git::git(different.path(), &["init"]).await.unwrap();
13468 assert!(
13469 public_resume_owner(home.path(), &runs, different.path())
13470 .await
13471 .is_err()
13472 );
13473 std::fs::remove_file(
13474 home.path()
13475 .join("runs")
13476 .join(&successor.id)
13477 .join("run.json"),
13478 )
13479 .unwrap();
13480 assert!(
13481 public_resume_owner(home.path(), &runs, &owner.repo)
13482 .await
13483 .is_err()
13484 );
13485 }
13486
13487 #[test]
13488 fn an_ordinary_release_keeps_a_resumable_run_available() {
13489 let mut released = task();
13490 released.start("stalled-run".to_owned());
13491 released.release();
13492 let unfinished = (!released.fresh_start)
13493 .then(|| Some("stalled-run".to_owned()))
13494 .flatten();
13495 assert_eq!(
13496 choose_starter(None, false, unfinished.as_deref()),
13497 Starter::Resume("stalled-run".to_owned()),
13498 "manual release must preserve the normal resume path"
13499 );
13500 }
13501
13502 #[test]
13503 fn resume_refusals_explain_admission_without_changing_task_or_run() {
13504 use crate::handover::{ResumeRefusal, resume_refusal_under};
13505 let home = tempfile::tempdir().unwrap();
13506 let mut exhausted = run_state(RunStatus::Blocked);
13507 exhausted.driver_exited = true;
13508 exhausted.config.graph.review_rounds = 3;
13509 exhausted.reviews = (1..=3).map(review_round).collect();
13510 for refusal in [
13511 ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
13512 ResumeRefusal::Status(RunStatus::Ready),
13513 ResumeRefusal::Released("20261022-000000-aaaa".into()),
13514 ResumeRefusal::Retired("retirement-successor".into()),
13515 ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
13516 ] {
13517 let mut state = exhausted.clone();
13518 let expected = match refusal {
13519 ResumeRefusal::Status(_) => {
13520 state.status = RunStatus::Ready;
13521 "status `ready`"
13522 }
13523 ResumeRefusal::Released(ref target) => {
13524 state.released_to = Some(target.clone());
13525 "execution was released"
13526 }
13527 ResumeRefusal::Retired(ref target) => {
13528 state.retired_to = Some(target.clone());
13529 "execution was retired"
13530 }
13531 ResumeRefusal::OwnershipTransferred(ref target) => {
13532 state.pr_taken_over_by = Some(target.clone());
13533 "PR ownership was transferred"
13534 }
13535 _ => "review budget exhausted (3/3 rounds used)",
13536 };
13537 assert_eq!(
13538 resume_refusal_under(&state, Some(home.path())),
13539 Some(refusal.clone())
13540 );
13541 assert_eq!(
13542 refusal.successor(),
13543 state
13544 .released_to
13545 .as_deref()
13546 .or(state.retired_to.as_deref())
13547 .or(state.pr_taken_over_by.as_deref())
13548 );
13549 state.save_under(home.path()).unwrap();
13550 let queue = Queue::at(home.path().join("queue"));
13551 let mut task = Task::new(
13552 "retained implementation".into(),
13553 state.instruction.clone(),
13554 state.repo.clone(),
13555 Source::Agent {
13556 run: "talk".into(),
13557 node: crate::queue::CHAT_NODE.into(),
13558 },
13559 );
13560 task.runs.push(state.id.clone());
13561 task.hold_machine(Some("stopped".into()));
13562 queue.put(&mut task).unwrap();
13563 let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
13564 let before_run = serde_json::to_value(&state).unwrap();
13565 let error = crate::chat_control::resume(&queue, home.path(), &state.id)
13566 .unwrap_err()
13567 .to_string();
13568 assert!(error.contains(expected), "{error}");
13569 assert!(!error.contains("only a stalled or blocked"), "{error}");
13570 if matches!(refusal, ResumeRefusal::Status(_)) {
13571 assert!(
13572 error.contains("is final; there is nothing left to resume"),
13573 "{error}"
13574 );
13575 }
13576 if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
13577 assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
13578 assert!(error.contains("review-only successor with a new review budget"));
13579 assert!(error.contains("does not resume this run"));
13580 }
13581 for target in [
13582 &state.released_to,
13583 &state.retired_to,
13584 &state.pr_taken_over_by,
13585 ]
13586 .into_iter()
13587 .flatten()
13588 {
13589 let short = if state.retired_to.as_ref() == Some(target) {
13590 target.as_str()
13591 } else {
13592 crate::run::short_of(target)
13593 };
13594 assert!(
13595 error.contains(&format!("run {short}; inspect `magi show {short}`")),
13596 "{error}"
13597 );
13598 if short != target {
13599 assert!(!error.contains(target), "full successor id leaked: {error}");
13600 }
13601 }
13602 assert_eq!(
13603 serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
13604 before_task
13605 );
13606 assert_eq!(
13607 serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
13608 .unwrap(),
13609 before_run
13610 );
13611 let question = action_question(&state.id, resume_action(&state.id));
13612 for phrases in [&PHRASES_EN, &PHRASES_JA] {
13613 let decision = decide_action(home.path(), &task, &question, phrases, |id| {
13614 RunState::load_under(id, home.path())
13615 });
13616 let ActionDecision::Refuse(detail) = decision else {
13617 panic!(
13618 "refusal expected: decision={decision:?}, refusal={refusal:?}, run={}, home={}",
13619 state.id,
13620 home.path().display()
13621 );
13622 };
13623 assert!(detail.contains(expected), "{detail}");
13624 }
13625 }
13626 exhausted.status = RunStatus::Ready;
13628 exhausted.released_to = Some("released".into());
13629 exhausted.retired_to = Some("retired".into());
13630 exhausted.pr_taken_over_by = Some("owner".into());
13631 let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
13632 assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
13633 let detail = reason.diagnostic(&exhausted);
13634 for target in ["released", "retired", "owner"] {
13635 assert!(detail.contains(&format!("magi show {target}")));
13636 }
13637 }
13638
13639 #[test]
13640 fn resume_action_ignores_question_checkpoints_in_another_home() {
13641 crate::run::pin_test_home();
13642 let home = tempfile::tempdir().unwrap();
13643 let mut state = run_state(RunStatus::Blocked);
13644 state.id = format!(
13647 "resume-context-{}",
13648 home.path().file_name().unwrap().to_str().unwrap()
13649 );
13650 state.driver_exited = true;
13651 state.config.graph.review_rounds = 1;
13652 state.reviews = vec![review_round(1)];
13653 state.save_under(home.path()).unwrap();
13654 let task = held_task_with(&state.id);
13655 let answer = action_question(&state.id, resume_action(&state.id));
13656 let mut checkpoint = approval_question(&state.id);
13657 let foreign = Questions::open();
13658 foreign.put(&mut checkpoint).unwrap();
13659 let refusal = crate::handover::resume_refusal_under(&state, Some(home.path()));
13660 let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
13661 RunState::load_under(id, home.path())
13662 });
13663 let matching: Vec<_> = foreign
13664 .list()
13665 .into_iter()
13666 .filter(|q| q.run == state.id && q.status.open())
13667 .collect();
13668 std::fs::remove_file(foreign.path_of(&checkpoint.id)).unwrap();
13669 assert!(
13670 matches!(decision, ActionDecision::Refuse(_)),
13671 "decision={decision:?}, refusal={refusal:?}, run={}, home={}, foreign_home={}, matching={matching:?}",
13672 state.id,
13673 home.path().display(),
13674 crate::run::test_home().display()
13675 );
13676 assert_eq!(
13677 refusal,
13678 Some(crate::handover::ResumeRefusal::ReviewBudget { used: 1, limit: 1 })
13679 );
13680 let local = Questions::at(home.path().join("questions"));
13681 for status in [
13682 ask::QuestionStatus::Open,
13683 ask::QuestionStatus::Answered,
13684 ask::QuestionStatus::Abandoned,
13685 ] {
13686 let mut question = checkpoint.clone();
13687 match status {
13688 ask::QuestionStatus::Open => {}
13689 ask::QuestionStatus::Answered => {
13690 question
13691 .answer(ask::Answer::Choice(question.choices[0].clone()))
13692 .unwrap();
13693 }
13694 ask::QuestionStatus::Abandoned => question.abandon("fixture closed"),
13695 }
13696 local.put(&mut question).unwrap();
13697 let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
13698 RunState::load_under(id, home.path())
13699 });
13700 if status.open() {
13701 assert_eq!(decision, ActionDecision::Resume(state.id.clone()));
13702 } else {
13703 assert!(
13704 matches!(decision, ActionDecision::Refuse(ref detail) if detail.contains("review budget exhausted")),
13705 "status={status:?}, decision={decision:?}"
13706 );
13707 }
13708 }
13709 }
13710
13711 #[test]
13712 fn resume_action_checks_the_driver_lease_in_the_supplied_home() {
13713 let home = tempfile::tempdir().unwrap();
13714 let mut state = run_state(RunStatus::Stalled);
13715 state.id = format!(
13716 "resume-driver-{}",
13717 home.path().file_name().unwrap().to_str().unwrap()
13718 );
13719 state.driver_claimed = Some(false);
13720 state.save_under(home.path()).unwrap();
13721 let task = held_task_with(&state.id);
13722 let question = action_question(&state.id, resume_action(&state.id));
13723 let decide = || {
13724 decide_action(home.path(), &task, &question, &PHRASES_EN, |id| {
13725 RunState::load_under(id, home.path())
13726 })
13727 };
13728 let lease = crate::driver::maintenance(home.path(), &state.id).unwrap();
13729 assert_eq!(state.liveness_under(home.path(), false), Liveness::Live);
13730 assert_eq!(
13731 decide(),
13732 ActionDecision::Refuse("run already has a live driver".into())
13733 );
13734 drop(lease);
13735 assert_eq!(decide(), ActionDecision::Resume(state.id.clone()));
13736 }
13737
13738 #[test]
13739 fn resume_checkpoint_admission_uses_the_supplied_question_store() {
13740 let home = tempfile::tempdir().unwrap();
13741 let mut state = run_state(RunStatus::Blocked);
13742 state.driver_exited = true;
13743 state.config.graph.review_rounds = 1;
13744 state.reviews = vec![review_round(1)];
13745 assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
13746 for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
13747 let mut saved = state.clone();
13748 match checkpoint {
13749 "publication" => saved.pr_publication_pending = true,
13750 "approval" => {
13751 saved.land_approval = Some(crate::run::LandApproval {
13752 question: "approval".into(),
13753 head: "head".into(),
13754 })
13755 }
13756 "armed" => saved.land_armed_head = Some("head".into()),
13757 "landing" => saved.status = RunStatus::Landing,
13758 _ => {
13759 let mut question = ask::Question::new(
13760 saved.id.clone(),
13761 "review".into(),
13762 "review-1".into(),
13763 "continue?".into(),
13764 String::new(),
13765 vec!["continue".into()],
13766 );
13767 ask::Questions::at(home.path().join("questions"))
13768 .put(&mut question)
13769 .unwrap();
13770 }
13771 }
13772 saved.save_under(home.path()).unwrap();
13773 assert!(
13774 crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
13775 "{checkpoint}"
13776 );
13777 assert!(
13778 crate::resume::validate(home.path(), &saved.id).is_ok(),
13779 "{checkpoint}"
13780 );
13781 }
13782 }
13783
13784 #[test]
13785 fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
13786 let mut state = run_state(RunStatus::Blocked);
13787 state.config.graph.review_rounds = 3;
13788 state.reviews = vec![review_round(1), review_round(2), review_round(3)];
13789 assert!(exhausted_review_budget(&state));
13790
13791 state.reviews.pop();
13793 assert!(!exhausted_review_budget(&state));
13794
13795 let mut stalled = run_state(RunStatus::Stalled);
13798 stalled.config.graph.review_rounds = 1;
13799 stalled.reviews = vec![review_round(1)];
13800 assert!(!exhausted_review_budget(&stalled));
13801 }
13802
13803 fn review_round(round: usize) -> crate::run::ReviewRound {
13804 crate::run::ReviewRound {
13805 round,
13806 head: "deadbeef".to_owned(),
13807 verified_head: None,
13808 verified_at: None,
13809 reviews: Vec::new(),
13810 e2e: Vec::new(),
13811 verify_retried: false,
13812 e2e_deferred: false,
13813 e2e_defer_reason: None,
13814 fix: None,
13815 blocking: 0,
13816 answered: 1,
13817 expected: 1,
13818 clean: false,
13819 progressed: true,
13820 vote_split: false,
13821 reconsideration: Vec::new(),
13822 verdict: None,
13823 }
13824 }
13825
13826 #[test]
13827 fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
13828 let mut run = RunState::new(
13829 PathBuf::from("/repo"),
13830 "main".to_owned(),
13831 "abc1234def".to_owned(),
13832 "add retries".to_owned(),
13833 Config::default(),
13834 );
13835 run.status = RunStatus::Judging;
13836 run.parked = true;
13837 let mut task = Task::new(
13838 "add retries".to_owned(),
13839 "add retries".to_owned(),
13840 PathBuf::from("/repo"),
13841 crate::queue::Source::Human,
13842 );
13843 task.status = TaskStatus::Failed;
13844 task.runs = vec![run.id.clone()];
13845 let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
13846 assert!(with(&task, &run), "parked after judging is the case");
13847 let mut parked_task = task.clone();
13848 parked_task.status = TaskStatus::Parked;
13849 assert!(with(&parked_task, &run), "the Parked status is the case");
13850
13851 let mut not_parked = run.clone();
13852 not_parked.parked = false;
13853 not_parked.status = RunStatus::Stalled;
13854 assert!(!with(&task, ¬_parked), "a stall is the conductor's");
13855
13856 let mut fresh = task.clone();
13857 fresh.fresh_start = true;
13858 assert!(!with(&fresh, &run), "a requeue asked for a new competition");
13859
13860 let mut review = task.clone();
13861 review.review_branch = Some("magi/x/A".to_owned());
13862 assert!(!with(&review, &run), "review is ranked before resume");
13863
13864 let mut held = task.clone();
13865 held.status = TaskStatus::Held;
13866 assert!(!with(&held, &run), "a hold stays visible to the conductor");
13867
13868 let mut released = run.clone();
13869 released.released_to = Some("20260901-000000-new1".to_owned());
13870 assert!(!with(&task, &released), "nothing left to resume into");
13871
13872 assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
13873 "unreadable"
13874 )));
13875 }
13876
13877 #[test]
13878 fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
13879 let mut released = RunState::new(
13880 PathBuf::from("/repo"),
13881 "main".to_owned(),
13882 "abc1234def".to_owned(),
13883 "add retries".to_owned(),
13884 Config::default(),
13885 );
13886 released.status = RunStatus::Blocked;
13887 assert_eq!(
13888 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
13889 Some(released.id.clone())
13890 );
13891 released.released_to = Some("20260901-000000-new1".to_owned());
13892 assert_eq!(
13893 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
13894 None,
13895 "there is nothing left to resume it into"
13896 );
13897 }
13898
13899 #[test]
13900 fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
13901 let mut exhausted = RunState::new(
13910 PathBuf::from("/repo"),
13911 "main".to_owned(),
13912 "abc1234def".to_owned(),
13913 "add retries".to_owned(),
13914 Config::default(),
13915 );
13916 exhausted.status = RunStatus::Blocked;
13917 exhausted.config.graph.review_rounds = 1;
13918 exhausted.reviews = vec![review_round(1)];
13919
13920 assert_eq!(
13921 unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
13922 None,
13923 "an exhausted `Blocked` run must not be offered as resumable"
13924 );
13925
13926 let mut has_budget_left = RunState::new(
13929 PathBuf::from("/repo"),
13930 "main".to_owned(),
13931 "abc1234def".to_owned(),
13932 "add retries".to_owned(),
13933 Config::default(),
13934 );
13935 has_budget_left.status = RunStatus::Blocked;
13936 has_budget_left.config.graph.review_rounds = 3;
13937 has_budget_left.reviews = vec![review_round(1)];
13938
13939 assert_eq!(
13940 unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
13941 Ok(has_budget_left.clone())
13942 }),
13943 Some(has_budget_left.id.clone())
13944 );
13945 }
13946
13947 #[test]
13948 fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
13949 let mut run = RunState::new(
13950 PathBuf::from("/repo"),
13951 "main".to_owned(),
13952 "abc1234def".to_owned(),
13953 "add retries".to_owned(),
13954 Config::default(),
13955 );
13956 run.status = RunStatus::Blocked;
13957 run.config.graph.review_rounds = 1;
13958 run.reviews = vec![review_round(1)];
13959 run.pr_publication_pending = true;
13960 assert_eq!(
13961 unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
13962 Some(run.id.clone()),
13963 "a spent review budget must not turn a failed publication into a re-competition"
13964 );
13965 }
13966
13967 #[test]
13968 fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
13969 let mut task = Task::new(
13970 "recover work".into(),
13971 "recover work".into(),
13972 PathBuf::from("/repo"),
13973 crate::queue::Source::Human,
13974 );
13975 let mut history = std::collections::BTreeMap::new();
13976 for index in 0..8 {
13977 let mut run = run_state(RunStatus::Blocked);
13978 run.id = format!("20260101-000000-{index:04}");
13979 run.base_commit = format!("upstream-{index}");
13980 if index > 0 {
13982 run.candidates.clear();
13983 }
13984 task.runs.extend([run.id.clone(), run.id.clone()]);
13985 history.insert(run.id.clone(), run);
13986 task.requeue();
13987 }
13988 let check = |task: &Task, starter: &Starter, limit| {
13989 retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
13990 };
13991 assert!(
13992 check(&task, &Starter::Start, 8)
13993 .unwrap()
13994 .contains("8 unretired")
13995 );
13996 assert!(check(&task, &Starter::Start, 9).is_none());
13997 assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
13998 task.release_operator("owner", None);
13999 assert_eq!(task.attempts, 0);
14000 let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
14001 assert!(check(&restored, &Starter::Start, 8).is_some());
14002 assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
14003 assert!(check(&restored, &Starter::Start, 0).is_none());
14004 }
14005
14006 #[test]
14007 fn retained_attempt_bound_includes_failed_startups_without_execution_history() {
14008 let tmp = tempfile::tempdir().unwrap();
14009 let mut task = Task::new(
14010 "recover selected PR".into(),
14011 "preserve implementation".into(),
14012 tmp.path().join("repo"),
14013 crate::queue::Source::Human,
14014 );
14015 let mut failed = run_state(RunStatus::Failed);
14016 failed.id = "20260101-000000-fail".into();
14017 failed.candidates.clear();
14018 failed.prep_complete = Some(false);
14019 failed.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
14020 failed.startup = Some(crate::run::Startup {
14021 kind: "pr-recovery".into(),
14022 branch: Some("selected-public-head".into()),
14023 stage: "worktree-setup".into(),
14024 complete: false,
14025 failure: Some("setup modified a tracked file and failed".into()),
14026 });
14027 let worktree = failed.worktree_root().join("under-review");
14030 std::fs::create_dir_all(&worktree).unwrap();
14031 let retained_edit = worktree.join("implementation");
14032 std::fs::write(&retained_edit, "retained setup edit").unwrap();
14033 task.record_startup_failure(crate::run::StartupFailure {
14034 run: failed.id.clone(),
14035 stage: "worktree-setup".into(),
14036 });
14037 let task: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
14038 assert!(task.runs.is_empty() && task.passes.is_empty());
14039 assert_eq!(task.attempts, 0);
14040 let starter = Starter::Review("selected-public-head".into());
14041 assert!(
14042 retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone()))
14043 .unwrap()
14044 .contains("1 unretired")
14045 );
14046 assert!(retained_attempt_hold(&task, &starter, 2, |_| Ok(failed.clone())).is_none());
14047 assert!(
14048 retained_attempt_hold(&task, &starter, 2, |_| anyhow::bail!("unreadable"))
14049 .unwrap()
14050 .contains("Cannot verify")
14051 );
14052 let mut mixed = task.clone();
14054 mixed.runs.push(failed.id.clone());
14055 mixed
14056 .startup_failures
14057 .push(task.startup_failures[0].clone());
14058 assert!(retained_attempt_hold(&mixed, &starter, 2, |_| Ok(failed.clone())).is_none());
14059 failed.retired_to = Some("verified-recovery-owner".into());
14060 assert!(retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone())).is_none());
14061 assert!(
14062 retained_attempt_hold(&task, &Starter::Resume(failed.id.clone()), 1, |_| {
14063 panic!("resuming the existing owner must not allocate a new attempt")
14064 })
14065 .is_none()
14066 );
14067 assert_eq!(
14068 std::fs::read_to_string(retained_edit).unwrap(),
14069 "retained setup edit"
14070 );
14071 assert!(task.runs.is_empty() && task.passes.is_empty());
14072 assert_eq!(task.attempts, 0);
14073 }
14074
14075 #[test]
14076 fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
14077 let mut task = Task::new(
14078 "recover work".into(),
14079 "recover work".into(),
14080 PathBuf::from("/repo"),
14081 crate::queue::Source::Human,
14082 );
14083 let mut run = run_state(RunStatus::Superseded);
14084 run.candidates.clear();
14085 task.runs.push(run.id.clone());
14086 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
14087 run.retired_to = Some("authority".into());
14088 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
14089 run.retired_to = None;
14090 run.released_to = Some("authority".into());
14091 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
14092 assert!(
14093 retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
14094 .unwrap()
14095 .contains("Cannot verify")
14096 );
14097 assert!(
14099 retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
14100 panic!("resume must not load historical attempts")
14101 })
14102 .is_none()
14103 );
14104 }
14105
14106 #[test]
14107 fn retired_resume_requires_a_valid_same_repository_authority() {
14108 let mut source = run_state(RunStatus::Blocked);
14109 let mut empty = run_state(RunStatus::Blocked);
14110 empty.retired_to = Some(source.id.clone());
14111 let runs = vec![source.id.clone(), empty.id.clone()];
14112 let resolve = |source: &RunState, empty: &RunState| {
14113 unfinished_run_with(&runs, "fixture", |id| {
14114 if id == source.id {
14115 Ok(source.clone())
14116 } else if id == empty.id {
14117 Ok(empty.clone())
14118 } else {
14119 bail!("unreadable authority")
14120 }
14121 })
14122 };
14123 assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
14124 assert_eq!(
14125 choose_starter(None, false, resolve(&source, &empty).as_deref()),
14126 Starter::Resume(source.id.clone())
14127 );
14128 source.retired_to = Some(empty.id.clone());
14129 assert!(
14130 resolve(&source, &empty).is_none(),
14131 "cycles do not revive obsolete runs"
14132 );
14133 source.retired_to = None;
14134 source.repo = PathBuf::from("/another-repository");
14135 assert!(resolve(&source, &empty).is_none());
14136 source.repo = empty.repo.clone();
14137 source.released_to = Some("later".into());
14138 assert!(resolve(&source, &empty).is_none());
14139 empty.retired_to = Some("unlisted-run".into());
14140 assert!(resolve(&source, &empty).is_none());
14141 }
14142
14143 #[test]
14144 fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
14145 let mut older_stalled = RunState::new(
14153 PathBuf::from("/repo"),
14154 "main".to_owned(),
14155 "abc1234def".to_owned(),
14156 "add retries".to_owned(),
14157 Config::default(),
14158 );
14159 older_stalled.status = RunStatus::Stalled;
14160
14161 let mut newest_exhausted = RunState::new(
14162 PathBuf::from("/repo"),
14163 "main".to_owned(),
14164 "abc1234def".to_owned(),
14165 "add retries".to_owned(),
14166 Config::default(),
14167 );
14168 newest_exhausted.status = RunStatus::Blocked;
14169 newest_exhausted.config.graph.review_rounds = 1;
14170 newest_exhausted.reviews = vec![review_round(1)];
14171
14172 assert_eq!(
14173 unfinished_run_with(
14174 &[older_stalled.id.clone(), newest_exhausted.id.clone()],
14175 "t",
14176 |_| Ok(newest_exhausted.clone())
14177 ),
14178 None,
14179 "the newest run is exhausted, so nothing here is worth resuming - \
14180 least of all the older, already-superseded run"
14181 );
14182 }
14183
14184 #[test]
14185 fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
14186 assert_eq!(
14187 unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
14188 Err(anyhow::anyhow!("fixture is absent"))
14189 }),
14190 None
14191 );
14192 }
14193
14194 fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
14195 let mut q = ask::Question::new(
14196 run.to_owned(),
14197 "implement".to_owned(),
14198 "impl-A".to_owned(),
14199 "continue?".to_owned(),
14200 String::new(),
14201 vec!["resume で続行する".to_owned(), "other".to_owned()],
14202 );
14203 q.actions.insert("resume で続行する".to_owned(), action);
14204 q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
14205 .unwrap();
14206 q
14207 }
14208
14209 fn held_task_with(run: &str) -> Task {
14210 let mut t = task();
14211 t.runs = vec![run.to_owned()];
14212 t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
14213 t
14214 }
14215
14216 fn resume_action(run: &str) -> ask::ChoiceAction {
14217 ask::ChoiceAction::Resume { run: run.into() }
14218 }
14219
14220 #[test]
14221 fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
14222 let home = crate::run::test_home();
14223 for parked in [false, true] {
14224 let mut t = task();
14225 t.start("A".into());
14226 t.start("B".into());
14227 assert_eq!(t.runs, vec!["A", "B"]);
14228 t.start("A".into());
14229 let mut resumed = run_state(RunStatus::Blocked);
14230 resumed.id = "A".into();
14231 resumed.parked = parked;
14232 resumed.driver_exited = true;
14233 t.hold_machine(Some("resumed run stopped".into()));
14234 let q = action_question("A", resume_action("A"));
14235 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
14236 assert_eq!(
14237 decide_action(&home, &t, &q, &PHRASES_EN, |id| {
14238 assert_eq!(id, "A");
14239 Ok(resumed.clone())
14240 }),
14241 ActionDecision::Resume("A".into())
14242 );
14243 assert_eq!(
14244 action_standing(&t, &action_question("B", resume_action("B"))),
14245 ActionStanding::Stale
14246 );
14247 t.release_operator("cli", None);
14248 let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
14249 assert_eq!(id, "A");
14250 Ok(resumed.clone())
14251 });
14252 assert_eq!(
14253 choose_starter(None, false, unfinished.as_deref()),
14254 Starter::Resume("A".into())
14255 );
14256 assert_eq!(t.runs, vec!["B", "A"]);
14257 }
14258 }
14259
14260 #[test]
14261 fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
14262 let home = crate::run::test_home();
14263 let mut state = crate::land::tests::repair_state(true, true);
14264 state.status = RunStatus::Landing;
14265 state.parked = true;
14266 state.driver_exited = true;
14267 let mut q = ask::Question::new(
14268 state.id.clone(),
14269 land::APPROVAL_NODE.into(),
14270 "land".into(),
14271 "Merge?".into(),
14272 String::new(),
14273 vec![land::APPROVE.into(), land::HOLD.into()],
14274 );
14275 q.id = state.id.clone();
14276 state.land_approval = Some(crate::run::LandApproval {
14277 question: q.id.clone(),
14278 head: "current-head".into(),
14279 });
14280 assert!(land::upgrade_repair_choice(&mut q, &state));
14281 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14282 let mut task = held_task_with(&state.id);
14283 task.status = TaskStatus::Parked;
14284 assert_eq!(
14285 decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
14286 ActionDecision::Resume(state.id.clone())
14287 );
14288 q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
14289 q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
14290 task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
14291 assert_eq!(
14292 decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
14293 ActionDecision::Resume(state.id.clone()),
14294 "a repair answer newer than the manual hold resumes the existing owner"
14295 );
14296 task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
14297 for answered_at in [q.answered_at, None] {
14298 let mut older = q.clone();
14299 older.answered_at = answered_at;
14300 let refused = decide_action(&home, &task, &older, &PHRASES_EN, |_| {
14301 panic!("a later manual hold must prevent dispatch")
14302 });
14303 let ActionDecision::Refuse(reason) = refused else {
14304 panic!("expected an actionable refusal, got {refused:?}");
14305 };
14306 assert!(reason.contains("later operator decision"));
14307 assert!(reason.contains(&format!("magi task release {}", task.id)));
14308 }
14309 task.operator_decided_at = None;
14310 let mut superseded = state.clone();
14311 superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
14312 assert_eq!(
14313 decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(superseded)),
14314 ActionDecision::Stale
14315 );
14316 for case in 1..4 {
14317 let mut changed = state.clone();
14318 match case {
14319 1 => changed.status = RunStatus::Blocked,
14320 2 => changed.released_to = Some("new-owner".into()),
14321 _ => changed.land_approval.as_mut().unwrap().head.clear(),
14322 }
14323 assert!(matches!(
14324 decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(changed)),
14325 ActionDecision::Refuse(_)
14326 ));
14327 }
14328 assert!(matches!(
14329 decide_action(&home, &task, &q, &PHRASES_EN, |_| anyhow::bail!(
14330 "missing owner"
14331 )),
14332 ActionDecision::Refuse(_)
14333 ));
14334 task.runs.push("replacement".into());
14335 task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
14336 assert_eq!(
14337 decide_action(&home, &task, &q, &PHRASES_EN, |_| panic!(
14338 "old owner must not load"
14339 )),
14340 ActionDecision::Stale
14341 );
14342 }
14343
14344 #[test]
14345 fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
14346 let mut state = crate::land::tests::repair_state(true, true);
14347 state.status = RunStatus::Landing;
14348 state.parked = true;
14349 state.driver_exited = true;
14350 let mut q = ask::Question::new(
14351 state.id.clone(),
14352 land::APPROVAL_NODE.into(),
14353 "land".into(),
14354 "Merge?".into(),
14355 String::new(),
14356 vec![land::APPROVE.into(), land::HOLD.into()],
14357 );
14358 q.id = state.id.clone();
14359 state.land_approval = Some(crate::run::LandApproval {
14360 question: q.id.clone(),
14361 head: "current-head".into(),
14362 });
14363 state.save().unwrap();
14364 land::upgrade_repair_choice(&mut q, &state);
14365 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14366 Questions::open().put(&mut q).unwrap();
14367 let tmp = tempfile::tempdir().unwrap();
14368 let queue = Queue::at(tmp.path().join("queue"));
14369 let mut task = held_task_with(&state.id);
14370 task.status = TaskStatus::Parked;
14371 queue.put(&mut task).unwrap();
14372 let empty = Arc::new(tokio::sync::Semaphore::new(0));
14373 let free = Arc::new(tokio::sync::Semaphore::new(1));
14374 assert!(matches!(
14375 claim_dispatch(&queue, &task, false, &empty, &free),
14376 Err(SkipReason::OrdinaryCapacity)
14377 ));
14378 assert!(matches!(
14379 claim_dispatch(&queue, &task, true, &free, &free),
14380 Err(SkipReason::CoolingDown)
14381 ));
14382 let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
14383 assert!(claim.permit.is_some());
14384 assert!(matches!(
14385 claim_dispatch(&queue, &task, false, &free, &free),
14386 Err(SkipReason::ClaimUnavailable)
14387 ));
14388 drop(claim);
14389 Questions::open()
14390 .update(&q.id, |q| {
14391 q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
14392 Ok(())
14393 })
14394 .unwrap();
14395 let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
14396 assert!(claim.permit.is_none());
14397 assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
14398 }
14399
14400 #[test]
14401 fn decide_action_resumes_only_the_latest_resumable_run() {
14402 let home = crate::run::test_home();
14403 let t = held_task_with("r1");
14404 let q = action_question("r1", resume_action("r1"));
14405 let load = |s: RunState| move |_: &str| Ok(s);
14406 assert_eq!(
14407 decide_action(
14408 &home,
14409 &t,
14410 &q,
14411 &PHRASES_EN,
14412 load(run_state(RunStatus::Blocked))
14413 ),
14414 ActionDecision::Resume("r1".into())
14415 );
14416 let q_other = action_question("r1", resume_action("r0"));
14418 assert!(matches!(
14419 decide_action(
14420 &home,
14421 &t,
14422 &q_other,
14423 &PHRASES_EN,
14424 load(run_state(RunStatus::Blocked))
14425 ),
14426 ActionDecision::Refuse(_)
14427 ));
14428 assert!(matches!(
14430 decide_action(
14431 &home,
14432 &t,
14433 &q,
14434 &PHRASES_EN,
14435 load(run_state(RunStatus::Ready))
14436 ),
14437 ActionDecision::Refuse(_)
14438 ));
14439 let mut released = run_state(RunStatus::Blocked);
14441 released.released_to = Some("elsewhere".into());
14442 assert!(matches!(
14443 decide_action(&home, &t, &q, &PHRASES_EN, load(released)),
14444 ActionDecision::Refuse(_)
14445 ));
14446 assert!(matches!(
14448 decide_action(&home, &t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
14449 ActionDecision::Refuse(_)
14450 ));
14451 }
14452
14453 #[test]
14454 fn decide_action_ignores_a_question_about_an_earlier_run() {
14455 let home = crate::run::test_home();
14456 let mut t = held_task_with("r1");
14457 t.runs.push("r2".to_owned());
14458 let never = |_: &str| -> Result<RunState> { bail!("not read") };
14459 assert_eq!(
14460 decide_action(
14461 &home,
14462 &t,
14463 &action_question("r1", ask::ChoiceAction::Done),
14464 &PHRASES_EN,
14465 never
14466 ),
14467 ActionDecision::Stale
14468 );
14469 }
14470
14471 #[test]
14472 fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
14473 let home = crate::run::test_home();
14474 let mut t = held_task_with("r1");
14475 let never = |_: &str| -> Result<RunState> { bail!("not read") };
14476 assert_eq!(
14477 decide_action(
14478 &home,
14479 &t,
14480 &action_question("r1", ask::ChoiceAction::Requeue),
14481 &PHRASES_EN,
14482 never
14483 ),
14484 ActionDecision::Requeue
14485 );
14486 let done_q = action_question("r1", ask::ChoiceAction::Done);
14487 assert_eq!(
14488 decide_action(&home, &t, &done_q, &PHRASES_EN, never),
14489 ActionDecision::Done
14490 );
14491 t.mark_action_applied(&done_q.id);
14492 assert_eq!(
14493 decide_action(&home, &t, &done_q, &PHRASES_EN, never),
14494 ActionDecision::Skip
14495 );
14496
14497 let mut plain = action_question("r1", ask::ChoiceAction::Done);
14499 plain.actions.clear();
14500 assert_eq!(
14501 decide_action(&home, &held_task_with("r1"), &plain, &PHRASES_EN, never),
14502 ActionDecision::Skip
14503 );
14504 let mut running = held_task_with("r1");
14506 running.status = TaskStatus::Running;
14507 assert_eq!(
14508 decide_action(
14509 &home,
14510 &running,
14511 &action_question("r1", ask::ChoiceAction::Done),
14512 &PHRASES_EN,
14513 never
14514 ),
14515 ActionDecision::Skip
14516 );
14517 }
14518
14519 #[test]
14520 fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
14521 crate::run::pin_test_home();
14522 for legacy in [false, true] {
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 run = "20260101-000000-hold";
14527 let mut task = held_task_with(run);
14528 task.status = TaskStatus::Parked;
14529 let mut q = ask::Question::new(
14530 run.into(),
14531 land::APPROVAL_NODE.into(),
14532 "land".into(),
14533 "Repair?".into(),
14534 String::new(),
14535 vec![land::REPAIR.into()],
14536 );
14537 q.actions.insert(land::REPAIR.into(), resume_action(run));
14538 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14539 q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
14541 q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
14542 questions.put(&mut q).unwrap();
14543 task.hold_manual(Some("Keep this PR paused".into()));
14544 if legacy {
14545 task.hold_source = None;
14546 }
14547 queue.put(&mut task).unwrap();
14548
14549 apply_task_choice_actions(&queue, &questions, dir.path());
14550 let after = queue.get(&task.id).unwrap();
14551 assert!(after.operator_held());
14552 assert_eq!(after.hold_source, task.hold_source);
14553 assert_eq!(after.operator_decided_at, task.operator_decided_at);
14554 assert_eq!(after.runs, task.runs);
14555 assert_eq!(after.instruction, task.instruction);
14556 assert!(after.resume_override.is_none());
14557 assert!(after.action_applied(&q.id));
14558 let reason = after.hold_reason.as_deref().unwrap();
14559 assert!(reason.starts_with("Keep this PR paused"));
14560 assert!(reason.contains("later operator decision"));
14561 assert!(reason.contains(&format!("magi task release {}", task.id)));
14562
14563 for recovery in [
14564 crate::conduct::Recovery::Review,
14565 crate::conduct::Recovery::Requeue,
14566 ] {
14567 crate::conduct::apply(
14568 &queue,
14569 &questions,
14570 &crate::conduct::Verdict {
14571 decisions: vec![crate::conduct::Decision {
14572 id: task.id.clone(),
14573 recovery: Some(recovery),
14574 ..Default::default()
14575 }],
14576 },
14577 )
14578 .unwrap();
14579 }
14580 apply_task_choice_actions(&queue, &questions, dir.path());
14583 let still_held = queue.get(&task.id).unwrap();
14584 assert!(still_held.operator_held());
14585 assert_eq!(still_held.hold_reason, after.hold_reason);
14586 assert_eq!(still_held.runs, task.runs);
14587 assert!(still_held.review_branch.is_none());
14588 assert!(!still_held.fresh_start);
14589 assert!(queue.next_runnable().is_none());
14590 }
14591 }
14592
14593 #[test]
14594 fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
14595 for held in [false, true] {
14596 for retry in [false, true] {
14597 let dir = tempfile::tempdir().unwrap();
14598 let queue = Queue::at(dir.path().join("queue"));
14599 let questions = Questions::at(dir.path().join("questions"));
14600 let home = dir.path().join("home");
14601 let mut t = task();
14602 if held {
14603 t.hold_machine(Some("driver state unknown".into()));
14604 }
14605 queue.put(&mut t).unwrap();
14606 let verdict = serde_json::from_value(serde_json::json!({
14607 "decisions": [{
14608 "id": t.id,
14609 "question": "Driver state unknown; retry the checks or hold?",
14610 "choices": ["daemon: recheck and retry", "daemon: hold the task"],
14611 "actions": {
14612 "daemon: recheck and retry": {"do": "requeue"},
14613 "daemon: hold the task": {"do": "hold"}
14614 }
14615 }]
14616 }))
14617 .unwrap();
14618 crate::conduct::apply(&queue, &questions, &verdict).unwrap();
14619 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
14620 let mut q = questions.list().pop().unwrap();
14621 let choice = if retry {
14622 "daemon: recheck and retry"
14623 } else {
14624 "daemon: hold the task"
14625 };
14626 assert_eq!(q.actions.len(), 2);
14627 q.answer(ask::Answer::Choice(choice.into())).unwrap();
14628 questions.put(&mut q).unwrap();
14629
14630 questions.beat(&q.id, ask::WaiterKind::Deputy);
14632 for _ in 0..2 {
14633 resolve_blockers(&queue, &questions);
14634 apply_task_choice_actions(&queue, &questions, &home);
14635 let waiting = queue.get(&t.id).unwrap();
14636 assert_eq!(waiting.status, TaskStatus::Blocked);
14637 assert_eq!(waiting.blocked_by, [q.id.clone()]);
14638 assert!(waiting.answers.is_empty());
14639 assert!(!waiting.action_applied(&q.id));
14640 assert!(runnable(&queue).is_empty());
14641 let free = Arc::new(tokio::sync::Semaphore::new(1));
14642 assert!(claim_dispatch(&queue, &t, false, &free, &free).is_err());
14643 }
14644 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
14645
14646 resolve_blockers(&queue, &questions);
14648 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
14649 apply_task_choice_actions(&queue, &questions, &home);
14650 let after = queue.get(&t.id).unwrap();
14651 assert_eq!(
14652 after.status,
14653 if retry {
14654 TaskStatus::Queued
14655 } else {
14656 TaskStatus::Held
14657 }
14658 );
14659 assert!(after.action_applied(&q.id));
14660 assert_eq!(after.operator_held(), !retry);
14661 assert_eq!(after.answers.len(), 1);
14662
14663 let mut changed = after;
14665 if retry {
14666 changed.hold_manual(Some("later hold".into()));
14667 } else {
14668 changed.release_operator("test", None);
14669 }
14670 let expected = changed.status;
14671 queue.put(&mut changed).unwrap();
14672 apply_task_choice_actions(&queue, &questions, &home);
14673 assert_eq!(queue.get(&t.id).unwrap().status, expected);
14674 }
14675 }
14676 }
14677
14678 #[test]
14679 fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
14680 let dir = tempfile::tempdir().unwrap();
14681 let queue = Queue::at(dir.path().join("queue"));
14682 let questions = Questions::at(dir.path().join("questions"));
14683 let home = dir.path().join("home");
14684 let mut state = run_state(RunStatus::Blocked);
14685 state.id = "20260101-000000-act1".to_owned();
14686 state.save_under(&home).unwrap();
14687
14688 let mut t = held_task_with(&state.id);
14689 queue.put(&mut t).unwrap();
14690 let mut q = action_question(&state.id, resume_action(&state.id));
14691 questions.put(&mut q).unwrap();
14692
14693 apply_task_choice_actions(&queue, &questions, &home);
14694 let after = queue.get(&t.id).unwrap();
14695 assert_eq!(after.status, TaskStatus::Queued);
14696 assert!(!after.fresh_start);
14697 assert!(after.action_applied(&q.id));
14698 let pin = after.resume_override.clone().unwrap();
14699 assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
14700 assert!(pin.forced);
14701
14702 let mut again = queue.get(&t.id).unwrap();
14704 again.hold_machine(Some("later".into()));
14705 queue.put(&mut again).unwrap();
14706 apply_task_choice_actions(&queue, &questions, &home);
14707 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14708 }
14709
14710 #[test]
14711 fn done_choice_cannot_discard_unfinished_work_or_record_success_receipts() {
14712 let dir = tempfile::tempdir().unwrap();
14713 let home = dir.path();
14714 let queue = Queue::at(home.join("queue"));
14715 let questions = Questions::at(home.join("questions"));
14716 let mut state = run_state(RunStatus::Blocked);
14717 state.save_under(home).unwrap();
14718 let mut task = held_task_with(&state.id);
14719 queue.put(&mut task).unwrap();
14720 let mut question = action_question(&state.id, ask::ChoiceAction::Done);
14721 questions.put(&mut question).unwrap();
14722
14723 apply_task_choice_actions(&queue, &questions, home);
14724
14725 let after = queue.get(&task.id).unwrap();
14726 assert_eq!(after.status, TaskStatus::Held);
14727 assert!(after.hold_reason.as_deref().unwrap().contains("--discard"));
14728 assert_eq!(after.runs, task.runs);
14729 assert!(after.completion_history.is_empty());
14730 assert!(!after.decision_effects.contains_key(&question.id));
14731 assert_eq!(
14732 RunState::load_under(&state.id, home).unwrap().status,
14733 RunStatus::Blocked
14734 );
14735 }
14736
14737 #[test]
14738 fn a_delivered_answer_is_still_acted_on_exactly_once() {
14739 let dir = tempfile::tempdir().unwrap();
14740 let queue = Queue::at(dir.path().join("queue"));
14741 let questions = Questions::at(dir.path().join("questions"));
14742 let home = dir.path().join("home");
14743 let mut state = run_state(RunStatus::Blocked);
14744 state.id = "20260101-000000-act2".to_owned();
14745 state.save_under(&home).unwrap();
14746
14747 let mut t = held_task_with(&state.id);
14748 queue.put(&mut t).unwrap();
14749 let mut q = action_question(&state.id, resume_action(&state.id));
14750 q.answer_delivered = true;
14751 questions.put(&mut q).unwrap();
14752
14753 apply_task_choice_actions(&queue, &questions, &home);
14756 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
14757 assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
14758
14759 let mut again = queue.get(&t.id).unwrap();
14761 again.hold_machine(Some("later".into()));
14762 queue.put(&mut again).unwrap();
14763 apply_task_choice_actions(&queue, &questions, &home);
14764 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14765 }
14766
14767 #[test]
14768 fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
14769 let dir = tempfile::tempdir().unwrap();
14770 let queue = Queue::at(dir.path().join("queue"));
14771 let questions = Questions::at(dir.path().join("questions"));
14772 let home = dir.path().join("home");
14773 let mut state = run_state(RunStatus::Blocked);
14774 state.id = "20260101-000000-act3".to_owned();
14775 state.save_under(&home).unwrap();
14776 let mut t = held_task_with(&state.id);
14777 queue.put(&mut t).unwrap();
14778 let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
14779 questions.put(&mut q).unwrap();
14780
14781 questions.beat(&q.id, crate::ask::WaiterKind::Asker);
14782 apply_task_choice_actions(&queue, &questions, &home);
14783 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14784
14785 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
14786 apply_task_choice_actions(&queue, &questions, &home);
14787 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
14788 }
14789
14790 #[test]
14791 fn action_standing_tells_the_reasons_apart() {
14792 let mut t = held_task_with("r1");
14793 let q = action_question("r1", ask::ChoiceAction::Requeue);
14794 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
14795 let mut plain = q.clone();
14796 plain.actions.clear();
14797 assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
14798
14799 t.mark_action_applied(&q.id);
14801 assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
14802
14803 let mut t = held_task_with("r1");
14805 t.start("r2".to_owned());
14806 assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
14807 let q2 = action_question("r2", ask::ChoiceAction::Requeue);
14809 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
14810 t.status = TaskStatus::Blocked;
14811 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
14812
14813 let mut c = action_question("r0", ask::ChoiceAction::Requeue);
14815 c.node = crate::conduct::NODE.to_owned();
14816 assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
14817 assert!(!ActionStanding::Busy.daemon_owns());
14818 }
14819
14820 #[test]
14821 fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
14822 let dir = tempfile::tempdir().unwrap();
14823 let queue = Queue::at(dir.path().join("queue"));
14824 let questions = Questions::at(dir.path().join("questions"));
14825 let home = dir.path().join("home");
14826 let mut state = run_state(RunStatus::Ready);
14828 state.id = "20260101-000000-act4".to_owned();
14829 state.save_under(&home).unwrap();
14830 let mut t = held_task_with(&state.id);
14831 t.status = TaskStatus::Running;
14832 queue.put(&mut t).unwrap();
14833 let mut q = action_question(&state.id, ask::ChoiceAction::Done);
14834 q.cwd = Some(dir.path().display().to_string());
14835 questions.put(&mut q).unwrap();
14836
14837 let running = queue.get(&t.id).unwrap();
14840 assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
14841 assert!(matches!(
14842 crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
14843 crate::waiter::Action::Deliver(_)
14844 ));
14845 apply_task_choice_actions(&queue, &questions, &home);
14847 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
14848 let mut back = queue.get(&t.id).unwrap();
14849 back.hold_machine(Some("later".into()));
14850 queue.put(&mut back).unwrap();
14851 apply_task_choice_actions(&queue, &questions, &home);
14852 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
14853 let mut again = queue.get(&t.id).unwrap();
14854 again.hold_machine(Some("again".into()));
14855 queue.put(&mut again).unwrap();
14856 apply_task_choice_actions(&queue, &questions, &home);
14857 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14858 }
14859}