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
2658#[doc(hidden)]
2659pub struct TaskWorkerLease {
2660 pub job: crate::worker::Job,
2661 dir: PathBuf,
2662 lease: Option<crate::worker::Lease>,
2663}
2664
2665impl TaskWorkerLease {
2666 pub fn release_lease(&mut self) {
2667 self.lease = None;
2668 }
2669}
2670
2671impl Drop for TaskWorkerLease {
2672 fn drop(&mut self) {
2673 self.release_lease();
2674 let _ = std::fs::remove_dir_all(&self.dir);
2675 }
2676}
2677
2678#[doc(hidden)]
2680pub fn live_task_fixture(home: &Path, task: &str) -> Result<TaskWorkerLease> {
2681 let request = TaskWorker {
2682 opts: Opts::default(),
2683 queue: home.join("queue"),
2684 task: task.to_owned(),
2685 lane: PermitKind::default(),
2686 standalone: true,
2687 };
2688 let (job, lease) = crate::worker::running_fixture(
2689 home,
2690 &format!("task:{task}"),
2691 serde_json::to_value(request)?,
2692 )?;
2693 Ok(TaskWorkerLease {
2694 dir: home.join("workers").join("jobs").join(&job.id),
2695 job,
2696 lease: Some(lease),
2697 })
2698}
2699
2700fn task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2701 Ok(crate::worker::active(home)?
2702 .into_iter()
2703 .filter(|job| job.kind == "task")
2704 .collect())
2705}
2706
2707fn owned_task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2708 task_jobs(home)?
2709 .into_iter()
2710 .filter_map(
2711 |job| match serde_json::from_value::<TaskWorker>(job.payload.clone()) {
2712 Ok(request) if !request.standalone => Some(Ok(job)),
2713 Ok(_) => None,
2714 Err(error) => Some(Err(error.into())),
2715 },
2716 )
2717 .collect()
2718}
2719
2720#[must_use]
2722pub fn managed(home: &Path) -> bool {
2723 match crate::worker::active(home) {
2724 Err(error) => {
2725 tracing::error!("cannot determine scheduler ownership: {error:#}");
2726 true
2727 }
2728 Ok(jobs) if jobs.iter().any(|j| j.kind == "scheduler") => true,
2729 Ok(_) => {
2730 read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2731 && crate::worker::try_lease(home, "scheduler").map_or(true, |lease| lease.is_none())
2732 }
2733 }
2734}
2735
2736pub async fn spawn_detached(home: &Path, opts: &Opts) -> Result<crate::worker::Job> {
2738 anyhow::ensure!(
2739 crate::worker::control(home, "scheduler")?.is_none() || !managed(home),
2740 "the scheduler is stopping; wait for retirement before starting it again"
2741 );
2742 crate::worker::spawn(
2743 home,
2744 "scheduler",
2745 "scheduler",
2746 serde_json::to_value(opts.absolute()?)?,
2747 )
2748 .await
2749}
2750
2751fn park_request_path(home: &Path, job: &crate::worker::Job) -> PathBuf {
2752 home.join("worker-parks").join(format!("{}.json", job.id))
2753}
2754
2755fn request_task_park(
2756 home: &Path,
2757 job: &crate::worker::Job,
2758 cause: crate::run::ParkCause,
2759) -> Result<()> {
2760 let path = park_request_path(home, job);
2761 std::fs::create_dir_all(path.parent().context("worker park directory")?)?;
2762 std::fs::write(path, serde_json::to_vec(&cause)?)?;
2763 crate::worker::request(home, &job.key, crate::worker::Control::Park)
2764}
2765
2766pub fn request_control(home: &Path, control: crate::worker::Control) -> Result<()> {
2768 if control == crate::worker::Control::Park {
2769 for job in owned_task_jobs(home)? {
2770 request_task_park(home, &job, crate::run::ParkCause::Operator)?;
2771 }
2772 }
2773 crate::worker::request(home, "scheduler", control)
2774}
2775
2776pub(crate) fn scheduler_restart_options(home: &Path) -> Result<Option<Opts>> {
2778 if let Some(job) = crate::worker::active(home)?
2779 .into_iter()
2780 .find(|job| job.kind == "scheduler")
2781 {
2782 return serde_json::from_value(job.payload)
2783 .context("read detached scheduler options")
2784 .map(Some);
2785 }
2786 if read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2787 && crate::worker::try_lease(home, "scheduler")?.is_none()
2788 {
2789 let path = home.join("scheduler-options.json");
2790 let body = std::fs::read(&path).with_context(|| format!("read {}", path.display()))?;
2791 return serde_json::from_slice(&body)
2792 .context("decode detached scheduler options")
2793 .map(Some);
2794 }
2795 Ok(None)
2796}
2797
2798pub async fn restart_detached(home: &Path) -> Result<()> {
2800 let Some(opts) = scheduler_restart_options(home)? else {
2801 return Ok(());
2802 };
2803 request_control(home, crate::worker::Control::Stop)?;
2804 loop {
2805 let reserved = crate::worker::active(home)?
2806 .iter()
2807 .any(|job| job.kind == "scheduler");
2808 if !reserved && crate::worker::try_lease(home, "scheduler")?.is_some() {
2809 break;
2810 }
2811 tokio::time::sleep(Duration::from_millis(100)).await;
2812 }
2813 spawn_detached(home, &opts).await?;
2814 Ok(())
2815}
2816
2817pub async fn run_scheduler_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2819 let opts: Opts = serde_json::from_value(payload)?;
2820 let _ = home;
2821 serve_until(opts, Stop::new()).await
2822}
2823
2824pub async fn run_task_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2826 let request: TaskWorker = serde_json::from_value(payload)?;
2827 let queue = Queue::at(request.queue);
2828 let key = format!("task:{}", request.task);
2829 let job = task_jobs(home)?
2830 .into_iter()
2831 .find(|job| job.key == key)
2832 .context("task worker reservation is missing")?;
2833 let park_path = park_request_path(home, &job);
2834 let _claim = loop {
2837 match queue.claim(&request.task) {
2838 Ok(claim) => break claim,
2839 Err(e) if e.chain().any(|c| c.is::<std::io::Error>()) => {
2842 return Err(e.context("claim the task for its worker"));
2843 }
2844 Err(_) => {
2845 sweep_stale_claims(&queue, STALE_CLAIM);
2846 tokio::time::sleep(Duration::from_millis(50)).await;
2847 }
2848 }
2849 };
2850 let mut task = queue.get(&request.task)?;
2851 if !task.status.runnable()
2852 || (!request.standalone
2853 && request.lane
2854 != permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent))
2855 {
2856 return Ok(());
2857 }
2858 let stop = Stop::new();
2859 let watcher = {
2860 let home = home.to_path_buf();
2861 let stop = stop.clone();
2862 let park_path = park_path.clone();
2863 tokio::spawn(async move {
2864 loop {
2865 if crate::worker::control(&home, &key).ok().flatten().is_some() {
2866 let cause = std::fs::read(&park_path)
2867 .ok()
2868 .and_then(|body| serde_json::from_slice(&body).ok())
2869 .unwrap_or(crate::run::ParkCause::Operator);
2870 stop.park(cause);
2871 return;
2872 }
2873 tokio::time::sleep(Duration::from_millis(200)).await;
2874 }
2875 })
2876 };
2877 let quota = if request.standalone {
2878 run_claimed_until(&request.opts, &queue, &mut task, &stop).await
2879 } else {
2880 let status = Arc::new(Mutex::new(Status::new()));
2881 Box::pin(attempt(
2882 &request.opts,
2883 &queue,
2884 &status,
2885 &stop,
2886 crate::graph::Pause::new(),
2887 &mut task,
2888 ))
2889 .await
2890 };
2891 watcher.abort();
2892 let _ = std::fs::remove_file(park_path);
2893 persist_cooldown(home, "a).await?;
2894 Ok(())
2895}
2896
2897pub async fn spawn_claimed(
2900 home: &Path,
2901 opts: &Opts,
2902 queue: &Queue,
2903 task: &Task,
2904 claim: crate::queue::Claim,
2905) -> Result<crate::worker::Job> {
2906 let request = TaskWorker {
2907 opts: opts.absolute()?,
2908 queue: std::path::absolute(queue.root())?,
2909 task: task.id.clone(),
2910 lane: permit_kind(land_resume_state(task) == LandResume::Ready, task.urgent),
2911 standalone: true,
2912 };
2913 let job = crate::worker::spawn(
2914 home,
2915 "task",
2916 &format!("task:{}", task.id),
2917 serde_json::to_value(request)?,
2918 )
2919 .await?;
2920 drop(claim);
2921 Ok(job)
2922}
2923
2924pub async fn run_detached_claimed(
2927 opts: &Opts,
2928 queue: &Queue,
2929 task: &mut Task,
2930 claim: crate::queue::Claim,
2931) -> Result<()> {
2932 let home = crate::run::home();
2933 let job = spawn_claimed(&home, opts, queue, task, claim).await?;
2934 loop {
2935 crate::worker::active(&home)?;
2938 let current = crate::worker::get(&home, &job.id)?;
2939 if matches!(
2940 current.status,
2941 crate::worker::Status::Finished | crate::worker::Status::Failed
2942 ) {
2943 *task = queue.get(&task.id)?;
2944 anyhow::ensure!(
2945 current.status != crate::worker::Status::Failed,
2946 "task worker failed: {}",
2947 current.result.as_deref().unwrap_or("unknown failure")
2948 );
2949 return Ok(());
2950 }
2951 tokio::time::sleep(Duration::from_millis(200)).await;
2952 }
2953}
2954
2955async fn persist_cooldown(home: &Path, quota: &[QuotaLoss]) -> Result<()> {
2956 if let Some(until) = cooldown_until(quota, Timestamp::now()) {
2957 let _lease = loop {
2958 if let Some(lease) = crate::worker::try_lease(home, "task-quota-cooldown")? {
2959 break lease;
2960 }
2961 tokio::time::sleep(Duration::from_millis(10)).await;
2962 };
2963 if read_cooldown(home)?.is_none_or(|previous| previous < until) {
2964 let path = home.join("task-quota-cooldown.json");
2965 let temporary = path.with_extension("json.tmp");
2966 std::fs::write(&temporary, serde_json::to_vec(&until)?)?;
2967 std::fs::rename(temporary, path)?;
2968 }
2969 }
2970 Ok(())
2971}
2972
2973fn read_cooldown(home: &Path) -> Result<Option<Timestamp>> {
2974 match std::fs::read(home.join("task-quota-cooldown.json")) {
2975 Ok(body) => Ok(Some(serde_json::from_slice(&body)?)),
2976 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
2977 Err(error) => Err(error.into()),
2978 }
2979}
2980
2981pub async fn serve(opts: Opts) -> Result<()> {
2987 tracing::info!(
2988 "automatic update and restart requires magi web; standalone serve does not restart"
2989 );
2990 serve_until(opts, Stop::new()).await
2991}
2992
2993pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
3004 let opts = opts.absolute()?;
3005 let home = crate::run::home();
3006 let _scheduler = crate::worker::try_lease(&home, "scheduler")?
3007 .context("another scheduler already owns this home")?;
3008 if let Some(reading) = read_status(&home)
3009 && legacy_scheduler_running(&reading, Timestamp::now(), std::process::id())
3010 {
3011 bail!("a legacy scheduler is still running; stop it before starting independent dispatch");
3012 }
3013 if !crate::worker::active(&home)?
3014 .iter()
3015 .any(|job| job.kind == "scheduler")
3016 {
3017 crate::worker::clear_control(&home, "scheduler")?;
3018 }
3019 std::fs::write(
3020 home.join("scheduler-options.json"),
3021 serde_json::to_vec(&opts)?,
3022 )?;
3023 let control = {
3024 let home = home.clone();
3025 let stop = stop.clone();
3026 tokio::spawn(async move {
3027 loop {
3028 match crate::worker::control(&home, "scheduler").ok().flatten() {
3029 Some(crate::worker::Control::Park) => {
3030 let _ = request_control(&home, crate::worker::Control::Park);
3031 stop.park(crate::run::ParkCause::Operator);
3032 break;
3033 }
3034 Some(crate::worker::Control::Stop) => {
3035 stop.stop();
3036 break;
3037 }
3038 None => {}
3039 }
3040 tokio::time::sleep(Duration::from_millis(100)).await;
3041 }
3042 })
3043 };
3044 let signal = {
3045 let stop = stop.clone();
3046 tokio::spawn(async move {
3047 if tokio::signal::ctrl_c().await.is_ok() {
3048 stop.stop();
3049 tracing::info!("scheduler shutdown requested; independent workers continue");
3050 }
3051 })
3052 };
3053
3054 let worktrees_root = opts
3055 .worktrees_root
3056 .clone()
3057 .unwrap_or_else(crate::run::default_worktree_root);
3058 let outcome = drive(
3059 &opts,
3060 &Queue::open(),
3061 &status_path(),
3062 &crate::run::home(),
3063 &worktrees_root,
3064 &stop,
3065 )
3066 .await;
3067
3068 signal.abort();
3069 control.abort();
3070 outcome
3071}
3072
3073async fn drive(
3086 opts: &Opts,
3087 queue: &Queue,
3088 status_file: &Path,
3089 home: &Path,
3090 worktrees_root: &Path,
3091 stop: &Stop,
3092) -> Result<()> {
3093 let recovery_cfg = prepare(&opts.repo, opts).ok();
3101 let daemon_cfg = recovery_cfg
3102 .as_ref()
3103 .map(|c| c.daemon.clone())
3104 .unwrap_or_default();
3105 let reconciled = crate::driver::reconcile(home);
3106 if !reconciled.is_empty() {
3107 tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
3108 }
3109 let mut initial_status = Status::new();
3110 let owned = owned_task_jobs(home)?;
3111 initial_status.current = current_work(home, Timestamp::now())
3112 .into_iter()
3113 .filter(|current| {
3114 owned
3115 .iter()
3116 .any(|job| job.key.strip_prefix("task:") == Some(current.task.as_str()))
3117 })
3118 .collect();
3119 initial_status.idle = initial_status.current.is_empty();
3120 initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
3121 recovery_cfg.as_ref(),
3122 daemon_cfg.max_deputies,
3123 ));
3124 let status = Arc::new(Mutex::new(initial_status));
3125 write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
3126 let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
3127
3128 let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
3134
3135 tracing::info!(
3136 "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
3137 queue.root().display(),
3138 opts.poll.as_secs(),
3139 opts.max_attempts,
3140 concurrency,
3141 if daemon_cfg.pause_for_interrupts {
3142 ", interrupts enabled"
3143 } else {
3144 ""
3145 }
3146 );
3147
3148 let outcome = tokio::select! {
3149 outcome = poll(opts, queue, &status, home, worktrees_root, stop, DispatchLimits {
3150 max_concurrent: concurrency,
3151 pause_for_interrupts: daemon_cfg.pause_for_interrupts,
3152 recovery_cfg,
3153 }) => outcome,
3154 () = async {
3155 while !stop.stopped() {
3156 tokio::time::sleep(Duration::from_millis(25)).await;
3157 }
3158 } => {
3159 if stop.parking() {
3160 request_control(home, crate::worker::Control::Park)?;
3161 }
3162 Ok(())
3163 }
3164 };
3165
3166 stop.busy.store(0, Ordering::SeqCst);
3167 beat.abort();
3168 clear_status_at(status_file);
3169 outcome
3170}
3171
3172pub(crate) fn release_watch_settings_from_config(
3175 home: &Path,
3176 repo: &Path,
3177 cfg: &Config,
3178) -> (Vec<PathBuf>, u64) {
3179 let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
3180 .into_iter()
3181 .map(|r| r.path)
3182 .collect();
3183 let mut known: Vec<PathBuf> = Queue::at(home.join("queue"))
3186 .list()
3187 .into_iter()
3188 .map(|t| t.repo)
3189 .collect();
3190 let runs = home.join("runs");
3191 for id in crate::run::list_ids_in(&runs) {
3192 let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
3193 .ok()
3194 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
3195 .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
3196 known.extend(repo);
3197 }
3198 for k in known {
3199 let k = k.canonicalize().unwrap_or(k);
3200 if k.join(".git").exists() && !paths.contains(&k) {
3201 paths.push(k);
3202 }
3203 }
3204 let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
3205 if !paths.contains(&own) {
3206 paths.push(own);
3207 }
3208 (paths, cfg.daemon.release_stall_minutes)
3209}
3210
3211const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
3213
3214async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
3220 loop {
3221 tokio::time::sleep(HEARTBEAT).await;
3222 let snapshot = {
3223 let mut guard = lock(&status);
3224 guard.updated_at = Timestamp::now();
3225 guard.clone()
3226 };
3227 if let Err(e) = write_status_to(&path, &snapshot) {
3228 tracing::warn!("could not refresh the daemon status file: {e:#}");
3231 }
3232 }
3233}
3234
3235#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3238enum LandResume {
3239 NotLanding,
3242 StillWaiting,
3247 Ready,
3251}
3252
3253fn land_resume_state(task: &Task) -> LandResume {
3257 if task.sync_only.is_some() {
3258 return LandResume::NotLanding;
3259 }
3260 let Some(run_id) = task.execution_runs().last() else {
3261 return LandResume::NotLanding;
3262 };
3263 let Ok(state) = RunState::load(run_id) else {
3264 return LandResume::NotLanding;
3265 };
3266 if !state.parked {
3267 return LandResume::NotLanding;
3268 }
3269 if state.status == RunStatus::Landing
3270 && state.land_approval.as_ref().is_some_and(|binding| {
3271 ask::Questions::open()
3272 .get_for_effects(&binding.question)
3273 .is_ok_and(|q| {
3274 q.run == state.id
3275 && q.resolution()
3276 .as_deref()
3277 .is_some_and(crate::merge_decision::stops)
3278 })
3279 })
3280 {
3281 return LandResume::Ready;
3282 }
3283 if !implementers_match(task, &state) {
3284 return LandResume::NotLanding;
3285 }
3286 let node = if state.status == RunStatus::Landing {
3290 land::APPROVAL_NODE
3291 } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
3292 crate::github_text::ASK_NODE
3293 } else {
3294 return LandResume::NotLanding;
3295 };
3296 let store = ask::Questions::open();
3297 let waiting = store
3298 .list_for_effects()
3299 .into_iter()
3300 .filter(|q| &q.run == run_id && q.node == node)
3301 .max_by(|a, b| a.id.cmp(&b.id));
3302 let Some(mut q) = waiting else {
3303 return LandResume::Ready;
3304 };
3305 if !q.status.open() {
3306 if q.resolution().as_deref() == Some(land::REPAIR) {
3309 return if state.liveness(false) == Liveness::Live {
3310 LandResume::StillWaiting
3311 } else {
3312 LandResume::NotLanding
3313 };
3314 }
3315 return LandResume::Ready;
3316 }
3317 let timeout = Duration::from_secs(state.config.graph.answer_timeout);
3324 let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
3325 if !store.held_reply(&q.id) && elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
3326 q.abandon(format!(
3327 "no answer within {}s of asking",
3328 timeout.as_secs().max(1)
3329 ));
3330 if store.put(&mut q).is_ok() {
3333 return LandResume::Ready;
3334 }
3335 }
3336 LandResume::StillWaiting
3337}
3338
3339const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
3347
3348const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
3360
3361#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3374enum Interrupt {
3375 Idle,
3377 Parking {
3389 parked: Vec<String>,
3390 interrupt_task: String,
3391 },
3392 Running {
3400 parked: Vec<String>,
3401 interrupt_task: String,
3402 },
3403 Resuming { parked: Vec<String> },
3410}
3411
3412fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
3433 match state {
3434 Interrupt::Idle => {
3435 if in_flight.len() != 1 {
3447 return Interrupt::Idle;
3448 }
3449 match runnable.iter().find(|t| t.interrupt) {
3450 Some(t) => Interrupt::Parking {
3451 parked: in_flight.to_vec(),
3452 interrupt_task: t.id.clone(),
3453 },
3454 None => Interrupt::Idle,
3455 }
3456 }
3457 Interrupt::Parking {
3458 parked,
3459 interrupt_task,
3460 } => {
3461 if in_flight.iter().any(|id| parked.contains(id)) {
3462 Interrupt::Parking {
3464 parked,
3465 interrupt_task,
3466 }
3467 } else if in_flight.contains(&interrupt_task) {
3468 Interrupt::Running {
3469 parked,
3470 interrupt_task,
3471 }
3472 } else if runnable.iter().any(|t| t.id == interrupt_task) {
3473 Interrupt::Parking {
3477 parked,
3478 interrupt_task,
3479 }
3480 } else {
3481 Interrupt::Resuming { parked }
3486 }
3487 }
3488 Interrupt::Running {
3489 parked,
3490 interrupt_task,
3491 } => {
3492 if in_flight.contains(&interrupt_task) {
3493 Interrupt::Running {
3494 parked,
3495 interrupt_task,
3496 }
3497 } else {
3498 Interrupt::Resuming { parked }
3504 }
3505 }
3506 Interrupt::Resuming { parked } => {
3507 if in_flight.iter().any(|id| parked.contains(id)) {
3508 Interrupt::Idle
3514 } else if runnable.iter().any(|t| parked.contains(&t.id)) {
3515 Interrupt::Resuming { parked }
3516 } else {
3517 Interrupt::Idle
3520 }
3521 }
3522 }
3523}
3524
3525fn advance_interrupt_tick(
3531 enabled: bool,
3532 state: Interrupt,
3533 in_flight: &[String],
3534 runnable: &[Task],
3535) -> Interrupt {
3536 if !enabled {
3537 return Interrupt::Idle;
3538 }
3539 advance_interrupt(state, in_flight, runnable)
3540}
3541
3542fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
3547 match state {
3548 Interrupt::Idle => candidates,
3549 Interrupt::Parking {
3550 parked,
3551 interrupt_task,
3552 } => {
3553 if in_flight.iter().any(|id| parked.contains(id)) {
3554 Vec::new()
3555 } else {
3556 candidates
3557 .into_iter()
3558 .filter(|t| &t.id == interrupt_task)
3559 .collect()
3560 }
3561 }
3562 Interrupt::Running { .. } => Vec::new(),
3563 Interrupt::Resuming { parked } => candidates
3571 .into_iter()
3572 .find(|t| parked.contains(&t.id))
3573 .into_iter()
3574 .collect(),
3575 }
3576}
3577
3578struct DispatchLimits {
3582 max_concurrent: usize,
3585 pause_for_interrupts: bool,
3587 recovery_cfg: Option<Config>,
3588}
3589
3590#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3599enum PermitKind {
3600 None,
3605 Urgent,
3612 #[default]
3615 Ordinary,
3616}
3617
3618fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
3621 if priority {
3622 PermitKind::None
3623 } else if urgent {
3624 PermitKind::Urgent
3625 } else {
3626 PermitKind::Ordinary
3627 }
3628}
3629
3630fn available_slots(requests: &[TaskWorker], limit: usize) -> (usize, usize) {
3631 let (ordinary, urgent) = requests.iter().filter(|request| !request.standalone).fold(
3632 (0usize, 0usize),
3633 |(ordinary, urgent), request| match request.lane {
3634 PermitKind::Ordinary => (ordinary + 1, urgent),
3635 PermitKind::Urgent => (ordinary, urgent + 1),
3636 PermitKind::None => (ordinary, urgent),
3637 },
3638 );
3639 (
3640 limit.saturating_sub(ordinary),
3641 1usize.saturating_sub(urgent),
3642 )
3643}
3644
3645#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
3647enum SkipReason {
3648 ClaimUnavailable,
3649 RereadFailed,
3650 NoLongerRunnable,
3651 WaitingOnLanding,
3652 CoolingDown,
3653 OrdinaryCapacity,
3654 UrgentCapacity,
3655 InterruptGate,
3656}
3657
3658impl SkipReason {
3659 fn key(self) -> &'static str {
3660 match self {
3661 Self::ClaimUnavailable => "claim_unavailable",
3662 Self::RereadFailed => "reread_failed",
3663 Self::NoLongerRunnable => "no_longer_runnable",
3664 Self::WaitingOnLanding => "waiting_on_landing",
3665 Self::CoolingDown => "cooling_down",
3666 Self::OrdinaryCapacity => "ordinary_capacity",
3667 Self::UrgentCapacity => "urgent_capacity",
3668 Self::InterruptGate => "interrupt_gate",
3669 }
3670 }
3671
3672 fn describe(self) -> &'static str {
3673 match self {
3674 Self::ClaimUnavailable => "could not claim it (held elsewhere or claim failed)",
3675 Self::RereadFailed => "could not re-read it",
3676 Self::NoLongerRunnable => "no longer runnable",
3677 Self::WaitingOnLanding => "waiting on landing",
3678 Self::CoolingDown => "quota cooldown",
3679 Self::OrdinaryCapacity => "no free ordinary slot",
3680 Self::UrgentCapacity => "urgent slot busy",
3681 Self::InterruptGate => "withheld by the interrupt sequence",
3682 }
3683 }
3684}
3685
3686#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3688pub struct DispatchReasonCount {
3689 pub reason: String,
3691 pub count: usize,
3693}
3694
3695#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3697pub struct DispatchWait {
3698 pub runnable: usize,
3700 pub reasons: Vec<DispatchReasonCount>,
3702}
3703
3704type DispatchSkips = std::collections::BTreeSet<(String, SkipReason)>;
3705
3706fn aggregate_dispatch_wait(runnable: usize, skips: &DispatchSkips) -> Option<DispatchWait> {
3707 if runnable == 0 {
3708 return None;
3709 }
3710 let mut counts = std::collections::BTreeMap::new();
3711 for (_, reason) in skips {
3712 *counts.entry(*reason).or_insert(0usize) += 1;
3713 }
3714 let mut counts: Vec<_> = counts.into_iter().collect();
3715 counts.sort_by(|(a, n), (b, m)| m.cmp(n).then(a.cmp(b)));
3716 Some(DispatchWait {
3717 runnable,
3718 reasons: counts
3719 .into_iter()
3720 .map(|(reason, count)| DispatchReasonCount {
3721 reason: reason.key().to_owned(),
3722 count,
3723 })
3724 .collect(),
3725 })
3726}
3727
3728fn interrupt_skips(before: &[String], after: &[Task]) -> DispatchSkips {
3729 before
3730 .iter()
3731 .filter(|id| !after.iter().any(|task| &task.id == *id))
3732 .map(|id| (id.clone(), SkipReason::InterruptGate))
3733 .collect()
3734}
3735
3736fn changed_dispatch_skips(previous: &mut DispatchSkips, current: DispatchSkips) -> bool {
3737 if *previous == current {
3738 return false;
3739 }
3740 *previous = current;
3741 true
3742}
3743
3744struct DispatchClaim {
3745 task: Task,
3746 claim: crate::queue::Claim,
3747 permit: Option<tokio::sync::OwnedSemaphorePermit>,
3748}
3749
3750fn claim_dispatch(
3753 queue: &Queue,
3754 candidate: &Task,
3755 cooling_down: bool,
3756 ordinary: &Arc<tokio::sync::Semaphore>,
3757 urgent: &Arc<tokio::sync::Semaphore>,
3758) -> std::result::Result<DispatchClaim, SkipReason> {
3759 let claim = queue
3760 .claim(&candidate.id)
3761 .map_err(|_| SkipReason::ClaimUnavailable)?;
3762 let task = match queue.get(&candidate.id) {
3763 Ok(t) if t.status.runnable() => t,
3764 Ok(_) => return Err(SkipReason::NoLongerRunnable),
3765 Err(e) => {
3766 tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
3767 return Err(SkipReason::RereadFailed);
3768 }
3769 };
3770 let resume = land_resume_state(&task);
3771 if resume == LandResume::StillWaiting {
3772 return Err(SkipReason::WaitingOnLanding);
3773 }
3774 let priority = resume == LandResume::Ready;
3775 if !priority && cooling_down {
3776 return Err(SkipReason::CoolingDown);
3777 }
3778 let permit = match permit_kind(priority, task.urgent) {
3781 PermitKind::None => None,
3782 PermitKind::Urgent => Some(
3783 Arc::clone(urgent)
3784 .try_acquire_owned()
3785 .map_err(|_| SkipReason::UrgentCapacity)?,
3786 ),
3787 PermitKind::Ordinary => Some(
3788 Arc::clone(ordinary)
3789 .try_acquire_owned()
3790 .map_err(|_| SkipReason::OrdinaryCapacity)?,
3791 ),
3792 };
3793 let stamp = Timestamp::now();
3796 let mut task = task;
3797 task.dispatched_at = Some(stamp);
3798 if let Err(e) = queue.modify(&task.id, |t| {
3799 t.dispatched_at = Some(stamp);
3800 true
3801 }) {
3802 tracing::warn!("could not record dispatch order of {}: {e:#}", task.short());
3803 }
3804 Ok(DispatchClaim {
3805 task,
3806 claim,
3807 permit,
3808 })
3809}
3810
3811#[derive(Serialize, Deserialize)]
3830struct ServiceWorker {
3831 opts: Opts,
3832 queue: PathBuf,
3833 worktrees_root: PathBuf,
3834 operation: String,
3835}
3836
3837fn load_conductor(home: &Path) -> Result<Conductor> {
3838 match std::fs::read(home.join("conductor-state.json")) {
3839 Ok(body) => serde_json::from_slice(&body).context("read conductor state"),
3840 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Conductor::new()),
3841 Err(error) => Err(error.into()),
3842 }
3843}
3844
3845fn conductor_work(queue: &Queue, home: &Path) -> (Vec<Task>, Vec<Task>, Vec<Task>) {
3846 let live: std::collections::BTreeSet<_> = current_work(home, Timestamp::now())
3847 .into_iter()
3848 .map(|c| c.task)
3849 .collect();
3850 let stalled = stalled_tasks(queue, home, Timestamp::now());
3851 let stalled_ids: std::collections::BTreeSet<_> = stalled.iter().map(|t| t.id.clone()).collect();
3852 let finished = finished_tasks(queue)
3853 .into_iter()
3854 .filter(|t| !live.contains(&t.id) && !stalled_ids.contains(&t.id))
3855 .filter(|t| !awaiting_resume_with(t, |id| RunState::load_under(id, home)))
3856 .collect();
3857 let queued = queued_tasks(queue)
3858 .into_iter()
3859 .filter(|t| !live.contains(&t.id))
3860 .collect();
3861 (queued, stalled, finished)
3862}
3863
3864fn retention_service_receipt(
3867 home: &Path,
3868 operation: &str,
3869 phase: &str,
3870 outcome: &str,
3871 detail: &str,
3872 cfg: Option<&Config>,
3873) {
3874 if !matches!(operation, "housekeeping" | "disk-pressure") {
3875 return;
3876 }
3877 let receipt = serde_json::json!({"checked_at": Timestamp::now(),
3878 "version": env!("CARGO_PKG_VERSION"), "pid": std::process::id(),
3879 "operation": operation, "outcome": outcome, "detail": detail,
3880 "auto_fold": cfg.map(|c| c.disk.auto_fold),
3881 "reclaim_bytes": cfg.map(|c| c.disk.worktree_reclaim_bytes)});
3882 if let Err(error) = crate::fold_evidence::atomic_write(
3883 &home.join(format!("source-eviction-{operation}-{phase}.json")),
3884 &serde_json::to_vec(&receipt).expect("service receipt"),
3885 ) {
3886 tracing::warn!("retention service receipt failed: {error:#}");
3887 }
3888}
3889
3890async fn start_service(
3891 home: &Path,
3892 opts: &Opts,
3893 queue: &Queue,
3894 worktrees_root: &Path,
3895 operation: &str,
3896 cfg: Option<&Config>,
3897 busy: bool,
3898) -> Result<()> {
3899 let fetch_cfg = if operation == "fetch" {
3902 match prepare(&opts.repo, opts) {
3903 Ok(cfg) => Some(cfg),
3904 Err(error) => {
3905 tracing::warn!("could not reload periodic fetch configuration: {error:#}");
3906 return Ok(());
3907 }
3908 }
3909 } else {
3910 None
3911 };
3912 let cfg = fetch_cfg.as_ref().or(cfg);
3913 let ticks = home.join("service-ticks");
3914 std::fs::create_dir_all(&ticks)?;
3915 let receipt = ticks.join(format!("daemon-{operation}"));
3916 let last = std::fs::read(&receipt)
3917 .ok()
3918 .and_then(|body| serde_json::from_slice::<Timestamp>(&body).ok());
3919 let interval = match operation {
3920 "disk-pressure" => 30,
3921 "chat-goals" => 60,
3922 "cache" => CACHE_CHECK_INTERVAL_SECS,
3923 "fetch" => cfg.map_or(60, |cfg| cfg.repos.fetch_interval.max(1)),
3924 _ => opts.poll.as_secs().max(1),
3925 };
3926 let now = Timestamp::now();
3927 if !cache_check_due(last, now, interval) {
3928 retention_service_receipt(
3929 home,
3930 operation,
3931 "dispatch",
3932 "skipped",
3933 "cadence not due",
3934 cfg,
3935 );
3936 return Ok(());
3937 }
3938 let key = format!("service:daemon-{operation}");
3939 if crate::worker::active(home)?
3940 .iter()
3941 .any(|job| job.key == key)
3942 {
3943 retention_service_receipt(
3944 home,
3945 operation,
3946 "dispatch",
3947 "skipped",
3948 "service worker already active",
3949 cfg,
3950 );
3951 return Ok(());
3952 }
3953 let eligible = match operation {
3954 "conductor" => {
3955 let (queued, stalled, finished) = conductor_work(queue, home);
3956 !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3957 && load_conductor(home)?.worth_a_look(queue, &stalled, &finished)
3958 }
3959 "maintenance" => {
3960 queue.list().iter().any(|task| {
3961 crate::triage::disk_wait_eligible(task)
3962 && task
3963 .disk_checked_at
3964 .is_none_or(|at| now.as_second() - at.as_second() >= 60)
3965 }) || Questions::at(home.join("questions"))
3966 .list_for_effects()
3967 .iter()
3968 .any(|q| {
3969 q.chosen_action().is_some_and(|action| action.maintenance())
3970 && !home
3971 .join("choice-actions")
3972 .join(format!("{}.json", q.id))
3973 .exists()
3974 })
3975 }
3976 "housekeeping" => !busy && runnable(queue).is_empty(),
3977 "cache" => {
3978 !busy
3979 && !runnable(queue).is_empty()
3980 && cfg.is_some_and(|cfg| cfg.disk.cache_limit_bytes > 0)
3981 }
3982 "disk-pressure" => busy,
3983 "fetch" => {
3984 cfg.is_some_and(|cfg| cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty())
3985 }
3986 "chat-goals" => crate::talk::Talks::at(home.join("talks"))
3987 .list()
3988 .iter()
3989 .any(|talk| {
3990 talk.status.open()
3991 && talk.pending.is_empty()
3992 && talk.pending_attachments.is_empty()
3993 && talk.goals.iter().any(|goal| goal.active())
3994 }),
3995 _ => false,
3996 };
3997 if !eligible {
3998 retention_service_receipt(
3999 home,
4000 operation,
4001 "dispatch",
4002 "skipped",
4003 if operation == "housekeeping" {
4004 "active work or runnable task queue"
4005 } else {
4006 "no active work; idle housekeeping owns scan"
4007 },
4008 cfg,
4009 );
4010 return Ok(());
4011 }
4012 retention_service_receipt(
4013 home,
4014 operation,
4015 "dispatch",
4016 "launching",
4017 "eligible and cadence due",
4018 cfg,
4019 );
4020 let request = ServiceWorker {
4021 opts: opts.absolute()?,
4022 queue: std::path::absolute(queue.root())?,
4023 worktrees_root: std::path::absolute(worktrees_root)?,
4024 operation: operation.to_owned(),
4025 };
4026 if let Err(error) =
4027 crate::worker::spawn(home, "daemon-service", &key, serde_json::to_value(request)?).await
4028 {
4029 retention_service_receipt(
4030 home,
4031 operation,
4032 "dispatch",
4033 "error",
4034 &format!("worker launch: {error:#}"),
4035 cfg,
4036 );
4037 tracing::warn!(operation, "could not launch daemon service: {error:#}");
4038 }
4039 std::fs::write(receipt, serde_json::to_vec(&now)?)?;
4040 Ok(())
4041}
4042
4043pub async fn run_service_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
4046 let request: ServiceWorker = serde_json::from_value(payload)?;
4047 let opts = &request.opts;
4048 let queue = Queue::at(request.queue);
4049 let questions = Questions::at(home.join("questions"));
4050 match request.operation.as_str() {
4051 "chat-goals" => {
4052 let talks = crate::talk::Talks::at(home.join("talks"));
4053 crate::chat_goal_runtime::sweep(&talks, false).await;
4054 }
4055 "maintenance" => {
4056 apply_maintenance_choices(&queue, &questions, home).await;
4057 triage::monitor_disk_waits(
4058 &queue,
4059 &questions,
4060 opts.config.as_deref(),
4061 Timestamp::now(),
4062 );
4063 }
4064 "conductor" => {
4065 let path = home.join("conductor-state.json");
4066 let mut conductor = load_conductor(home)?;
4067 let (queued, stalled, finished) = conductor_work(&queue, home);
4068 if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
4069 && conductor.worth_a_look(&queue, &stalled, &finished)
4070 {
4071 let cfg = prepare(&opts.repo, opts)?;
4072 conductor
4073 .maybe_run(
4074 &cfg,
4075 &opts.repo,
4076 &queue,
4077 &questions,
4078 home,
4079 &queued,
4080 &stalled,
4081 &finished,
4082 opts.max_attempts,
4083 )
4084 .await;
4085 let temporary = path.with_extension("json.tmp");
4086 std::fs::write(&temporary, serde_json::to_vec(&conductor)?)?;
4087 std::fs::rename(temporary, path)?;
4088 }
4089 }
4090 "fetch" => {
4091 let cfg = prepare(&opts.repo, opts)?;
4092 if cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty() {
4093 let outcome = clean::fetch_origins(&cfg.repos.roots, FETCH_TIMEOUT, || false).await;
4094 tracing::debug!("fetch origins: {outcome:?}");
4095 }
4096 }
4097 "cache" => {
4098 if task_jobs(home)?.is_empty() {
4099 let mut checked = None;
4100 maybe_prune_cache_between_runs(
4101 &opts.repo,
4102 opts,
4103 home,
4104 &Stop::new(),
4105 &mut checked,
4106 Timestamp::now(),
4107 )
4108 .await;
4109 }
4110 }
4111 "disk-pressure" => {
4112 if let Ok(cfg) = prepare(&opts.repo, opts) {
4113 retention_service_receipt(
4114 home,
4115 "disk-pressure",
4116 "worker",
4117 "running",
4118 "retention sweep",
4119 Some(&cfg),
4120 );
4121 crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
4122 if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
4123 tracing::warn!("disk pressure cache cleanup failed: {e:#}");
4124 }
4125 if let Err(e) = crate::build_target::prune_registered(home, &cfg.disk) {
4126 tracing::warn!("disk pressure isolated build cleanup failed: {e:#}");
4127 }
4128 for current in current_work(home, Timestamp::now()) {
4129 if let Ok(state) = RunState::load_under(¤t.run, home)
4130 && let Some(reason) = disk_gate(&state.repo, &state.config)
4131 {
4132 for job in owned_task_jobs(home)?.into_iter().filter(|job| {
4133 job.key.strip_prefix("task:") == Some(current.task.as_str())
4134 }) {
4135 request_task_park(
4136 home,
4137 &job,
4138 crate::run::ParkCause::Interrupt {
4139 reason: reason.clone(),
4140 },
4141 )?;
4142 }
4143 notices::raise_in(
4144 home,
4145 Notice::warn(
4146 "disk:pressure",
4147 "Disk pressure persists after cleanup; active workers were asked to checkpoint and park. New starts and resumes wait for free space.",
4148 ),
4149 );
4150 }
4151 }
4152 } else {
4153 retention_service_receipt(
4154 home,
4155 "disk-pressure",
4156 "worker",
4157 "error",
4158 "configuration could not be loaded",
4159 None,
4160 );
4161 }
4162 }
4163 "housekeeping" => {
4164 if task_jobs(home)?.is_empty() {
4165 match prepare(&opts.repo, opts) {
4166 Ok(cfg) => {
4167 retention_service_receipt(
4168 home,
4169 "housekeeping",
4170 "worker",
4171 "running",
4172 "retention sweep",
4173 Some(&cfg),
4174 );
4175 crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
4176 }
4177 Err(error) => retention_service_receipt(
4178 home,
4179 "housekeeping",
4180 "worker",
4181 "error",
4182 &format!("configuration: {error:#}"),
4183 None,
4184 ),
4185 }
4186 janitor(&opts.repo, opts, home, &request.worktrees_root).await;
4187 resweep_superseded_attempts(&queue, home);
4188 triage_held(&queue, home, opts).await;
4189 } else {
4190 retention_service_receipt(
4191 home,
4192 "housekeeping",
4193 "worker",
4194 "skipped",
4195 "task worker became active",
4196 None,
4197 );
4198 }
4199 }
4200 operation => bail!("unknown daemon service {operation}"),
4201 }
4202 Ok(())
4203}
4204
4205fn task_worker_spawn_error(home: &Path, request: &TaskWorker, error: anyhow::Error) -> Result<()> {
4209 let key = format!("task:{}", request.task);
4210 let payload = serde_json::to_value(request)?;
4211 if crate::worker::active(home)?
4212 .iter()
4213 .any(|job| job.key == key && job.kind == "task" && job.payload != payload)
4214 {
4215 tracing::warn!(
4216 "task {} acquired a competing worker reservation: {error:#}",
4217 crate::run::short_of(&request.task)
4218 );
4219 return Ok(());
4220 }
4221 tracing::error!("task worker startup stopped dispatch: {error:#}");
4222 notices::raise_in(
4223 home,
4224 Notice::error(
4225 "loop:worker-startup",
4226 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),
4229 ).link(Link::Task { id: request.task.clone() }),
4230 );
4231 Err(error).with_context(|| {
4232 format!(
4233 "cannot start task {} worker; dispatcher stopped; any unacknowledged reservation remains occupied",
4234 crate::run::short_of(&request.task)
4235 )
4236 })
4237}
4238
4239async fn poll(
4240 opts: &Opts,
4241 queue: &Queue,
4242 status: &Arc<Mutex<Status>>,
4243 home: &Path,
4244 worktrees_root: &Path,
4245 stop: &Stop,
4246 limits: DispatchLimits,
4247) -> Result<()> {
4248 let mut attempted = Vec::new();
4249 let mut settling_once_services = false;
4250 let interrupt_path = home.join("scheduler-interrupt.json");
4251 let mut interrupt = match std::fs::read(&interrupt_path) {
4252 Ok(body) => serde_json::from_slice(&body).context("read scheduler interrupt state")?,
4253 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Interrupt::Idle,
4254 Err(error) => return Err(error.into()),
4255 };
4256 let mut previous = std::collections::BTreeSet::<String>::new();
4257 let mut previous_skips = DispatchSkips::new();
4258 while !stop.stopped() {
4259 let jobs: Vec<_> = crate::worker::active(home)?
4260 .into_iter()
4261 .filter(|job| job.kind == "task")
4262 .collect();
4263 let requests: Vec<_> = jobs
4264 .iter()
4265 .map(|job| {
4266 serde_json::from_value::<TaskWorker>(job.payload.clone())
4267 .with_context(|| format!("read live task worker {}", job.id))
4268 })
4269 .collect::<Result<_>>()?;
4270 let live: std::collections::BTreeSet<_> = requests.iter().map(|r| r.task.clone()).collect();
4271 let owned: std::collections::BTreeSet<_> = requests
4272 .iter()
4273 .filter(|r| !r.standalone)
4274 .map(|r| r.task.clone())
4275 .collect();
4276 let current: Vec<_> = requests
4277 .iter()
4278 .zip(&jobs)
4279 .filter(|(request, _)| !request.standalone)
4280 .map(|(request, job)| Current {
4281 worker: Some(job.id.clone()),
4282 task: request.task.clone(),
4283 run: queue
4284 .get(&request.task)
4285 .ok()
4286 .and_then(|task| task.execution_runs().last().cloned())
4287 .unwrap_or_default(),
4288 })
4289 .collect();
4290 {
4291 let mut snapshot = lock(status);
4292 snapshot.polls += 1;
4293 snapshot.completed += previous.difference(&owned).count();
4294 snapshot.current = current;
4295 snapshot.idle = owned.is_empty();
4296 snapshot.dispatch_wait = None;
4297 }
4298 previous = owned.clone();
4299 stop.busy.store(owned.len(), Ordering::SeqCst);
4300
4301 let (ordinary, urgent) = available_slots(&requests, limits.max_concurrent);
4304 let sem = Arc::new(tokio::sync::Semaphore::new(ordinary));
4305 let urgent_sem = Arc::new(tokio::sync::Semaphore::new(urgent));
4306 let mut permits = Vec::new();
4307 sweep_stale_claims(queue, STALE_CLAIM);
4308 reclaim_orphaned_running(queue, opts.max_attempts, &live);
4309 reclaim_abandoned_runs(home, Timestamp::now());
4310 let questions = Questions::at(home.join("questions"));
4311
4312 crate::task_chat::sweep(
4315 queue,
4316 &crate::talk::Talks::at(home.join("talks")),
4317 &questions,
4318 home,
4319 );
4320 if let Err(error) = crate::task_inquiry::Outbox::at(home)
4321 .sweep(queue, &crate::talk::Talks::at(home.join("talks")))
4322 {
4323 tracing::warn!("task inquiry delivery remains pending: {error:#}");
4324 }
4325 repair_choice_offers(&questions);
4326 resolve_blockers(queue, &questions);
4327 apply_task_choice_actions(queue, &questions, home);
4328 triage::apply_answers(queue, &questions);
4329 reconcile_task_questions(queue, &questions);
4330 let talks = crate::talk::Talks::at(home.join("talks"));
4331 crate::chat_notify::sweep(queue, &talks, home);
4332 crate::notice_delivery::sweep(queue, &talks, home, &opts.repo);
4333 crate::chat_watch::sweep(home, &talks);
4334 if let Err(error) = crate::chat_control::reconcile_decisions(queue, home) {
4335 tracing::warn!("decision receipt reconciliation remains pending: {error:#}");
4336 }
4337 let mut turns = tokio::task::JoinSet::new();
4338 crate::chat_notify::start_turns(&talks, stop.parking(), &mut turns);
4339 while turns.join_next().await.is_some() {}
4341
4342 crate::consult::start_services(
4343 home,
4344 &opts.repo,
4345 limits.recovery_cfg.as_ref(),
4346 opts.config.as_deref(),
4347 )
4348 .await?;
4349 for operation in [
4350 "conductor",
4351 "maintenance",
4352 "housekeeping",
4353 "disk-pressure",
4354 "cache",
4355 "fetch",
4356 "chat-goals",
4357 ] {
4358 if settling_once_services {
4362 break;
4363 }
4364 if operation == "chat-goals" && stop.parking() {
4365 continue;
4366 }
4367 start_service(
4368 home,
4369 opts,
4370 queue,
4371 worktrees_root,
4372 operation,
4373 limits.recovery_cfg.as_ref(),
4374 !live.is_empty(),
4375 )
4376 .await?;
4377 }
4378 let latest = crate::worker::active(home)?;
4379 if latest.iter().any(|job| job.key == "service:daemon-cache")
4380 || latest
4381 .iter()
4382 .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4383 {
4384 stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4385 continue;
4386 }
4387 let candidates: Vec<Task> = runnable(queue)
4388 .into_iter()
4389 .filter(|task| !live.contains(&task.id))
4390 .filter(|task| !opts.once || !attempted.contains(&task.id))
4391 .collect();
4392 let in_flight: Vec<_> = owned.iter().cloned().collect();
4393 let prior_interrupt = std::mem::discriminant(&interrupt);
4394 interrupt = advance_interrupt_tick(
4395 limits.pause_for_interrupts,
4396 interrupt,
4397 &in_flight,
4398 &candidates,
4399 );
4400 if prior_interrupt != std::mem::discriminant(&interrupt) {
4403 let temporary = interrupt_path.with_extension("json.tmp");
4404 std::fs::write(&temporary, serde_json::to_vec(&interrupt)?)?;
4405 std::fs::rename(temporary, &interrupt_path)?;
4406 }
4407 if let Interrupt::Parking {
4408 parked,
4409 interrupt_task,
4410 } = &interrupt
4411 {
4412 for job in jobs.iter().filter(|job| {
4413 parked
4414 .iter()
4415 .any(|id| job.key.strip_prefix("task:") == Some(id.as_str()))
4416 }) {
4417 if crate::worker::control(home, &job.key)?.is_none() {
4418 request_task_park(
4419 home,
4420 job,
4421 crate::run::ParkCause::Interrupt {
4422 reason: format!(
4423 "task {} asked to run first",
4424 crate::run::short_of(interrupt_task)
4425 ),
4426 },
4427 )?;
4428 }
4429 }
4430 }
4431 let candidate_ids: Vec<_> = candidates.iter().map(|task| task.id.clone()).collect();
4432 let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
4433 let mut skips = interrupt_skips(&candidate_ids, &candidates);
4434 let cooling = read_cooldown(home)?.is_some_and(|until| Timestamp::now() < until);
4435 let mut started = false;
4436 let mut resync = false;
4437 for candidate in candidates {
4438 if stop.stopped() {
4439 break;
4440 }
4441 let DispatchClaim {
4442 task,
4443 claim,
4444 permit,
4445 } = match claim_dispatch(queue, &candidate, cooling, &sem, &urgent_sem) {
4446 Ok(claim) => claim,
4447 Err(reason) => {
4448 skips.insert((candidate.id, reason));
4449 continue;
4450 }
4451 };
4452 if crate::worker::active(home)?
4453 .iter()
4454 .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4455 {
4456 drop(claim);
4457 resync = true;
4458 break;
4459 }
4460 let lane = permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent);
4461 let request = TaskWorker {
4462 opts: opts.absolute()?,
4463 queue: std::path::absolute(queue.root())?,
4464 task: task.id.clone(),
4465 lane,
4466 standalone: false,
4467 };
4468 if let Err(error) = crate::worker::spawn(
4471 home,
4472 "task",
4473 &format!("task:{}", task.id),
4474 serde_json::to_value(&request)?,
4475 )
4476 .await
4477 {
4478 task_worker_spawn_error(home, &request, error)?;
4479 drop(claim);
4480 resync = true;
4481 break;
4482 }
4483 drop(claim);
4484 permits.extend(permit);
4485 attempted.push(task.id);
4486 started = true;
4487 }
4488 if !resync && !stop.stopped() {
4489 if !started {
4490 lock(status).dispatch_wait = aggregate_dispatch_wait(candidate_ids.len(), &skips);
4491 }
4492 if changed_dispatch_skips(&mut previous_skips, skips) {
4493 if previous_skips.is_empty() {
4494 tracing::info!("dispatch skips cleared");
4495 }
4496 for (task, reason) in &previous_skips {
4497 tracing::info!(
4498 task,
4499 reason = reason.key(),
4500 "task {} skipped: {}",
4501 crate::run::short_of(task),
4502 reason.describe()
4503 );
4504 }
4505 }
4506 }
4507 if started || resync {
4508 continue;
4509 }
4510 if owned.is_empty() && opts.once {
4511 settling_once_services = true;
4512 if crate::worker::active(home)?.iter().any(|job| {
4516 job.kind == "daemon-service"
4517 && matches!(
4518 job.key.as_str(),
4519 "service:daemon-housekeeping"
4520 | "service:daemon-conductor"
4521 | "service:daemon-maintenance"
4522 )
4523 }) {
4524 stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4525 continue;
4526 }
4527 break;
4528 }
4529 stop.idle(if live.is_empty() {
4530 opts.poll
4531 } else {
4532 RECHECK_WHILE_BUSY.min(opts.poll)
4533 })
4534 .await;
4535 }
4536 stop.busy.store(0, Ordering::SeqCst);
4539 lock(status).dispatch_wait = None;
4540 Ok(())
4541}
4542
4543async fn resume_owner_lock(home: &Path, id: &str) -> Result<crate::pr_head::OwnerLock> {
4547 let busy = |error: &anyhow::Error| {
4548 error.downcast_ref::<std::io::Error>().is_some_and(|error| {
4549 error.kind() == std::io::ErrorKind::WouldBlock
4550 || cfg!(windows) && error.raw_os_error() == Some(33)
4551 })
4552 };
4553 match crate::pr_head::owner_lock(home, id) {
4554 Ok(lock) => return Ok(lock),
4555 Err(error) if busy(&error) => {}
4556 Err(error) => return Err(error),
4557 }
4558 let wait = RunState::load_under(id, home)?
4559 .config
4560 .graph
4561 .timeout_resource_wait;
4562 crate::pr_head::owner_lock_wait(home, id, Duration::from_secs(wait)).await
4563}
4564
4565async fn public_resume_owner(
4569 home: &Path,
4570 runs: &[String],
4571 repo: &Path,
4572) -> Result<Option<RunState>> {
4573 let mut owner = None;
4574 for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
4575 let _lock = resume_owner_lock(home, id).await?;
4576 let state = RunState::load_under(id, home)?;
4577 if state.released()
4578 || state.retired_to.is_some()
4579 || state.pr_taken_over_by.is_some()
4580 || !crate::handover::landing_checkpoint(&state)
4581 {
4582 continue;
4583 }
4584 anyhow::ensure!(
4585 crate::git::toplevel(&state.repo).await?.canonicalize()?
4586 == crate::git::toplevel(repo).await?.canonicalize()?,
4587 "public owner repository differs; inspect run lineage"
4588 );
4589 anyhow::ensure!(
4590 owner.is_none(),
4591 "multiple retained public owners; inspect run lineage"
4592 );
4593 if let Some(reason) = crate::handover::resume_refusal_under(&state, Some(home)) {
4594 anyhow::bail!(reason.diagnostic(&state));
4595 }
4596 let claimed = is_working_on_other(home, id, Timestamp::now())?;
4597 anyhow::ensure!(
4598 state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
4599 "public owner's driver is live or unknown; wait before retrying"
4600 );
4601 owner = Some(state);
4602 }
4603 Ok(owner)
4604}
4605
4606async fn attempt(
4612 opts: &Opts,
4613 queue: &Queue,
4614 status: &Arc<Mutex<Status>>,
4615 stop: &Stop,
4616 interrupt_pause: crate::graph::Pause,
4617 task: &mut Task,
4618) -> Vec<QuotaLoss> {
4619 if let Some(request) = task.sync_only.clone() {
4620 Box::pin(attempt_sync_only(
4621 queue,
4622 status,
4623 stop,
4624 interrupt_pause,
4625 task,
4626 request,
4627 ))
4628 .await;
4629 return Vec::new();
4630 }
4631 let repo = repo_for(task, &opts.repo);
4632 tracing::info!(
4633 "task {} — {} (repo {})",
4634 task.short(),
4635 task.title,
4636 repo.display()
4637 );
4638
4639 let public_owner = match public_resume_owner(&crate::run::home(), &task.runs, &repo).await {
4640 Ok(owner) => owner,
4641 Err(e) => {
4642 task.hold_machine(Some(format!(
4643 "Cannot verify existing public owner: {e:#}; no attempt started."
4644 )));
4645 record(queue, task);
4646 return Vec::new();
4647 }
4648 };
4649 let resume_runs = public_owner
4650 .as_ref()
4651 .map(|s| vec![s.id.clone()])
4652 .unwrap_or_else(|| task.execution_runs().to_vec());
4653
4654 if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
4658 && previous
4659 .merge_decision
4660 .as_ref()
4661 .is_some_and(|decision| !decision.closed)
4662 && previous.status != RunStatus::Landing
4663 && !crate::merge_decision::resumable_hold(&previous)
4664 {
4665 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)));
4666 record(queue, task);
4667 return Vec::new();
4668 }
4669 let stop_owner = resume_runs
4670 .last()
4671 .and_then(|id| RunState::load(id).ok())
4672 .filter(|state| {
4673 crate::merge_decision::resumable_hold(state)
4674 || state.status == RunStatus::Landing
4675 && state.land_approval.as_ref().is_some_and(|binding| {
4676 Questions::open()
4677 .get_for_effects(&binding.question)
4678 .is_ok_and(|q| {
4679 q.run == state.id
4680 && q.resolution()
4681 .as_deref()
4682 .is_some_and(crate::merge_decision::stops)
4683 })
4684 })
4685 });
4686 if let Some(owner) = stop_owner {
4687 let mut runner = match Runner::resume(&owner.id) {
4688 Ok(runner) => runner,
4689 Err(e) => {
4690 task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
4691 record(queue, task);
4692 return Vec::new();
4693 }
4694 };
4695 runner.on_pause(stop.pause());
4696 runner.watch_interrupt(interrupt_pause);
4697 let quota_before = runner.state.quota.clone();
4698 let before_start = task.clone();
4699 task.start(owner.id.clone());
4700 if let Err(error) = queue.put(task) {
4701 *task = before_start;
4702 let error = runner.fail_startup("task-start", error);
4703 if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
4704 task.record_startup_failure(failure.clone());
4705 }
4706 task.hold_manual(Some(format!(
4707 "Could not persist task start; no agents dispatched: {error:#}"
4708 )));
4709 record(queue, task);
4710 return Vec::new();
4711 }
4712 lock(status).current.push(Current {
4713 worker: None,
4714 task: task.id.clone(),
4715 run: owner.id,
4716 });
4717 runner.state.carry_dispatched_resumes(task);
4718 runner.state.next_pass_task_entry = true;
4719 let result = runner.execute().await;
4720 return finish_attempt(
4721 opts.max_attempts,
4722 queue,
4723 task,
4724 &runner.state,
4725 "a_before,
4726 result,
4727 );
4728 }
4729
4730 if let Some(owner) = &public_owner
4731 && (task.fresh_start || !may_resume_run(owner, task))
4732 {
4733 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)));
4734 record(queue, task);
4735 return Vec::new();
4736 }
4737
4738 if let Some(state) = task
4739 .execution_runs()
4740 .last()
4741 .and_then(|id| RunState::load(id).ok())
4742 && let Some(reason) = crate::repair_budget::conflict_failure(task, &state)
4743 {
4744 task.hold_machine(Some(reason));
4745 record(queue, task);
4746 return Vec::new();
4747 }
4748
4749 if let Some(held) = crate::base_sync_recovery::held_run(queue, task)
4750 && !task.fresh_start
4751 && task.pr_recovery.is_none()
4752 {
4753 let authorized = if crate::repair_budget::conflict_pending(task, &held) {
4756 true
4757 } else if task.resumption.is_some() && compatible_run_instruction(&held, task) {
4758 let home = queue.root().parent().expect("queue has a home");
4759 match Runner::authorize_base_recovery_from_resumption(home, &held.id, &task.id).await {
4760 Ok(()) => true,
4761 Err(error) => {
4762 tracing::debug!(run = %held.id, %error, "base recovery resumption refused");
4763 false
4764 }
4765 }
4766 } else {
4767 false
4768 };
4769 if !authorized {
4770 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())));
4771 task.base_sync_notice(&held);
4773 task.resume_override = None;
4774 record(queue, task);
4775 return Vec::new();
4776 }
4777 }
4778 let unfinished = (!task.fresh_start)
4779 .then(|| unfinished_run(&resume_runs, task.short()))
4780 .flatten()
4781 .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
4782 let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
4783 if task.repair_grants.last().is_some_and(|receipt| {
4784 task.execution_runs().last() == Some(&receipt.request.run)
4785 && task.operator_decided_at == receipt.decision
4786 && previous
4787 .as_ref()
4788 .is_none_or(|run| run.id != receipt.request.run)
4789 }) {
4790 task.hold_unrequested_retry(Some(
4791 "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(),
4792 ));
4793 record(queue, task);
4794 return Vec::new();
4795 }
4796 if let Some(id) = &task.disk_resume_run
4797 && unfinished.as_ref() != Some(id)
4798 {
4799 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()));
4800 record(queue, task);
4801 return Vec::new();
4802 }
4803
4804 if !task.fresh_start
4805 && task.pr_recovery.is_none()
4806 && task.review_branch.is_none()
4807 && task.resume_override.is_none()
4808 && previous
4809 .as_ref()
4810 .is_some_and(|run| run.retired_to.is_some())
4811 && unfinished.is_none()
4812 {
4813 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()));
4814 record(queue, task);
4815 return Vec::new();
4816 }
4817
4818 let saved_recovery = previous.as_ref().filter(|run| {
4819 task.replacement.is_none()
4820 && task.pr_recovery.as_ref().is_some_and(|selected| {
4821 selected
4822 .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
4823 .is_ok()
4824 && selected_starter(selected, Some(run), unfinished.as_deref())
4825 == Starter::Resume(run.id.clone())
4826 })
4827 });
4828
4829 let explicit = match &task.overrides {
4833 Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
4834 Some(_) => opts.config.as_deref(),
4835 None => opts.config.as_deref(),
4836 };
4837 let (mut config, layers) = if let Some(run) = saved_recovery {
4838 let mut saved = run.clone();
4841 if let Err(e) = saved.configure_recovery_resume() {
4842 task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
4843 record(queue, task);
4844 return Vec::new();
4845 }
4846 (saved.config, Vec::new())
4847 } else {
4848 let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
4849 Ok(loaded) => loaded,
4850 Err(e) => {
4851 let reason = format!("[config] {e:#}");
4852 record_config_failure(task, &e);
4853 task.last_error = Some(reason.clone());
4854 task.hold_machine(Some(reason));
4855 record(queue, task);
4856 return Vec::new();
4857 }
4858 };
4859 if let Err(e) = apply_options(&mut config, opts, task) {
4860 task.hold_manual(Some(format!(
4861 "[config] {e:#}; correct the merge override before releasing the task"
4862 )));
4863 record(queue, task);
4864 return Vec::new();
4865 }
4866 if let Some(selected) = &task.pr_recovery
4867 && let Err(e) = selected.configure(&mut config)
4868 {
4869 task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
4870 record(queue, task);
4871 return Vec::new();
4872 }
4873 (config, layers)
4874 };
4875 let config_evidence = crate::pr_recovery::ConfigEvidence {
4876 layers,
4877 overrides: task.overrides.clone(),
4878 daemon_merge: task
4879 .overrides
4880 .as_ref()
4881 .is_none_or(|o| o.inherit_daemon_options)
4882 .then(|| opts.merge.clone())
4883 .flatten(),
4884 };
4885 apply_task_implementers(&mut config, task);
4886 if let Some(replacement) = &task.replacement {
4887 let safe = RunState::load(&replacement.run).is_ok_and(|old| {
4888 old.liveness(false) == Liveness::Dead
4889 && old.merge_decision.as_ref().is_some_and(|d| {
4890 d.closed
4891 && d.question == replacement.question
4892 && d.replacement_run.as_ref().is_none_or(|run| {
4893 task.execution_runs().last() == Some(run)
4894 && RunState::load(run).is_ok_and(|current| {
4895 current.replaces.as_ref().is_some_and(|pin| {
4896 pin.question == replacement.question
4897 && pin.agent == replacement.agent
4898 })
4899 })
4900 })
4901 })
4902 });
4903 if !safe {
4904 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()));
4905 record(queue, task);
4906 return Vec::new();
4907 }
4908 match config.agent(&replacement.agent) {
4909 Ok(agent) if crate::agent::installed(agent) => {}
4910 _ => {
4911 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)));
4912 record(queue, task);
4913 return Vec::new();
4914 }
4915 }
4916 config.graph.implementers = 1;
4917 config.graph.land_approval = true;
4918 config.merge.mode = MergeMode::Pr;
4919 config.graph.selected_implementer = Some(replacement.agent.clone());
4920 }
4921 let p = phrases(&config.graph.language);
4922 let start_failed = p.could_not_start;
4923 if let Ok(base) =
4928 crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
4929 .await
4930 && let Ok(head) =
4931 crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
4932 {
4933 let mut inputs = crate::queue::recovery_inputs(&task.sources);
4934 if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
4935 let source = crate::git::rev_parse(&repo, branch)
4936 .await
4937 .unwrap_or_default();
4938 inputs.push_str(&format!(";review:{branch}:{source}"));
4939 }
4940 if let Some(reason) = task
4941 .recovery_exhausted(
4942 &head,
4943 &inputs,
4944 task.attempt_limit
4945 .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
4946 )
4947 .filter(|_| {
4948 !task.repair_grants.last().is_some_and(|receipt| {
4949 RunState::load(&receipt.request.run)
4950 .is_ok_and(|run| crate::repair_budget::pending(task, &run))
4951 })
4952 })
4953 {
4954 task.hold_recovery_budget(
4955 reason,
4956 crate::queue::RecoveryAdmission { base: head, inputs },
4957 );
4958 record(queue, task);
4959 return Vec::new();
4960 }
4961 task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
4962 }
4963
4964 let consume_review = !previous
4985 .as_ref()
4986 .is_some_and(|state| crate::repair_budget::pending(task, state));
4987 let review_branch = consume_review
4988 .then(|| review_branch_for(task, previous.as_ref()))
4989 .flatten();
4990 let branch_exists = match review_branch {
4991 Some(branch) => crate::git::branch_exists(&repo, branch)
4992 .await
4993 .unwrap_or(false),
4994 None => false,
4995 };
4996 let proposed = review_retry_starter(
5000 task,
5001 previous.as_ref(),
5002 review_branch,
5003 branch_exists,
5004 unfinished.as_deref(),
5005 );
5006 let retry_selected = task.replacement.is_some()
5007 && task.resumption.is_some()
5008 && !task.fresh_start
5009 && previous.as_ref().is_some_and(|run| {
5010 run.replaces.is_some()
5011 && ((run.status == RunStatus::Failed && run.viable().is_empty())
5012 || (run.status == RunStatus::Blocked && run.tally.is_none()))
5013 });
5014 let stop_pin = task
5015 .resume_override
5016 .as_ref()
5017 .filter(|pin| {
5018 Questions::open()
5019 .get_for_effects(&pin.question_id)
5020 .is_ok_and(|q| {
5021 q.node == land::APPROVAL_NODE
5022 && q.resolution()
5023 .as_deref()
5024 .is_some_and(crate::merge_decision::stops)
5025 })
5026 })
5027 .and_then(|pin| pin.pinned_run.clone());
5028 let granted_run = task.repair_grants.last().and_then(|receipt| {
5029 let state = RunState::load(&receipt.request.run).ok()?;
5030 crate::repair_budget::pending(task, &state).then(|| receipt.request.run.clone())
5031 });
5032 let starter = if let Some(run) = granted_run {
5033 Starter::Resume(run)
5034 } else if let Some(owner) = &public_owner {
5035 Starter::Resume(owner.id.clone())
5036 } else if let Some(run) = stop_pin {
5037 Starter::Resume(run)
5040 } else if retry_selected {
5041 Starter::Resume(previous.as_ref().unwrap().id.clone())
5042 } else if let Some(selected) = &task.pr_recovery {
5043 if selected
5044 .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
5045 .is_ok()
5046 {
5047 selected_starter(selected, previous.as_ref(), unfinished.as_deref())
5048 } else {
5049 Starter::Review(selected.branch.clone())
5050 }
5051 } else {
5052 starter_with_implementers(task, previous.as_ref(), proposed)
5053 };
5054 let disk_reason = match &starter {
5057 Starter::Resume(id) => previous.as_ref().filter(|run| &run.id == id).map_or_else(
5058 || {
5059 RunState::load(id)
5060 .ok()
5061 .and_then(|run| disk_gate(&run.repo, &run.config))
5062 },
5063 |run| disk_gate(&run.repo, &run.config),
5064 ),
5065 _ => disk_gate(&repo, &config),
5066 };
5067 if let Some(reason) = disk_reason {
5068 task.notice_cause("disk-space", None, None);
5069 task.last_error = Some(reason.clone());
5070 let disk_checked_at = task.disk_checked_at;
5071 task.hold_machine(Some(reason.clone()));
5072 if matches!(starter, Starter::Resume(_)) {
5073 task.mark_disk_capacity();
5074 } else {
5075 task.mark_startup_disk_capacity();
5076 }
5077 task.disk_checked_at = disk_checked_at;
5078 record(queue, task);
5079 tracing::warn!("holding {} for want of disk space: {reason}", task.short());
5080 notices::raise(
5081 Notice::warn(
5082 &format!("disk:{}", repo.display()),
5083 format!("Task {} is waiting for disk space. It will resume automatically when disk and output admission checks succeed.", task.id),
5084 )
5085 .link(Link::Task {
5086 id: task.id.clone(),
5087 }),
5088 );
5089 return Vec::new();
5090 }
5091 let review_branch = if consume_review {
5092 let valid = review_branch.is_some();
5093 task.review_instruction = None;
5094 task.review_branch.take().filter(|_| valid)
5095 } else {
5096 None
5097 };
5098 if let Some(pin) = &task.resume_override
5101 && let Some(run) = &pin.pinned_run
5102 && starter != Starter::Resume(run.clone())
5103 {
5104 let run = run.clone();
5105 task.notice_cause("resume-owner", Some(&run), None);
5106 task.hold_machine(Some(format!(
5107 "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
5108 task.id
5109 )));
5110 record(queue, task);
5111 return Vec::new();
5112 }
5113 if let Some(run) = &task.disk_resume_run
5117 && starter != Starter::Resume(run.clone())
5118 {
5119 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()));
5120 record(queue, task);
5121 return Vec::new();
5122 }
5123 if task.replacement.is_some()
5124 && previous.as_ref().is_some_and(|run| run.replaces.is_some())
5125 && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
5126 {
5127 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()));
5128 record(queue, task);
5129 return Vec::new();
5130 }
5131 if let Some(reason) = retained_attempt_hold(
5132 task,
5133 &starter,
5134 config.disk.retained_attempt_limit,
5135 RunState::load,
5136 ) {
5137 if let Starter::Review(branch) = &starter {
5140 task.review_branch = Some(branch.clone());
5141 }
5142 task.hold_unrequested_retry(Some(reason));
5143 record(queue, task);
5144 return Vec::new();
5145 }
5146 let attachments = match task_attachments(queue, task) {
5151 Ok(a) => a,
5152 Err(e) => {
5153 task.attempts += 1;
5154 task.fail_startup_target(
5155 "startup-attachments",
5156 e.name.clone(),
5157 format!("{start_failed}{e:#}"),
5158 opts.max_attempts,
5159 );
5160 record(queue, task);
5161 return Vec::new();
5162 }
5163 };
5164 let startup_pause = stop.pause();
5165 let startup_interrupt = interrupt_pause.clone();
5166 let wait = crate::repo_lock::WaitPolicy::new(
5167 Duration::from_secs(config.graph.timeout_resource_wait),
5168 move || startup_pause.parked() || startup_interrupt.parked(),
5169 );
5170 let started = wait.scope(Box::pin(async { match &starter {
5173 Starter::Review(_) if task.pr_recovery.is_some() => {
5174 let selected = task.pr_recovery.clone().expect("selected recovery");
5175 match selected.check_task_assignment(&task.id, &task.instruction, task.reassignments.len()) {
5176 Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
5177 .await
5178 .map(|mut r| {
5179 r.state.attachments = attachments.clone();
5180 r
5181 }),
5182 Err(e) => Err(e),
5183 }
5184 }
5185 Starter::Review(branch) => {
5186 tracing::info!(
5187 "task {} reopens `{branch}` as a review-only pass",
5188 task.short()
5189 );
5190 let takeover = crate::handover::Takeover {
5193 earlier: task.earlier_attempts().to_vec(),
5194 home: crate::run::home(),
5195 choice: take_divergence_answer(branch, &config.merge.remote, task),
5196 task_instruction: Some(instruction_for(task)),
5197 };
5198 Runner::review_taking_over(
5199 &repo,
5200 branch,
5201 config,
5202 Some(takeover),
5203 crate::run::Origin::queue(&task.id),
5204 )
5205 .await
5206 }
5207 Starter::Resume(id) => {
5208 tracing::info!("resuming run {id} rather than competing again");
5209 Runner::resume(id).and_then(|mut r| {
5210 if retry_selected {
5211 for candidate in &mut r.state.candidates {
5214 candidate.failed = None;
5215 candidate.empty = false;
5216 candidate.commits = 0;
5217 }
5218 r.state.status = RunStatus::Implementing;
5219 r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
5220 }
5221 if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
5222 r.state.sources = task.sources.clone();
5223 }
5224 if r.state.prep_failure.is_some() {
5225 let approval = task
5226 .resumption
5227 .as_ref()
5228 .context("preparation retry requires an explicit task release")?;
5229 r.retry_preparation(approval.at)?;
5230 }
5231 if let Some(instruction) =
5232 prepare_instruction(&starter, Some(&r.state.instruction), task)
5233 {
5234 r.state.instruction = instruction;
5235 }
5236 r.state.attachments = attachments.clone();
5237 if task.replacement.is_some() {
5238 r.state.config.merge.mode = MergeMode::Pr;
5239 r.state.config.graph.land_approval = true;
5240 }
5241 if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
5245 .overrides
5246 .as_ref()
5247 .and_then(|o| o.merge.as_deref())
5248 .and_then(|m| merge_mode(m).ok())
5249 {
5250 r.state.config.merge.mode = mode;
5251 }
5252 Ok(r)
5253 })
5254 }
5255 Starter::Start => {
5256 if let Some(branch) = &review_branch {
5257 tracing::warn!(
5258 "conductor chose review for task {} but branch `{branch}` no longer \
5259 exists; requeuing as a fresh competition instead",
5260 task.short()
5261 );
5262 }
5263 let instruction = prepare_instruction(&starter, None, task)
5264 .unwrap_or_else(|| task.instruction.clone());
5265 Runner::start_naming(
5266 &repo,
5267 instruction,
5268 &task.title,
5269 config,
5270 crate::run::Origin::queue(&task.id),
5271 )
5272 .await
5273 .map(|mut r| {
5274 r.state.attachments = attachments.clone();
5275 r.state.sources = task.sources.clone();
5276 r
5277 })
5278 }
5279 }})).await;
5280 if let Err(error) = &started
5281 && let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>()
5282 {
5283 task.record_startup_failure(failure.clone());
5284 }
5285 let mut runner = match started {
5286 Ok(r) => r,
5287 Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
5288 let detail = format!("{e:#}");
5289 task.last_error = Some(detail.clone());
5290 if e.is::<crate::build_target::AdmissionDiskWait>()
5291 && let Starter::Review(branch) = &starter
5292 && review_branch.is_some()
5293 {
5294 task.review_branch = Some(branch.clone());
5295 task.review_instruction = Some(task.instruction.clone());
5296 }
5297 if stop.parking() || interrupt_pause.parked() {
5298 let attempts = task.attempts;
5299 task.park(e.to_string());
5300 task.attempts = attempts;
5302 } else if e.is::<crate::build_target::AdmissionDiskWait>() {
5303 let disk_checked_at = task.disk_checked_at;
5304 task.hold_machine(Some(detail));
5305 task.mark_startup_disk_capacity();
5306 task.disk_checked_at = disk_checked_at;
5307 } else {
5308 task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
5309 }
5310 record(queue, task);
5311 return Vec::new();
5312 }
5313 Err(e) if task.pr_recovery.is_some() => {
5317 task.startup_notice_cause("startup-public-head");
5318 task.attempts += 1;
5319 task.last_error = Some(format!("{start_failed}{e:#}"));
5320 task.hold_unrequested_retry(Some(format!(
5321 "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."
5322 )));
5323 record(queue, task);
5324 return Vec::new();
5325 }
5326 Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
5327 let detail = match e.downcast_ref::<crate::handover::Refused>() {
5328 Some(r) => (p.handover_refused)(r),
5329 None => format!("{e:#}"),
5330 };
5331 task.startup_notice_cause("startup-handover");
5332 let reason = format!("{start_failed}{detail}");
5333 task.last_error = Some(reason.clone());
5334 let branch = match &starter {
5337 Starter::Review(branch) => Some(branch.clone()),
5338 _ => None,
5339 };
5340 task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
5344 record(queue, task);
5345 tracing::warn!(
5346 "holding {} for a branch it cannot take over: {e:#}",
5347 task.short()
5348 );
5349 return Vec::new();
5350 }
5351 Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
5356 let d = e
5357 .downcast_ref::<crate::reconcile::Diverged>()
5358 .expect("checked by the guard");
5359 let mut q = ask::Question::new(
5360 task.id.clone(),
5361 crate::reconcile::NODE.to_owned(),
5362 crate::reconcile::SEAT.to_owned(),
5363 d.summary(),
5364 d.detail(),
5365 d.choices(),
5366 );
5367 match Questions::open().put(&mut q) {
5368 Ok(()) => {
5369 task.last_error = Some(format!("{e:#}"));
5370 task.review_branch = Some(d.branch.clone());
5373 task.review_instruction = Some(task.instruction.clone());
5374 task.block(vec![q.id.clone()], Some(d.summary()));
5375 }
5376 Err(put) => {
5377 tracing::warn!("could not file the divergence question: {put:#}");
5378 task.attempts += 1;
5379 task.fail_startup(
5380 "startup-question-store",
5381 format!("{start_failed}{e:#}"),
5382 opts.max_attempts,
5383 );
5384 }
5385 }
5386 record(queue, task);
5387 return Vec::new();
5388 }
5389 Err(e) => {
5390 if e.downcast_ref::<crate::reconcile::Stale>().is_some()
5396 && let Starter::Review(branch) = &starter
5397 {
5398 task.review_branch = Some(branch.clone());
5399 task.review_instruction = Some(task.instruction.clone());
5400 task.last_error = Some(format!("{start_failed}{e:#}"));
5401 task.status = crate::queue::TaskStatus::Failed;
5402 record(queue, task);
5403 return Vec::new();
5404 }
5405 task.attempts += 1;
5406 task.last_error = Some(format!("{start_failed}{e:#}"));
5407 task.startup_notice_cause("startup-source");
5408 task.hold_unrequested_retry(Some(format!(
5409 "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
5410 )));
5411 record(queue, task);
5412 return Vec::new();
5413 }
5414 };
5415 if !matches!(starter, Starter::Resume(_))
5416 && let Some((mode, source)) = task.build_cache_override(&runner.state.config)
5417 {
5418 runner
5419 .state
5420 .event("build-cache", format!("{mode} selected by {source}"));
5421 }
5422 if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
5423 runner.state.recovery_config = Some(config_evidence);
5424 }
5425 if let Some(replacement) = &task.replacement {
5426 if matches!(starter, Starter::Start) {
5427 runner.state.instruction.push_str(&format!(
5428 "\n\n# Replacement review context\n{}",
5429 replacement.context
5430 ));
5431 }
5432 runner.state.replaces = Some(replacement.clone());
5433 runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
5434 if let Ok(mut old) = RunState::load(&replacement.run)
5435 && let Some(d) = &mut old.merge_decision
5436 {
5437 d.replacement_run = Some(runner.state.id.clone());
5438 old.event(
5439 "replacement",
5440 format!(
5441 "replacement run {} owns the next attempt; old PR remains closed",
5442 runner.state.id
5443 ),
5444 );
5445 if let Err(e) = old.save() {
5446 let error = runner.fail_startup("replacement-history", e);
5447 if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5448 task.record_startup_failure(failure.clone());
5449 }
5450 task.hold_manual(Some(format!(
5451 "Could not link replacement history: {error:#}; no agents dispatched"
5452 )));
5453 record(queue, task);
5454 return Vec::new();
5455 }
5456 }
5457 }
5458 runner.state.task_instruction = Some(task.instruction.clone());
5459 runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
5462 if runner.state.origin_chat.is_none() {
5463 runner.state.origin_chat = task.chat_talk().map(str::to_owned);
5464 }
5465 runner.on_pause(stop.pause());
5467 runner.watch_interrupt(interrupt_pause);
5471
5472 let run = runner.state.id.clone();
5475 let before_start = task.clone();
5476 task.start(run.clone());
5477 if let Err(error) = queue.put(task) {
5478 *task = before_start;
5479 let error = runner.fail_startup("task-start", error);
5480 if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5481 task.record_startup_failure(failure.clone());
5482 }
5483 task.hold_manual(Some(format!(
5484 "Could not persist task start; no agents dispatched: {error:#}"
5485 )));
5486 record(queue, task);
5487 return Vec::new();
5488 }
5489 if task.status != TaskStatus::Running {
5490 return Vec::new();
5492 }
5493 lock(status).current.push(Current {
5494 worker: None,
5495 task: task.id.clone(),
5496 run,
5497 });
5498
5499 let quota_before = runner.state.quota.clone();
5502 runner.state.carry_dispatched_resumes(task);
5503 runner.state.next_pass_task_entry = true;
5504 let result = runner.execute().await;
5505 finish_attempt(
5506 opts.max_attempts,
5507 queue,
5508 task,
5509 &runner.state,
5510 "a_before,
5511 result,
5512 )
5513}
5514
5515async fn attempt_sync_only(
5516 queue: &Queue,
5517 status: &Arc<Mutex<Status>>,
5518 stop: &Stop,
5519 interrupt: crate::graph::Pause,
5520 task: &mut Task,
5521 request: crate::base_sync_only::Request,
5522) {
5523 let result = async {
5524 anyhow::ensure!(
5525 task.status == TaskStatus::Queued
5526 && task.execution_runs().last() == Some(&request.run)
5527 && task.resume_override.as_ref().is_some_and(
5528 |pin| pin.at == request.at && pin.pinned_run.as_ref() == Some(&request.run)
5529 ),
5530 "sync-base-only request no longer owns the exact queued run"
5531 );
5532 let mut runner = Runner::resume(&request.run)?;
5533 anyhow::ensure!(
5534 public_resume_owner(&crate::run::home(), &task.runs, &runner.state.repo)
5535 .await?
5536 .is_none(),
5537 "the task still has a public execution owner"
5538 );
5539 anyhow::ensure!(
5540 !stop.parking() && !interrupt.parked(),
5541 "paused before base synchronization"
5542 );
5543 let original = task.clone();
5544 task.start(request.run.clone());
5545 task.attempts = original.attempts;
5546 if let Err(error) = queue.put(task) {
5547 *task = original;
5548 return Err(error);
5549 }
5550 if task.status != TaskStatus::Running || task.sync_only.as_ref() != Some(&request) {
5551 return Ok(());
5552 }
5553 lock(status).current.push(Current {
5554 worker: None,
5555 task: task.id.clone(),
5556 run: request.run.clone(),
5557 });
5558 runner.on_pause(stop.pause());
5559 runner.watch_interrupt(interrupt);
5560 runner.execute_sync_only(request.clone()).await
5561 }
5562 .await;
5563 if task.sync_only.as_ref() == Some(&request) {
5564 let saved = RunState::load(&request.run).ok();
5565 let detail = result.err().map(|error| {
5566 format!("Base synchronization only: {error:#}; verification was not allowed")
5567 });
5568 crate::base_sync_only::settle(task, &request, saved.as_ref(), detail);
5569 record(queue, task);
5570 }
5571}
5572
5573pub fn finish_attempt(
5578 max_attempts: usize,
5579 queue: &Queue,
5580 task: &mut Task,
5581 state: &RunState,
5582 quota_before: &[QuotaLoss],
5583 result: Result<()>,
5584) -> Vec<QuotaLoss> {
5585 let detail = match result {
5586 Ok(()) => describe(state),
5587 Err(e) => format!("{e:#}"),
5588 };
5589 let fresh = losses_this_attempt(quota_before, &state.quota);
5590 let verdict = Verdict {
5591 status: state.status,
5592 left_pr: state.pr.is_some(),
5595 quota_hit: !fresh.is_empty(),
5601 parked: state.parked,
5605 no_viable_candidates: state.viable().is_empty(),
5608 };
5609 if let Some(replacement) = &state.replaces
5610 && let Some(pr) = &state.pr
5611 && let Ok(mut old) = RunState::load(&replacement.run)
5612 && let Some(d) = &mut old.merge_decision
5613 {
5614 d.replacement_pr = Some(pr.url.clone());
5615 let _ = old.save();
5616 }
5617 settle_and_diagnose(task, verdict, &detail, max_attempts, state);
5618 if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
5619 task.hold_unrequested_retry(Some(format!(
5620 "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.",
5621 task.short()
5622 )));
5623 }
5624 if task.status == TaskStatus::Done {
5625 supersede_prior_runs(task, &crate::run::home());
5626 }
5627 record(queue, task);
5628 tracing::info!(
5629 "task {} is {} after run {} ({})",
5630 task.short(),
5631 task.status.as_str(),
5632 state.short(),
5633 label(state.status)
5634 );
5635 fresh
5636}
5637
5638pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
5642 if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
5645 && !awaiting_resume_with(task, RunState::load)
5646 && withheld_text_wait(task).is_none()
5650 && !(task.fresh_start && task.replacement.is_some())
5651 {
5652 let why = task.last_error.clone().map_or_else(
5653 || "the run did not finish".to_owned(),
5654 |e| format!("the run did not finish: {e}"),
5655 );
5656 task.hold_unrequested_retry(Some(format!(
5657 "{why}. It was started by hand, so it is not retried \
5658 automatically; `magi task release` retries it."
5659 )));
5660 record(queue, task);
5661 }
5662}
5663
5664#[must_use]
5668pub fn loop_would_resume(run: &str) -> bool {
5669 unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
5670}
5671
5672#[must_use]
5682pub fn foreign_loop(
5683 reading: Option<&Reading>,
5684 now: Timestamp,
5685 own_pid: u32,
5686) -> Option<Option<u32>> {
5687 let reading = reading.filter(|r| r.running(now))?;
5688 match reading.pid {
5689 Some(pid) if pid == own_pid => None,
5690 pid => Some(pid),
5691 }
5692}
5693
5694fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
5695 reading.worker_protocol != Some(1)
5696 && (foreign_loop(Some(reading), now, own_pid).is_some()
5697 || reading
5698 .pid
5699 .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
5700}
5701
5702pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
5713 run_claimed_until(opts, queue, task, &Stop::new()).await;
5714}
5715
5716async fn run_claimed_until(
5717 opts: &Opts,
5718 queue: &Queue,
5719 task: &mut Task,
5720 stop: &Stop,
5721) -> Vec<QuotaLoss> {
5722 let status = Arc::new(Mutex::new(Status::new()));
5723 let mut quota = Box::pin(attempt(
5726 opts,
5727 queue,
5728 &status,
5729 stop,
5730 crate::graph::Pause::new(),
5731 task,
5732 ))
5733 .await;
5734 let mut resumes = 0;
5743 while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
5744 let Some(timeout) = withheld_text_wait(task) else {
5745 break;
5746 };
5747 eprintln!(
5748 "waiting for the owner's answer on a withheld pull request text \
5749 (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
5750 );
5751 let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
5754 let ready = loop {
5755 match land_resume_state(task) {
5756 LandResume::StillWaiting
5757 if !stop.parking() && std::time::Instant::now() < limit =>
5758 {
5759 tokio::time::sleep(WITHHELD_POLL).await;
5760 }
5761 LandResume::Ready => break true,
5762 _ => break false,
5763 }
5764 };
5765 if !ready || stop.parking() {
5766 break;
5767 }
5768 resumes += 1;
5769 quota.extend(
5770 Box::pin(attempt(
5771 opts,
5772 queue,
5773 &status,
5774 stop,
5775 crate::graph::Pause::new(),
5776 task,
5777 ))
5778 .await,
5779 );
5780 }
5781 hold_if_runnable(queue, task);
5782 quota
5783}
5784
5785const MAX_WITHHELD_RESUMES: u32 = 3;
5788
5789const WITHHELD_POLL: Duration = Duration::from_secs(15);
5791
5792fn withheld_text_wait(task: &Task) -> Option<u64> {
5795 let id = task.execution_runs().last()?;
5796 let s = RunState::load(id).ok()?;
5797 (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
5798 .then_some(s.config.graph.answer_timeout)
5799}
5800
5801fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
5811 after
5812 .iter()
5813 .filter(|q| !before.contains(q))
5814 .cloned()
5815 .collect()
5816}
5817
5818fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
5821 let quota: Vec<_> = quota
5822 .iter()
5823 .filter(|q| q.cause == crate::agent::QuotaCause::UsageLimit)
5824 .collect();
5825 if quota.is_empty() {
5826 return None;
5827 }
5828 let with_hint = quota.iter().find(|q| q.reset.is_some());
5829 let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
5830 let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
5831 let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
5832 Some(
5833 now.checked_add(jiff::SignedDuration::from_secs(secs))
5834 .unwrap_or(Timestamp::MAX),
5835 )
5836}
5837
5838fn implementers_match(task: &Task, state: &RunState) -> bool {
5840 task.replacement.as_ref().map_or_else(
5841 || {
5842 task.implementers()
5843 .is_none_or(|n| n == state.config.graph.implementers)
5844 },
5845 |replacement| {
5846 state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
5847 && state.config.graph.implementers == 1
5848 },
5849 )
5850}
5851
5852fn starter_with_implementers(
5854 task: &Task,
5855 previous: Option<&RunState>,
5856 proposed: Starter,
5857) -> Starter {
5858 if previous.is_some_and(|s| !implementers_match(task, s)) {
5859 task.review_of
5860 .as_ref()
5861 .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
5862 } else {
5863 proposed
5864 }
5865}
5866
5867fn apply_task_implementers(config: &mut Config, task: &Task) {
5869 if let Some(n) = task.implementers() {
5870 config.graph.implementers = n;
5871 }
5872}
5873
5874#[cfg(test)]
5879fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
5880 let explicit = match &task.overrides {
5881 Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
5882 _ => opts.config.as_deref(),
5883 };
5884 let (mut config, _) = Config::discover(repo, explicit)?;
5885 apply_options(&mut config, opts, task)?;
5886 Ok(config)
5887}
5888
5889fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
5890 if task
5891 .overrides
5892 .as_ref()
5893 .is_none_or(|o| o.inherit_daemon_options)
5894 && let Some(mode) = opts.merge.as_deref()
5895 {
5896 config.merge.mode = merge_mode(mode)?;
5897 }
5898 if let Some(o) = &task.overrides {
5899 o.apply(config);
5900 }
5901 if let Some((mode, _)) = task.build_cache_override(config) {
5902 config.verify.build_cache = mode;
5903 }
5904 Ok(())
5905}
5906
5907fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
5909 let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
5910 if let Some(mode) = &opts.merge {
5911 config.merge.mode = merge_mode(mode)?;
5912 }
5913 Ok(config)
5914}
5915
5916async fn maybe_prune_cache_between_runs(
5921 repo: &Path,
5922 opts: &Opts,
5923 home: &Path,
5924 stop: &Stop,
5925 last_checked: &mut Option<Timestamp>,
5926 now: Timestamp,
5927) {
5928 if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
5929 return;
5930 }
5931 *last_checked = Some(now);
5932 let cfg = match prepare(repo, opts) {
5933 Ok(cfg) => cfg,
5934 Err(e) => {
5935 tracing::warn!("cache check: no config: {e:#}");
5936 return;
5937 }
5938 };
5939 match clean::prune_cache_if_over_limit(&cfg, home) {
5940 Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
5941 "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
5942 pruned.files,
5943 pruned.freed
5944 ),
5945 Ok(_) => {}
5946 Err(e) => {
5947 tracing::warn!("housekeep: prune cache: {e:#}");
5948 notices::raise_in(
5949 home,
5950 Notice::warn(
5951 "housekeep:cache",
5952 format!(
5953 "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
5954 e.to_string()
5955 .lines()
5956 .next()
5957 .unwrap_or("unknown cleanup error")
5958 ),
5959 ),
5960 );
5961 }
5962 }
5963}
5964
5965fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
5969 last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
5970}
5971
5972async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
5991 let cfg = match prepare(repo, opts) {
5992 Ok(cfg) => cfg,
5993 Err(e) => {
5994 tracing::warn!("housekeep: no config: {e:#}");
5995 return;
5996 }
5997 };
5998 let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
6007 let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
6008 if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
6013 let mut extra = Vec::new();
6014 if out.unreadable > 0 {
6015 extra.push(format!("{} unreadable", out.unreadable));
6016 }
6017 if out.orphaned_worktrees > 0 {
6018 extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
6019 }
6020 let detail = if extra.is_empty() {
6021 String::new()
6022 } else {
6023 format!(" ({})", extra.join(", "))
6024 };
6025 tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
6026 }
6027 if out.external_merges_recorded > 0 {
6028 tracing::info!(
6029 "housekeep: recorded {} run(s) as merged externally",
6030 out.external_merges_recorded
6031 );
6032 }
6033 if out.stale_pr_states_repaired > 0 {
6034 tracing::info!(
6035 "housekeep: rewrote {} run record(s) whose pull request had already settled",
6036 out.stale_pr_states_repaired
6037 );
6038 }
6039 if out.cache_files > 0 {
6040 tracing::info!(
6041 "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
6042 out.cache_files,
6043 out.cache_freed
6044 );
6045 }
6046 if out.questions_abandoned > 0 {
6047 tracing::info!(
6048 "housekeep: abandoned {} question(s) left open by a finished run",
6049 out.questions_abandoned
6050 );
6051 }
6052}
6053
6054async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
6063 let questions = Questions::at(home.join("questions"));
6064 let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
6065 if report.is_empty() {
6066 return;
6067 }
6068 if !report.quarantined.is_empty() {
6069 tracing::info!(
6070 "triage: held {} blocked task(s) whose blocked-on task or \
6071 question no longer exists: {}",
6072 report.quarantined.len(),
6073 report.quarantined.join(", ")
6074 );
6075 }
6076 if !report.resumed.is_empty() {
6077 tracing::info!(
6078 "triage: resumed {} held task(s) whose machine hold had resolved: {}",
6079 report.resumed.len(),
6080 report.resumed.join(", ")
6081 );
6082 }
6083 if !report.asked.is_empty() {
6084 tracing::info!(
6085 "triage: asked about {} held task(s): {}",
6086 report.asked.len(),
6087 report.asked.join(", ")
6088 );
6089 }
6090 if !report.answered.is_empty() {
6091 tracing::info!(
6092 "triage: applied {} operator answer(s): {}",
6093 report.answered.len(),
6094 report.answered.join(", ")
6095 );
6096 }
6097}
6098
6099pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
6106 disk_gate_at(repo, config, crate::run::home)
6107}
6108
6109pub(crate) fn disk_gate_at(
6110 repo: &Path,
6111 config: &Config,
6112 home: impl FnOnce() -> PathBuf,
6113) -> Option<String> {
6114 let measure = if crate::build_target::isolated(config) {
6115 crate::disk::managed_free_bytes
6116 } else {
6117 crate::disk::free_bytes
6118 };
6119 disk_gate_with(repo, config, home, measure)
6120}
6121
6122fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
6126 repo: &Path,
6127 config: &Config,
6128 home: impl FnOnce() -> PathBuf,
6129 free_bytes: F,
6130) -> Option<String> {
6131 let min = config.disk.min_free_bytes;
6132 if min == 0 {
6133 return None;
6134 }
6135 let output = match config.verify.build_cache {
6136 BuildCache::Shared => config.cache_dir(),
6137 BuildCache::Isolated => Some(home()),
6138 };
6139 let default_worktree_root;
6140 let worktree_root = match config.graph.worktree_root.as_deref() {
6141 Some(root) => root,
6142 None => {
6143 default_worktree_root = crate::run::default_worktree_root();
6144 &default_worktree_root
6145 }
6146 };
6147 for path in [Some(repo), output.as_deref(), Some(worktree_root)]
6148 .into_iter()
6149 .flatten()
6150 {
6151 let probe = if path == repo {
6152 path
6153 } else {
6154 path.ancestors().find(|p| p.exists()).unwrap_or(path)
6155 };
6156 let reason = match free_bytes(probe) {
6157 Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
6158 Err(e) => Some(crate::disk::unmeasured_in(
6159 probe,
6160 &e,
6161 &config.graph.language,
6162 )),
6163 };
6164 if reason.is_some() {
6165 return reason;
6166 }
6167 }
6168 None
6169}
6170
6171const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
6178
6179const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
6183
6184fn quota_wait(
6193 reset_at: Option<Timestamp>,
6194 now: Timestamp,
6195 fallback: Duration,
6196 cap: Duration,
6197) -> Duration {
6198 match reset_at {
6199 Some(at) if at > now => {
6200 let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
6201 Duration::from_secs(secs).min(cap)
6202 }
6203 _ => fallback,
6204 }
6205}
6206
6207fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
6221 parse_reset_hint_zoned(text, now)
6222 .or_else(|| parse_reset_hint_dated(text))
6223 .or_else(|| parse_reset_hint_relative(text, recorded))
6224}
6225
6226fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
6230 let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
6231 let mut rest = rest.trim();
6232 if rest.is_empty() {
6233 return None;
6234 }
6235 let mut total: i64 = 0;
6236 let mut matched = false;
6237 for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
6238 if let Some((digits, tail)) = rest.split_once(unit)
6239 && !digits.is_empty()
6240 && digits.bytes().all(|b| b.is_ascii_digit())
6241 {
6242 total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
6243 rest = tail;
6244 matched = true;
6245 }
6246 }
6247 if !rest.is_empty() || !matched {
6248 return None;
6249 }
6250 recorded
6251 .checked_add(jiff::SignedDuration::from_secs(total))
6252 .ok()
6253}
6254
6255fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
6259 let clock = clock.trim().to_lowercase();
6260 let (digits, pm) = clock
6261 .strip_suffix("am")
6262 .map(|d| (d, false))
6263 .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
6264 let (h, m) = digits.trim().split_once(':')?;
6265 let mut hour: i8 = h.trim().parse().ok()?;
6266 let minute: i8 = m.trim().parse().ok()?;
6267 if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
6268 return None;
6269 }
6270 if pm && hour != 12 {
6271 hour += 12;
6272 } else if !pm && hour == 12 {
6273 hour = 0;
6274 }
6275 Some((hour, minute))
6276}
6277
6278fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
6283 let open = text.find('(')?;
6284 let close = text.rfind(')')?;
6285 if close <= open {
6286 return None;
6287 }
6288 let zone = text[open + 1..close].trim();
6289 let (hour, minute) = parse_12h_clock(&text[..open])?;
6290 let tz = jiff::tz::TimeZone::get(zone).ok()?;
6291 let candidate = now
6292 .to_zoned(tz)
6293 .with()
6294 .hour(hour)
6295 .minute(minute)
6296 .second(0)
6297 .millisecond(0)
6298 .microsecond(0)
6299 .nanosecond(0)
6300 .build()
6301 .ok()?;
6302 let mut at = candidate.timestamp();
6303 if at <= now {
6304 at += jiff::SignedDuration::from_hours(24);
6305 }
6306 Some(at)
6307}
6308
6309fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
6318 let words: Vec<&str> = text.split_whitespace().collect();
6319 if words.len() < 5 {
6320 return None;
6321 }
6322 (0..=words.len() - 5)
6323 .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
6324}
6325
6326fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
6332 if trailing.is_some_and(|next| next.starts_with('(')) {
6333 return None;
6334 }
6335 let month = month_number(window[0])?;
6336 let day_token = window[1].strip_suffix(',')?.to_lowercase();
6337 let day_digits = ["st", "nd", "rd", "th"]
6338 .iter()
6339 .find_map(|suffix| day_token.strip_suffix(*suffix))?;
6340 let day: i8 = day_digits.parse().ok()?;
6341 let year_token = window[2];
6342 if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
6343 return None;
6344 }
6345 let year: i16 = year_token.parse().ok()?;
6346 let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
6350 let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
6351 let date = jiff::civil::Date::new(year, month, day).ok()?;
6352 let candidate = date
6353 .at(hour, minute, 0, 0)
6354 .to_zoned(jiff::tz::TimeZone::UTC)
6355 .ok()?;
6356 Some(candidate.timestamp())
6357}
6358
6359fn month_number(name: &str) -> Option<i8> {
6362 const NAMES: [&str; 12] = [
6363 "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
6364 ];
6365 let lower = name.to_lowercase();
6366 NAMES
6367 .iter()
6368 .position(|n| *n == lower.as_str())
6369 .map(|i| i as i8 + 1)
6370}
6371
6372#[cfg(test)]
6374fn exhausted_review_budget(state: &RunState) -> bool {
6375 !crate::handover::can_resume(state)
6378 && state.status == RunStatus::Blocked
6379 && !state.released()
6380 && state.retired_to.is_none()
6381}
6382
6383fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
6420 unfinished_run_with(runs, short, RunState::load)
6421}
6422
6423pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
6426where
6427 F: FnMut(&str) -> Result<RunState>,
6428{
6429 let mut id = runs.last()?.clone();
6430 let mut visited = std::collections::BTreeSet::new();
6431 let mut repo = None;
6432 loop {
6433 if !runs.contains(&id) || !visited.insert(id.clone()) {
6434 tracing::warn!("invalid or cyclic recovery authority for task {short}");
6435 return None;
6436 }
6437 let state = match load(&id) {
6438 Ok(state) if state.id == id => state,
6439 Ok(_) => return None,
6440 Err(e) => {
6441 tracing::warn!("could not read run {id} for task {short}: {e:#}");
6442 return None;
6443 }
6444 };
6445 if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
6446 return None;
6447 }
6448 repo = Some(state.repo.clone());
6449 if let Some(authority) = state.retired_to {
6450 id = authority;
6451 continue;
6452 }
6453 return (crate::handover::can_resume(&state)
6454 && state.liveness(false) != crate::run::Liveness::Live)
6455 .then_some(id);
6456 }
6457}
6458
6459fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
6467where
6468 F: FnOnce(&str) -> Result<RunState>,
6469{
6470 if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
6472 || task.fresh_start
6473 || task.review_branch.is_some()
6474 {
6475 return false;
6476 }
6477 let Some(id) = task.execution_runs().last() else {
6478 return false;
6479 };
6480 load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
6481}
6482
6483#[derive(Debug, Clone, PartialEq, Eq)]
6486enum Starter {
6487 Review(String),
6490 Resume(String),
6492 Start,
6494}
6495
6496fn retained_attempt_hold(
6501 task: &Task,
6502 starter: &Starter,
6503 limit: usize,
6504 mut load: impl FnMut(&str) -> Result<RunState>,
6505) -> Option<String> {
6506 if limit == 0 || matches!(starter, Starter::Resume(_)) {
6507 return None;
6508 }
6509 let mut retained = 0;
6510 for id in task
6511 .runs
6512 .iter()
6513 .chain(task.startup_failures.iter().map(|failure| &failure.run))
6514 .collect::<std::collections::BTreeSet<_>>()
6515 {
6516 let state = match load(id) {
6517 Ok(state) if state.id == *id => state,
6518 _ => {
6519 return Some(format!(
6520 "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
6521 ));
6522 }
6523 };
6524 if state.retired_to.is_some() || state.released() {
6525 continue;
6526 }
6527 retained += 1;
6530 }
6531 (retained >= limit).then(|| format!(
6532 "[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."
6533 ))
6534}
6535
6536fn selected_starter(
6538 selected: &crate::pr_recovery::Selection,
6539 previous: Option<&RunState>,
6540 unfinished: Option<&str>,
6541) -> Starter {
6542 if let Some(id) = unfinished
6543 && previous.is_some_and(|r| {
6544 r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
6545 })
6546 {
6547 Starter::Resume(id.to_owned())
6548 } else {
6549 Starter::Review(selected.branch.clone())
6550 }
6551}
6552
6553fn take_divergence_answer(
6557 branch: &str,
6558 remote: &str,
6559 task: &mut Task,
6560) -> Option<crate::reconcile::Choice> {
6561 let summary = crate::reconcile::summary_for(branch, remote);
6562 let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
6563 (a.question == summary)
6564 .then(|| crate::reconcile::Choice::from_answer(&a.answer))
6565 .flatten()
6566 .map(|c| (i, c))
6567 })?;
6568 task.answers.remove(idx);
6569 Some(choice)
6570}
6571
6572fn choose_starter(
6584 review_branch: Option<&str>,
6585 branch_exists: bool,
6586 unfinished: Option<&str>,
6587) -> Starter {
6588 match review_branch {
6589 Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
6590 Some(_) => Starter::Start,
6591 None => match unfinished {
6592 Some(id) => Starter::Resume(id.to_owned()),
6593 None => Starter::Start,
6594 },
6595 }
6596}
6597
6598fn review_retry_starter(
6602 task: &Task,
6603 previous: Option<&RunState>,
6604 branch: Option<&str>,
6605 exists: bool,
6606 unfinished: Option<&str>,
6607) -> Starter {
6608 if let Some(run) = previous
6609 && unfinished == Some(run.id.as_str())
6610 && run.reviewed_commits.is_some()
6611 && branch.is_some_and(|branch| {
6612 exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
6613 })
6614 && may_resume_run(run, task)
6615 {
6616 return Starter::Resume(run.id.clone());
6617 }
6618 match (branch, unfinished, &task.review_of) {
6619 (None, None, Some(branch)) => Starter::Review(branch.clone()),
6620 _ => choose_starter(branch, exists, unfinished),
6621 }
6622}
6623
6624fn review_branch_for<'a>(task: &'a Task, previous: Option<&RunState>) -> Option<&'a str> {
6626 task.review_branch
6627 .as_deref()
6628 .filter(|&branch| match &task.review_instruction {
6629 Some(authored) => *authored == task.instruction,
6630 None => previous.map_or_else(
6633 || task.review_of.as_deref() == Some(branch),
6634 |run| compatible_run_instruction(run, task),
6635 ),
6636 })
6637}
6638
6639fn may_resume_run(run: &RunState, task: &Task) -> bool {
6642 if !task.assignment_accepts(run) {
6643 return false;
6644 }
6645 task.resume_override
6646 .as_ref()
6647 .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
6648 || compatible_run_instruction(run, task)
6649}
6650
6651pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
6653 if let Some(authored) = &run.task_instruction {
6654 return compatible_instruction(authored, task);
6655 }
6656 if compatible_instruction(&run.instruction, task) {
6657 return true;
6658 }
6659 if run.reviewed_commits.is_some() {
6662 if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
6663 return strip_answers_block(authored, task).trim() == task.instruction.trim();
6664 }
6665 if let Some(branch) = &task.review_of {
6666 let canonical = format!(
6667 "Review the branch `{branch}` (review-only: no implementation, no judging)."
6668 );
6669 let generated = format!(
6670 "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"
6671 );
6672 return task.instruction == canonical && run.instruction.starts_with(&generated);
6673 }
6674 }
6675 false
6676}
6677
6678pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
6680 strip_answers_block(old, task) == task.instruction
6681}
6682
6683fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
6686 if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
6687 return fallback.to_path_buf();
6688 }
6689 task.repo.clone()
6690}
6691
6692const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
6696
6697fn answers_block(task: &Task, count: usize) -> String {
6699 let mut s = ANSWERS_HEADER.to_owned();
6700 for a in &task.answers[..count] {
6701 s.push_str(&format!("- {}: {}\n", a.question, a.answer));
6702 }
6703 s
6704}
6705
6706fn resumption_block(r: &crate::queue::Resumption) -> String {
6709 format!(
6710 "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
6711 Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
6712 r.generation, r.at, r.instruction, r.answers_through,
6713 )
6714}
6715
6716fn append_answers(base: &str, task: &Task) -> String {
6718 let mut s = base.to_owned();
6719 if !task.answers.is_empty() {
6720 s.push_str(&answers_block(task, task.answers.len()));
6721 }
6722 if let Some(r) = &task.resumption {
6723 s.push_str(&resumption_block(r));
6724 }
6725 s
6726}
6727
6728fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
6732 let mut instruction = instruction;
6733 for approval in task
6734 .resumption
6735 .iter()
6736 .chain(task.resumption_history.iter().rev())
6737 {
6738 if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
6739 instruction = base;
6740 break;
6741 }
6742 }
6743 for count in (1..=task.answers.len()).rev() {
6744 let block = answers_block(task, count);
6745 if let Some(base) = instruction.strip_suffix(&block) {
6746 return base;
6747 }
6748 }
6749 instruction
6750}
6751
6752fn instruction_for(task: &Task) -> String {
6760 append_answers(&task.instruction, task)
6761}
6762
6763fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
6775 append_answers(strip_answers_block(old_instruction, task), task)
6776}
6777
6778fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
6780 let failure = error.downcast_ref::<crate::config::ConfigFailure>();
6781 task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
6782 if let Some(cause) = task.hold_notice_cause.as_mut() {
6783 cause.target = failure.map(|f| f.target.clone());
6784 }
6785}
6786
6787#[derive(Debug, thiserror::Error)]
6788#[error("attachment `{name}` is recorded on the task but {path} is missing")]
6789struct MissingAttachment {
6790 name: String,
6791 path: PathBuf,
6792}
6793
6794fn task_attachments(
6796 queue: &Queue,
6797 task: &Task,
6798) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
6799 let paths = queue.attachment_paths(task);
6800 for (name, path) in task.attachments.iter().zip(&paths) {
6801 if !path.is_file() {
6802 return Err(MissingAttachment {
6803 name: name.clone(),
6804 path: path.clone(),
6805 });
6806 }
6807 }
6808 Ok(paths)
6809}
6810
6811fn prepare_instruction(
6822 starter: &Starter,
6823 old_instruction: Option<&str>,
6824 task: &Task,
6825) -> Option<String> {
6826 match starter {
6827 Starter::Start => Some(instruction_for(task)),
6828 Starter::Resume(_) => Some(resumed_instruction(
6829 old_instruction.expect("a resumed run always has a prior instruction"),
6830 task,
6831 )),
6832 Starter::Review(_) => None,
6833 }
6834}
6835
6836fn record(queue: &Queue, task: &mut Task) {
6840 if let Err(e) = queue.put(task) {
6841 tracing::error!("could not record task {}: {e:#}", task.short());
6842 let notice = Notice::error(
6843 "loop:record",
6844 format!(
6845 "Task {} state could not be saved: {}. Check the disk.",
6846 task.id,
6847 e.to_string().lines().next().unwrap_or("unknown save error")
6848 ),
6849 )
6850 .link(Link::Task {
6851 id: task.id.clone(),
6852 });
6853 match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
6855 Some(home) => notices::raise_in(home, notice),
6856 None => notices::raise(notice),
6857 }
6858 }
6859}
6860
6861fn runnable(queue: &Queue) -> Vec<Task> {
6867 let mut tasks: Vec<Task> = queue
6868 .list()
6869 .into_iter()
6870 .filter(|t| t.status.runnable())
6871 .collect();
6872 tasks.sort_unstable_by(crate::queue::dispatch_order);
6873 tasks
6874}
6875
6876fn describe(state: &RunState) -> String {
6890 let p = phrases(&state.config.graph.language);
6891 let mut detail = if state.status == RunStatus::Stalled {
6892 let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
6893 seats.sort_unstable();
6894 seats.dedup();
6895 if seats.is_empty() {
6896 p.quorum_lost.to_owned()
6897 } else {
6898 format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
6899 }
6900 } else {
6901 format!("{}{}", p.run_ended, state.status.display_label())
6902 };
6903 if let Some(cause) = state.verification_blocking_cause() {
6904 detail.push_str(&format!(" ({cause})"));
6905 } else if let Some(last) = state.events.last() {
6906 let unanswered = state
6910 .reviews
6911 .last()
6912 .filter(|r| {
6913 state.status == RunStatus::Blocked
6914 && last.node == "review"
6915 && r.incomplete()
6916 && r.blocking == 0
6917 && r.round == state.config.graph.review_rounds
6918 && r.e2e.iter().all(crate::run::CommandOutcome::ok)
6919 })
6920 .map(|r| (r.expected - r.answered, r.round));
6921 match unanswered {
6922 Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
6923 detail.push_str(&format!(
6924 " ({}: {})",
6925 last.node,
6926 (p.reviewers_never_answered)(missing, rounds)
6927 ));
6928 }
6929 _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
6930 }
6931 }
6932 detail.push_str(&format!(" [run {}]", state.id));
6933 detail
6934}
6935
6936const DIAGNOSTIC_MAX: usize = 4_000;
6942
6943const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
6948
6949fn diagnostic(state: &RunState) -> Option<String> {
6963 let mut parts: Vec<String> = Vec::new();
6964
6965 for o in state.gate.iter().filter(|o| !o.ok()) {
6967 parts.push(format!(
6968 "gate `{}` failed ({}):\n{}",
6969 o.command,
6970 notices::exit_status(o.code),
6971 crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
6972 ));
6973 }
6974
6975 if let Some(last) = state
6978 .events
6979 .iter()
6980 .rev()
6981 .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
6982 {
6983 parts.push(last.message.clone());
6984 }
6985
6986 if state.viable().is_empty() {
6993 for c in &state.candidates {
6994 if let Some(evidence) = &c.verified_noop {
6995 parts.push(format!(
6996 "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
6997 c.label
6998 ));
6999 } else if !c.summary.trim().is_empty() {
7000 parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
7001 } else if let Some(why) = &c.failed {
7002 parts.push(format!("candidate {}: {why}", c.label));
7003 }
7004 }
7005 }
7006
7007 if parts.is_empty() {
7008 return None;
7009 }
7010 Some(crate::run::tail(
7015 &parts.join("\n\n"),
7016 DIAGNOSTIC_MAX.saturating_sub(100),
7017 ))
7018}
7019
7020fn label(status: RunStatus) -> &'static str {
7028 status.as_str()
7029}
7030
7031pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
7033 match mode {
7034 "none" => Ok(MergeMode::None),
7035 "local" => Ok(MergeMode::Local),
7036 "pr" => Ok(MergeMode::Pr),
7037 other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
7038 }
7039}
7040
7041fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
7046 mutex
7047 .lock()
7048 .unwrap_or_else(std::sync::PoisonError::into_inner)
7049}
7050
7051#[cfg(test)]
7052mod tests {
7053 use super::*;
7054 use crate::queue::{Source, TaskStatus};
7055 use crate::run::{Candidate, CommandOutcome};
7056 use pretty_assertions::assert_eq;
7057
7058 fn task() -> Task {
7059 Task::new(
7060 "add retries".to_owned(),
7061 "add retries".to_owned(),
7062 PathBuf::from("/repo"),
7063 Source::Human,
7064 )
7065 }
7066
7067 #[test]
7068 fn dispatch_wait_aggregates_unique_skips_in_stable_count_order() {
7069 let skips = DispatchSkips::from([
7070 ("a".into(), SkipReason::CoolingDown),
7071 ("b".into(), SkipReason::WaitingOnLanding),
7072 ("c".into(), SkipReason::WaitingOnLanding),
7073 ("d".into(), SkipReason::OrdinaryCapacity),
7074 ]);
7075 let wait = aggregate_dispatch_wait(4, &skips).unwrap();
7076 assert_eq!(wait.runnable, 4);
7077 assert_eq!(
7078 wait.reasons
7079 .iter()
7080 .map(|r| (r.reason.as_str(), r.count))
7081 .collect::<Vec<_>>(),
7082 [
7083 ("waiting_on_landing", 2),
7084 ("cooling_down", 1),
7085 ("ordinary_capacity", 1)
7086 ]
7087 );
7088 assert_eq!(aggregate_dispatch_wait(0, &DispatchSkips::new()), None);
7089 assert!(
7090 aggregate_dispatch_wait(2, &DispatchSkips::new())
7091 .unwrap()
7092 .reasons
7093 .is_empty()
7094 );
7095 }
7096
7097 #[test]
7098 fn dispatch_wait_tracks_interrupt_withholding_and_set_changes() {
7099 let before = vec!["a".into(), "b".into(), "c".into()];
7100 let allowed = vec![task_with_id("b")];
7101 let skips = interrupt_skips(&before, &allowed);
7102 assert_eq!(
7103 skips,
7104 DispatchSkips::from([
7105 ("a".into(), SkipReason::InterruptGate),
7106 ("c".into(), SkipReason::InterruptGate),
7107 ])
7108 );
7109 let mut previous = DispatchSkips::new();
7110 assert!(!changed_dispatch_skips(&mut previous, DispatchSkips::new()));
7111 assert!(changed_dispatch_skips(&mut previous, skips.clone()));
7112 assert!(!changed_dispatch_skips(&mut previous, skips));
7113 assert!(changed_dispatch_skips(
7114 &mut previous,
7115 DispatchSkips::from([("a".into(), SkipReason::CoolingDown),])
7116 ));
7117 assert!(changed_dispatch_skips(&mut previous, DispatchSkips::new()));
7118 }
7119
7120 #[test]
7121 fn dispatch_wait_status_reads_legacy_and_future_reason_keys() {
7122 let mut value = serde_json::to_value(Status::new()).unwrap();
7123 value.as_object_mut().unwrap().remove("dispatch_wait");
7124 assert!(
7125 serde_json::from_value::<Status>(value.clone())
7126 .unwrap()
7127 .dispatch_wait
7128 .is_none()
7129 );
7130 assert!(
7131 serde_json::from_value::<Reading>(value.clone())
7132 .unwrap()
7133 .dispatch_wait
7134 .is_none()
7135 );
7136 value["dispatch_wait"] = serde_json::json!({
7137 "runnable": 3, "reasons": [{"reason": "future_reason", "count": 3}]
7138 });
7139 let reading = serde_json::from_value::<Reading>(value).unwrap();
7140 assert_eq!(
7141 reading.dispatch_wait.unwrap().reasons[0].reason,
7142 "future_reason"
7143 );
7144 }
7145
7146 fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
7147 let job = crate::worker::Job {
7148 id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
7149 sequence: 1,
7150 kind: "task".into(),
7151 key: format!("task:{}", request.task),
7152 payload: serde_json::to_value(request).unwrap(),
7153 generation: "a".repeat(64),
7154 version: None,
7155 status: crate::worker::Status::Starting,
7156 result: None,
7157 pid: None,
7158 created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
7159 finished_at: None,
7160 };
7161 let dir = home.join("workers/jobs").join(&job.id);
7162 std::fs::create_dir_all(&dir).unwrap();
7163 std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
7164 job
7165 }
7166
7167 #[test]
7168 fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
7169 let home = tempfile::tempdir().unwrap();
7170 let request = TaskWorker {
7171 opts: Opts::default(),
7172 queue: home.path().join("queue"),
7173 task: "startup".into(),
7174 lane: PermitKind::Ordinary,
7175 standalone: false,
7176 };
7177 let job = starting_task_reservation(home.path(), &request);
7178 let error = task_worker_spawn_error(
7179 home.path(),
7180 &request,
7181 anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
7182 )
7183 .expect_err("our own reservation must not turn a failed spawn into a resync");
7184 let active = crate::worker::active(home.path()).unwrap();
7185 assert_eq!(active.len(), 1);
7186 assert_eq!(active[0].id, job.id);
7187 assert_eq!(active[0].status, crate::worker::Status::Starting);
7188 assert!(
7189 crate::worker::control(home.path(), &job.key)
7190 .unwrap()
7191 .is_none()
7192 );
7193 let notices = notices::Notices::at(home.path().join("notifications")).list();
7194 assert_eq!(notices.len(), 1);
7195 assert_eq!(notices[0].key, "loop:worker-startup");
7196 assert!(!notices[0].message.contains("private-error-detail"));
7197 assert!(notices[0].message.contains(&request.task));
7198 assert!(
7199 notices[0]
7200 .message
7201 .contains("could not be started or acknowledged")
7202 );
7203 assert!(notices[0].message.contains("worker.log"));
7204 assert_eq!(
7205 notices[0].link,
7206 Some(Link::Task {
7207 id: request.task.clone()
7208 })
7209 );
7210 assert!(format!("{error:#}").contains("private-error-detail"));
7211 }
7212
7213 #[test]
7214 fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
7215 let home = tempfile::tempdir().unwrap();
7216 let mut request = TaskWorker {
7217 opts: Opts::default(),
7218 queue: home.path().join("queue"),
7219 task: "handoff".into(),
7220 lane: PermitKind::Ordinary,
7221 standalone: true,
7222 };
7223 let job = starting_task_reservation(home.path(), &request);
7224 request.standalone = false;
7225 task_worker_spawn_error(
7226 home.path(),
7227 &request,
7228 anyhow::anyhow!("operation key is already reserved for a different request"),
7229 )
7230 .expect("a different standalone request is the handoff race, not our startup failure");
7231 let active = crate::worker::active(home.path()).unwrap();
7232 assert_eq!(active.len(), 1);
7233 assert_eq!(active[0].id, job.id);
7234 assert_eq!(active[0].payload, job.payload);
7235 assert!(
7236 notices::Notices::at(home.path().join("notifications"))
7237 .list()
7238 .is_empty()
7239 );
7240 }
7241
7242 #[test]
7243 fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
7244 let home = tempfile::tempdir().unwrap();
7245 let queue = Queue::at(home.path().join("queue"));
7246 let mut task = task();
7247 task.runs = vec!["previous".into()];
7248 queue.put(&mut task).unwrap();
7249 let request = TaskWorker {
7250 opts: Opts::default(),
7251 queue: home.path().join("queue"),
7252 task: task.id.clone(),
7253 lane: PermitKind::Ordinary,
7254 standalone: false,
7255 };
7256 let job = starting_task_reservation(home.path(), &request);
7257 let claims = current_work(home.path(), Timestamp::now());
7258 assert_eq!(claims.len(), 1);
7259 assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
7260 assert_eq!(claims[0].run, "previous");
7261 assert!(other_claims_run(&claims, "previous", None));
7262 assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
7265 assert!(is_working_on(home.path(), "previous", Timestamp::now()));
7266 }
7267
7268 #[test]
7269 fn admission_excludes_only_the_callers_exact_reservation() {
7270 let own = Current {
7271 worker: Some("own".into()),
7272 task: "same-task".into(),
7273 run: "previous".into(),
7274 };
7275 assert!(!other_claims_run(
7276 std::slice::from_ref(&own),
7277 "previous",
7278 Some("own")
7279 ));
7280 assert!(other_claims_run(
7281 std::slice::from_ref(&own),
7282 "previous",
7283 None
7284 ));
7285 for worker in [None, Some("other".into())] {
7286 let other = Current {
7287 worker,
7288 ..own.clone()
7289 };
7290 assert!(other_claims_run(
7291 &[own.clone(), other],
7292 "previous",
7293 Some("own")
7294 ));
7295 }
7296 let legacy: Current =
7297 serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
7298 assert!(other_claims_run(&[legacy], "previous", Some("own")));
7299 }
7300
7301 #[test]
7302 fn os_leased_task_worker_survives_wall_clock_advance() {
7303 let home = tempfile::tempdir().unwrap();
7304 let queue = Queue::at(home.path().join("queue"));
7305 let mut task = task();
7306 let run = "20260903-100000-abcd";
7307 task.start(run.into());
7308 queue.put(&mut task).unwrap();
7309 let mut worker = live_task_fixture(home.path(), &task.id).unwrap();
7310 let future = Timestamp::now() + jiff::SignedDuration::from_secs(3600);
7311 assert!(
7312 current_work(home.path(), future)
7313 .iter()
7314 .any(
7315 |claim| claim.worker.as_deref() == Some(worker.job.id.as_str())
7316 && claim.run == run
7317 )
7318 );
7319 worker.release_lease();
7320 assert!(worker.dir.join("job.json").is_file());
7321 assert!(!is_working_on(home.path(), run, future));
7322 let dir = worker.dir.clone();
7323 drop(worker);
7324 assert!(!dir.exists());
7325 }
7326
7327 #[test]
7328 fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
7329 let mut task = task();
7330 let mut run = run_state(RunStatus::Reviewing);
7331 run.task_instruction = Some(task.instruction.clone());
7332 run.reviewed_commits = Some(vec!["committed-fix".into()]);
7333 let branch = "magi/test/B";
7334 run.candidates.push(crate::run::Candidate {
7335 branch: branch.into(),
7336 ..candidate('B', "preserved work", false, None)
7337 });
7338 task.runs = vec![run.id.clone()];
7339 let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
7340 assert_eq!(
7341 review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
7342 Starter::Resume(run.id.clone())
7343 );
7344 assert!(matches!(
7345 review_retry_starter(
7346 &task,
7347 Some(&run),
7348 Some("different"),
7349 true,
7350 unfinished.as_deref()
7351 ),
7352 Starter::Review(_)
7353 ));
7354 assert_eq!(
7355 review_retry_starter(
7356 &task,
7357 Some(&run),
7358 Some(branch),
7359 false,
7360 unfinished.as_deref()
7361 ),
7362 Starter::Start
7363 );
7364 task.instruction.push_str(" changed criteria");
7365 assert!(matches!(
7366 review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
7367 Starter::Review(_)
7368 ));
7369 assert!(matches!(
7370 review_retry_starter(&task, Some(&run), Some(branch), true, None),
7371 Starter::Review(_)
7372 ));
7373 }
7374
7375 #[test]
7376 fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
7377 let dir = tempfile::tempdir().unwrap();
7378 let queue = Queue::at(dir.path().join("queue"));
7379 let mut task = task();
7380 task.status = TaskStatus::Running;
7381 task.attempts = 1;
7382 queue.put(&mut task).unwrap();
7383 let live = std::collections::BTreeSet::from([task.id.clone()]);
7384 assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
7385 drop(queue.claim(&task.id).unwrap());
7386 let saved = queue.get(&task.id).unwrap();
7387 assert_eq!(saved.status, TaskStatus::Running);
7388 assert_eq!(saved.attempts, 1);
7389 assert!(saved.last_error.is_none());
7390 }
7391
7392 #[test]
7393 fn standalone_workers_do_not_consume_scheduler_lanes() {
7394 let request = |task: &str, lane, standalone| TaskWorker {
7395 opts: Opts::default(),
7396 queue: PathBuf::from("/queue"),
7397 task: task.to_owned(),
7398 lane,
7399 standalone,
7400 };
7401 let mut jobs = vec![
7402 request("ordinary", PermitKind::Ordinary, false),
7403 request("standalone-urgent", PermitKind::Urgent, true),
7404 request("standalone-ordinary", PermitKind::Ordinary, true),
7405 request("decision", PermitKind::None, false),
7406 ];
7407 assert_eq!(available_slots(&jobs, 2), (1, 1));
7408 jobs.push(request("urgent", PermitKind::Urgent, false));
7409 assert_eq!(available_slots(&jobs, 2), (1, 0));
7410 assert_eq!(available_slots(&jobs, 0), (0, 0));
7411 }
7412
7413 #[test]
7414 fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
7415 let now = Timestamp::now();
7416 let mut reading = Reading {
7417 pid: Some(std::process::id()),
7418 updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
7419 ..Reading::default()
7420 };
7421 assert!(!reading.running(now));
7422 assert!(legacy_scheduler_running(&reading, now, 0));
7423 reading.worker_protocol = Some(1);
7424 assert!(!legacy_scheduler_running(&reading, now, 0));
7425 }
7426
7427 #[test]
7428 fn selected_public_head_overrides_historical_resume_and_pin() {
7429 let mut t = task();
7430 let mut old = run_state(RunStatus::Blocked);
7431 let selection = crate::pr_recovery::Selection {
7432 url: "url".into(),
7433 branch: format!("magi/task-{}", t.id),
7434 head: "a".repeat(40),
7435 source_head: None,
7436 source_run: None,
7437 source_proof: None,
7438 disposition: Some(crate::pr_recovery::Disposition::Review),
7439 instruction: t.instruction.clone(),
7440 approved_at: Timestamp::now(),
7441 };
7442 t.resume_override = Some(crate::queue::OperatorResume {
7443 pinned_run: Some(old.id.clone()),
7444 question_id: "choice".into(),
7445 at: Timestamp::now(),
7446 conductor_rehold: None,
7447 forced: false,
7448 });
7449 assert_eq!(
7450 selected_starter(&selection, Some(&old), Some(&old.id)),
7451 Starter::Review(selection.branch.clone())
7452 );
7453 old.pr_recovery = Some(selection.clone());
7454 assert_eq!(
7455 selected_starter(&selection, Some(&old), Some(&old.id)),
7456 Starter::Review(selection.branch.clone())
7457 );
7458 old.reviewed_commits = Some(vec!["implementation".into()]);
7459 assert_eq!(
7460 selected_starter(&selection, Some(&old), Some(&old.id)),
7461 Starter::Resume(old.id.clone())
7462 );
7463 let mut changed = selection.clone();
7464 changed.head = "b".repeat(40);
7465 assert_eq!(
7466 selected_starter(&changed, Some(&old), Some(&old.id)),
7467 Starter::Review(changed.branch)
7468 );
7469 }
7470
7471 #[test]
7472 fn candidate_transplant_failure_is_one_actionable_hold() {
7473 let dir = tempfile::tempdir().unwrap();
7474 let q = Queue::at(dir.path().join("queue"));
7475 let mut t = task();
7476 let mut state = run_state(RunStatus::Blocked);
7477 state.event("prep", "cannot apply referenced commit: conflict");
7478 state.prep_failure = Some("conflict".into());
7479 t.start(state.id.clone());
7480 finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
7481 assert_eq!(t.attempts, 1);
7482 assert_eq!(t.status, TaskStatus::Held);
7483 assert!(t.operator_held());
7484 assert!(!t.status.runnable());
7485 assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
7486 let first = t.chat_notice_key().unwrap();
7487 t.chat_notices.push(first.clone());
7488 t.release_operator("test", None);
7489 state.id = "another-unprepared-run".into();
7490 t.start(state.id.clone());
7491 finish_attempt(
7492 3,
7493 &q,
7494 &mut t,
7495 &state,
7496 &[],
7497 Err(anyhow::anyhow!("still conflicts")),
7498 );
7499 assert_eq!(
7500 t.chat_notice_key().as_ref(),
7501 Some(&first),
7502 "no work happened"
7503 );
7504 t.release_operator("test", None);
7505 state.prep_failure = None;
7506 state.status = RunStatus::Failed;
7507 state.begin_pass();
7508 t.start(state.id.clone());
7509 finish_attempt(
7510 1,
7511 &q,
7512 &mut t,
7513 &state,
7514 &[],
7515 Err(anyhow::anyhow!("new gate failure")),
7516 );
7517 let failure = t.chat_notice_key().unwrap();
7518 assert_ne!(failure, first, "approved recovery reached a real failure");
7519 t.release_operator("test", None);
7520 state.begin_pass();
7521 t.start(state.id.clone());
7522 finish_attempt(
7523 1,
7524 &q,
7525 &mut t,
7526 &state,
7527 &[],
7528 Err(anyhow::anyhow!("new failure on resume")),
7529 );
7530 assert_ne!(
7531 t.chat_notice_key().as_ref(),
7532 Some(&failure),
7533 "a new settled pass"
7534 );
7535 }
7536
7537 #[test]
7538 fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
7539 for source in ["cli", "web"] {
7540 let mut t = task();
7541 let mut run = run_state(RunStatus::Blocked);
7542 run.instruction = "Run A original criteria".into();
7543 run.task_instruction = Some(run.instruction.clone());
7544 t.start(run.id.clone());
7545 t.release_operator("choice", Some("resume-question"));
7546 t.resume_override = Some(crate::queue::OperatorResume {
7547 question_id: "resume-question".into(),
7548 at: Timestamp::now(),
7549 conductor_rehold: None,
7550 forced: true,
7551 pinned_run: Some(run.id.clone()),
7552 });
7553 t.hold_machine(Some("not enough free space to start a run".into()));
7554 let mut unchanged = t.clone();
7555 unchanged
7556 .edit("title changed".into(), unchanged.instruction.clone())
7557 .unwrap();
7558 unchanged.release_operator(source, None);
7559 assert_eq!(
7560 unchanged
7561 .resume_override
7562 .as_ref()
7563 .unwrap()
7564 .pinned_run
7565 .as_deref(),
7566 Some(run.id.as_str())
7567 );
7568 assert!(!compatible_run_instruction(&run, &unchanged));
7569 assert!(may_resume_run(&run, &unchanged));
7570
7571 t.edit(
7572 "approved recovery".into(),
7573 "Reuse measured PR head B; fix Clippy; review".into(),
7574 )
7575 .unwrap();
7576 assert!(t.resume_override.is_none());
7577 t.release_operator(source, None);
7578 let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
7579 assert!(reloaded.resume_override.is_none());
7580 assert!(!may_resume_run(&run, &reloaded));
7581 let unfinished =
7582 unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
7583 .filter(|_| may_resume_run(&run, &reloaded));
7584 assert_eq!(
7585 choose_starter(None, false, unfinished.as_deref()),
7586 Starter::Start
7587 );
7588 assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
7589 assert_eq!(
7590 reloaded.resumption_history[0].question_id.as_deref(),
7591 Some("resume-question")
7592 );
7593
7594 unchanged.instruction = "Reuse measured PR head B".into();
7597 unchanged.hold_machine(Some("disk hold".into()));
7598 unchanged.release_operator(source, None);
7599 assert!(unchanged.resume_override.is_none());
7600 assert!(!may_resume_run(&run, &unchanged));
7601 }
7602 }
7603
7604 #[test]
7605 fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
7606 let mut t = task();
7607 let mut run = run_state(RunStatus::Blocked);
7608 t.review_of = Some("approved-head".into());
7609 t.instruction =
7610 "Review the branch `approved-head` (review-only: no implementation, no judging)."
7611 .into();
7612 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();
7613 run.reviewed_commits = Some(vec!["Commit log".into()]);
7614 t.start(run.id.clone());
7615 t.hold_machine(Some("interrupted review".into()));
7616 t.release_operator("cli", None);
7617 assert!(
7618 compatible_run_instruction(&run, &t),
7619 "legacy explicit review remains resumable"
7620 );
7621 let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
7622 .filter(|_| compatible_run_instruction(&run, &t));
7623 assert_eq!(
7624 choose_starter(None, false, unfinished.as_deref()),
7625 Starter::Resume(run.id.clone())
7626 );
7627 run.task_instruction = Some(t.instruction.clone());
7628 assert!(compatible_run_instruction(&run, &t));
7629 let reloaded: RunState =
7630 serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
7631 assert!(compatible_run_instruction(&reloaded, &t));
7632 t.edit(
7633 "new approved head".into(),
7634 "Reuse measured PR head B".into(),
7635 )
7636 .unwrap();
7637 assert!(!compatible_run_instruction(&run, &t));
7638
7639 t.review_of = None;
7641 t.instruction = "Fix Clippy on approved head".into();
7642 run.task_instruction = None;
7643 run.instruction = format!(
7644 "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
7645 t.instruction
7646 );
7647 assert!(compatible_run_instruction(&run, &t));
7648 t.instruction.push('\n');
7649 assert!(
7650 compatible_run_instruction(&run, &t),
7651 "legacy generated review trimmed the original criteria"
7652 );
7653 t.hold_for_handover(Some("approved-head".into()), "refused".into());
7654 assert_eq!(review_branch_for(&t, Some(&run)), Some("approved-head"));
7655 t.edit("new plan".into(), "Reuse measured PR head B".into())
7656 .unwrap();
7657 assert!(review_branch_for(&t, Some(&run)).is_none());
7658 assert!(!compatible_run_instruction(&run, &t));
7659 t.review_branch = Some("approved-head".into());
7660 t.review_instruction = None;
7661 assert!(
7662 review_branch_for(&t, Some(&run)).is_none(),
7663 "legacy retained candidate cannot replace a revised approved head"
7664 );
7665 }
7666
7667 #[test]
7668 fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
7669 let home = crate::run::test_home();
7670 crate::run::pin_test_home();
7671 let dir = tempfile::tempdir().unwrap();
7672 let queue = Queue::at(dir.path().join("queue"));
7673 for resume in [true, false] {
7674 let state = run_state(RunStatus::Blocked);
7675 let mut t = task();
7676 t.start(state.id.clone());
7677 let action = if resume {
7678 ask::ChoiceAction::Resume {
7679 run: state.id.clone(),
7680 }
7681 } else {
7682 ask::ChoiceAction::Requeue
7683 };
7684 let mut q = action_question(&state.id, action);
7685 q.status = ask::QuestionStatus::Open;
7686 q.answer = None;
7687 q.answered_at = None;
7688 t.fail("run stopped with a question", 3);
7689 hold_if_runnable(&queue, &mut t);
7690 assert!(t.operator_decided_at.is_none());
7691 assert!(t.operator_held());
7692 q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
7693 let expected = if resume {
7694 ActionDecision::Resume(state.id.clone())
7695 } else {
7696 ActionDecision::Requeue
7697 };
7698 assert_eq!(
7699 decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
7700 expected
7701 );
7702 t.hold_manual(Some("later explicit hold".into()));
7703 assert_eq!(
7704 decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
7705 ActionDecision::Stale
7706 );
7707 }
7708 }
7709
7710 #[test]
7711 fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
7712 let mut t = task();
7713 t.answers.push(crate::queue::AnsweredQuestion {
7714 question: "Inspect the remote?".into(),
7715 answer: "Inspect then wait".into(),
7716 });
7717 let old = instruction_for(&t);
7718 assert!(compatible_instruction(&old, &t));
7719 t.instruction = "Reuse approved PR head and review".into();
7720 t.release_operator("cli", None);
7721 assert!(!compatible_instruction(&old, &t));
7722 let approved = instruction_for(&t);
7723 assert!(approved.contains("waiting premises are superseded"));
7724 assert!(compatible_instruction(&approved, &t));
7725 assert_eq!(resumed_instruction(&approved, &t), approved);
7726 t.release_operator("web", None);
7727 assert!(compatible_instruction(&approved, &t));
7728 assert_eq!(t.resumption_history.len(), 1);
7729 t.start("run".into());
7730 assert!(instruction_for(&t).contains("Explicit operator resumption"));
7731 }
7732
7733 #[test]
7737 fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
7738 let mut state = RunState::new(
7739 PathBuf::from("/repo"),
7740 "main".into(),
7741 "base".into(),
7742 "task".into(),
7743 Config::default(),
7744 );
7745 state.status = RunStatus::Landing;
7746 state.parked = true;
7747 state.pr_pushed_head = Some("head".into());
7748 state.land_unrelated = Some(
7749 serde_json::from_value(serde_json::json!({
7750 "head": "head", "question": "ci-question",
7751 "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
7752 }))
7753 .unwrap(),
7754 );
7755 let mut t = task();
7756 t.start(state.id.clone());
7757 let verdict = Verdict {
7758 status: RunStatus::Landing,
7759 left_pr: true,
7760 quota_hit: false,
7761 parked: true,
7762 no_viable_candidates: false,
7763 };
7764 settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
7765 assert_eq!(t.attempts, 0);
7766 assert_eq!(t.status, TaskStatus::Held);
7767 assert!(!t.operator_held());
7768 assert!(
7769 t.hold_reason
7770 .as_deref()
7771 .unwrap()
7772 .starts_with("[ci-unrelated]")
7773 );
7774 t.attempts = 1;
7776 settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
7777 assert_eq!(t.attempts, 1);
7778 assert_eq!(t.passes.len(), 1);
7779 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
7780 state.pr_pushed_head = Some("new-head".into());
7781 state.parked = false;
7782 state.status = RunStatus::Blocked;
7783 let stale = Verdict {
7784 status: RunStatus::Blocked,
7785 parked: false,
7786 ..verdict
7787 };
7788 settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
7789 assert_eq!(t.attempts, 1);
7790 state.begin_pass();
7792 state.begin_pass();
7793 state.status = RunStatus::Landing;
7794 state.parked = true;
7795 state.pr_pushed_head = Some("head".into());
7796 settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
7797 assert_eq!(t.attempts, 0);
7798 assert_eq!(t.passes.len(), 2);
7799 }
7800
7801 #[test]
7802 fn orphan_recovery_does_not_refund_a_previous_pass_loss() {
7803 let mut state = run_state(RunStatus::Failed);
7804 state
7805 .quota
7806 .push(loss("advisor-1", "2026-10-22T14:38:00Z", None));
7807 state.begin_pass();
7808 let mut t = task();
7809 t.start(state.id.clone());
7810 reclaim(&mut t, Some(state), 2, "en");
7811 assert_eq!(t.attempts, 1);
7812 }
7813
7814 #[test]
7815 fn an_all_seats_unauthenticated_node_refunds_and_holds_without_retry() {
7816 let mut state = run_state(RunStatus::Blocked);
7817 let losses: Vec<_> = ["alpha", "beta"]
7818 .into_iter()
7819 .enumerate()
7820 .map(|(i, agent)| {
7821 QuotaLoss::from_report(
7822 format!("advisor-{i}"),
7823 "advise",
7824 Some(&crate::agent::Quota {
7825 cause: crate::agent::QuotaCause::Authentication,
7826 agent: agent.to_owned(),
7827 reset: None,
7828 }),
7829 )
7830 })
7831 .collect();
7832 crate::graph::block_machine_outage(&mut state, "advise", &losses);
7833 state.quota = losses;
7834 let mut t = task();
7835 t.start(state.id.clone());
7836 let verdict = Verdict {
7837 status: state.status,
7838 left_pr: false,
7839 quota_hit: true,
7840 parked: false,
7841 no_viable_candidates: true,
7842 };
7843 settle_and_diagnose(&mut t, verdict, "authentication unavailable", 2, &state);
7844 assert_eq!(t.attempts, 0);
7845 assert_eq!(t.status, TaskStatus::Held);
7846 assert!(!t.operator_held());
7847 let reason = t.hold_reason.as_deref().unwrap();
7848 assert!(reason.starts_with("[authentication]"));
7849 assert!(
7850 reason.contains("alpha")
7851 && reason.contains("beta")
7852 && reason.contains("re-authenticate")
7853 );
7854 assert!(cooldown_until(&state.quota, Timestamp::now()).is_none());
7855 let mut orphan = task();
7857 orphan.start(state.id.clone());
7858 reclaim(&mut orphan, Some(state), 2, "en");
7859 assert_eq!(orphan.attempts, 0);
7860 assert_eq!(orphan.status, TaskStatus::Held);
7861 }
7862
7863 #[test]
7864 fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
7865 let mut state = RunState::new(
7866 PathBuf::from("/repo"),
7867 "main".to_owned(),
7868 "abc1234".to_owned(),
7869 "task".to_owned(),
7870 Config::default(),
7871 );
7872 state.status = RunStatus::Blocked;
7873 state.resource_block = Some(crate::run::ResourceBlock {
7874 cause: crate::run::ResourceBlockCause::Other,
7875 node: "graft".to_owned(),
7876 kind: "shared build cache".to_owned(),
7877 detail: "timed out".to_owned(),
7878 at: jiff::Timestamp::now(),
7879 });
7880 let mut t = task();
7881 t.start("20260902-000000-aaaa".to_owned());
7882 assert_eq!(t.attempts, 1);
7883 let verdict = Verdict {
7884 status: RunStatus::Blocked,
7885 left_pr: false,
7886 quota_hit: false,
7887 parked: false,
7888 no_viable_candidates: false,
7889 };
7890 settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
7891 assert_eq!(t.status, TaskStatus::Held);
7892 assert_eq!(t.attempts, 0, "the attempt is refunded");
7893 assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
7894 assert!(
7895 !t.operator_held(),
7896 "a machine hold, released without a human"
7897 );
7898
7899 let mut selected = task();
7900 selected.start("20260902-000000-cccc".into());
7901 selected.replacement = Some(crate::merge_decision::Replacement {
7902 question: "fixture".into(),
7903 run: "earlier".into(),
7904 pr: "https://example.invalid/pr/1".into(),
7905 agent: "selected".into(),
7906 context: "fixture".into(),
7907 });
7908 state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
7909 settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
7910 assert_eq!(selected.attempts, 0);
7911 assert!(
7912 !selected.operator_held(),
7913 "a selected agent also retains a machine resource hold"
7914 );
7915 assert!(
7916 selected
7917 .hold_reason
7918 .as_deref()
7919 .unwrap()
7920 .starts_with("[resource] ")
7921 );
7922
7923 let mut p = task();
7925 p.start("20260902-000000-bbbb".to_owned());
7926 settle_and_diagnose(
7927 &mut p,
7928 Verdict {
7929 parked: true,
7930 ..verdict
7931 },
7932 "parked",
7933 2,
7934 &state,
7935 );
7936 assert_eq!(p.status, TaskStatus::Parked);
7937 assert_eq!(
7938 p.attempts, 0,
7939 "parking refunds once rather than also settling the resource hold"
7940 );
7941 }
7942
7943 #[test]
7944 fn record_failure_notice_links_the_task() {
7945 let dir = tempfile::tempdir().unwrap();
7946 std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
7949 let queue = Queue::at(dir.path().join("queue"));
7950 let mut t = interrupt_task("rec-fail-1");
7951 record(&queue, &mut t);
7952
7953 let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
7954 assert_eq!(found.len(), 1);
7955 assert_eq!(found[0].key, "loop:record");
7956 assert_eq!(
7957 found[0].link,
7958 Some(Link::Task {
7959 id: "rec-fail-1".to_owned()
7960 })
7961 );
7962 }
7963
7964 fn interrupt_task(id: &str) -> Task {
7967 let mut t = task();
7968 t.id = id.to_owned();
7969 t.interrupt = true;
7970 t
7971 }
7972
7973 fn task_with_id(id: &str) -> Task {
7975 let mut t = task();
7976 t.id = id.to_owned();
7977 t
7978 }
7979
7980 fn urgent_task(id: &str) -> Task {
7982 let mut t = task();
7983 t.id = id.to_owned();
7984 t.urgent = true;
7985 t
7986 }
7987
7988 #[test]
7989 fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
7990 let dir = tempfile::tempdir().unwrap();
7991 let queue = Queue::at(dir.path().join("queue"));
7992 let mut parked = task_with_id("parked");
7993 parked.start("run".into());
7994 parked.park("upgrade");
7995 parked.record_pass_at(
7996 "run",
7997 0,
7998 Some(Timestamp::now()),
7999 1,
8000 Some(crate::run::ParkCause::Upgrade {
8001 from: "old".into(),
8002 to: None,
8003 }),
8004 );
8005 let mut fresh = task_with_id("fresh");
8006 fresh.priority = 100;
8007 let mut urgent_task = urgent_task("urgent");
8008 for t in [&mut parked, &mut fresh, &mut urgent_task] {
8009 queue.put(t).unwrap();
8010 }
8011 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
8012 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
8013 let candidates = runnable(&queue);
8014 assert_eq!(candidates[0].id, parked.id);
8015 let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
8016 assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_err());
8017 assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_ok());
8018 drop(first);
8019 let claimed_elsewhere = queue.claim(&parked.id).unwrap();
8020 let next = runnable(&queue)
8021 .into_iter()
8022 .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent).ok())
8023 .unwrap();
8024 assert_eq!(next.task.id, fresh.id);
8025 assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
8026 drop(claimed_elsewhere);
8027 drop(next);
8028 assert!(matches!(
8029 claim_dispatch(&queue, &parked, true, &ordinary, &urgent),
8030 Err(SkipReason::CoolingDown)
8031 ));
8032 }
8033
8034 #[test]
8035 fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
8036 let dir = tempfile::tempdir().unwrap();
8037 let queue = Queue::at(dir.path().join("queue"));
8038 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
8039 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
8040 let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
8041 let mut first = task();
8042 queue.put(&mut first).unwrap();
8043 let stale_plain = queue.get(&first.id).unwrap();
8044 first.set_urgent(true).unwrap();
8045 queue.put(&mut first).unwrap();
8046 let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
8047 let mut second = urgent_task("second");
8048 queue.put(&mut second).unwrap();
8049 assert!(matches!(
8050 claim_dispatch(&queue, &second, false, &ordinary, &urgent),
8051 Err(SkipReason::UrgentCapacity)
8052 ));
8053 drop(queue.claim(&second.id).unwrap());
8054 assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
8055 drop(dispatched);
8056 let stale_urgent = queue.get(&first.id).unwrap();
8057 first.set_urgent(false).unwrap();
8058 queue.put(&mut first).unwrap();
8059 assert!(matches!(
8060 claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent),
8061 Err(SkipReason::OrdinaryCapacity)
8062 ));
8063 assert_eq!(urgent.available_permits(), 1);
8064 drop(queue.claim(&first.id).unwrap());
8065 drop(occupied);
8066 }
8067
8068 #[test]
8069 fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
8070 let dir = tempfile::tempdir().unwrap();
8071 let queue = Queue::at(dir.path().join("queue"));
8072 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
8073 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
8074 let mut t = task();
8075 queue.put(&mut t).unwrap();
8076 for enabled in [true, false] {
8077 let stale = queue.get(&t.id).unwrap();
8078 t.set_urgent(enabled).unwrap();
8079 queue.put(&mut t).unwrap();
8080 assert_ne!(stale.urgent, enabled);
8081 let DispatchClaim {
8082 task: fresh,
8083 claim,
8084 permit,
8085 } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
8086 assert_eq!(fresh.urgent, enabled);
8087 assert_eq!(ordinary.available_permits(), usize::from(enabled));
8088 assert_eq!(urgent.available_permits(), usize::from(!enabled));
8089 assert!(queue.claim(&t.id).is_err());
8090 assert_eq!(fresh.attempts, stale.attempts);
8091 drop((claim, permit));
8092 assert_eq!(ordinary.available_permits(), 1);
8093 assert_eq!(urgent.available_permits(), 1);
8094 }
8095 t.set_urgent(true).unwrap();
8096 queue.put(&mut t).unwrap();
8097 let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
8098 assert!(matches!(
8099 claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8100 Err(SkipReason::UrgentCapacity)
8101 ));
8102 assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
8103 drop(queue.claim(&t.id).unwrap());
8104 assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
8105 drop(occupied);
8106 assert!(matches!(
8107 claim_dispatch(&queue, &t, true, &ordinary, &urgent),
8108 Err(SkipReason::CoolingDown)
8109 ));
8110 drop(queue.claim(&t.id).unwrap());
8111 let held = queue.claim(&t.id).unwrap();
8112 assert!(matches!(
8113 claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8114 Err(SkipReason::ClaimUnavailable)
8115 ));
8116 drop(held);
8117 t.status = TaskStatus::Held;
8118 queue.put(&mut t).unwrap();
8119 assert!(matches!(
8120 claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8121 Err(SkipReason::NoLongerRunnable)
8122 ));
8123 drop(queue.claim(&t.id).unwrap());
8124 std::fs::remove_file(queue.path_of(&t.id)).unwrap();
8125 assert!(matches!(
8126 claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8127 Err(SkipReason::RereadFailed)
8128 ));
8129 drop(queue.claim(&t.id).unwrap());
8130 assert_eq!(urgent.available_permits(), 1);
8131 }
8132
8133 #[test]
8138 fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
8139 assert_eq!(permit_kind(true, false), PermitKind::None);
8140 assert_eq!(permit_kind(true, true), PermitKind::None);
8141 }
8142
8143 #[test]
8148 fn permit_kind_separates_urgent_from_ordinary() {
8149 assert_eq!(permit_kind(false, true), PermitKind::Urgent);
8150 assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
8151 }
8152
8153 #[test]
8160 fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
8161 let cfg = Config::default();
8162 let repo = Path::new("/any/repo/path");
8163
8164 let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(1024))
8165 .expect("must hold below the threshold");
8166 assert!(reason.contains("1024"), "{reason}");
8167 assert!(
8168 reason.contains(&cfg.disk.min_free_bytes.to_string()),
8169 "{reason}"
8170 );
8171
8172 assert_eq!(
8173 disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(cfg.disk.min_free_bytes)),
8174 None,
8175 "exactly at the floor is open"
8176 );
8177 assert_eq!(
8178 disk_gate_with(
8179 repo,
8180 &cfg,
8181 PathBuf::new,
8182 |_| Ok(cfg.disk.min_free_bytes + 1)
8183 ),
8184 None,
8185 "comfortably above the floor is open"
8186 );
8187 }
8188
8189 #[test]
8190 fn disk_gate_with_checks_cache_and_worktree_volumes_and_measurement_errors() {
8191 let dir = tempfile::tempdir().unwrap();
8192 let repo = dir.path().join("repo");
8193 let cache = dir.path().join("cache");
8194 let worktrees = dir.path().join("worktrees");
8195 for path in [&repo, &cache, &worktrees] {
8196 std::fs::create_dir(path).unwrap();
8197 }
8198 let mut cfg = Config::default();
8199 cfg.graph.worktree_root = Some(worktrees.clone());
8200 cfg.verify.gate = vec![format!(
8201 "CARGO_TARGET_DIR='{}' cargo build",
8202 cache.display()
8203 )];
8204 for blocked in [&cache, &worktrees] {
8205 for unmeasured in [false, true] {
8206 assert!(
8207 disk_gate_with(&repo, &cfg, PathBuf::new, |path| {
8208 if path == blocked {
8209 if unmeasured {
8210 Err(anyhow::anyhow!("measurement failed"))
8211 } else {
8212 Ok(0)
8213 }
8214 } else {
8215 Ok(u64::MAX)
8216 }
8217 })
8218 .is_some(),
8219 "a blocked secondary output volume must close admission"
8220 );
8221 }
8222 }
8223 assert!(disk_gate_with(&repo, &cfg, PathBuf::new, |_| Ok(u64::MAX)).is_none());
8224 }
8225
8226 #[test]
8227 fn isolated_admission_measures_the_run_home_instead_of_the_shared_cache() {
8228 let dir = tempfile::tempdir().unwrap();
8229 let repo = dir.path().join("repo");
8230 let cache = dir.path().join("cache");
8231 let home_parent = dir.path().join("run-volume");
8232 let home = home_parent.join("new-home");
8233 for path in [&repo, &cache, &home_parent] {
8234 std::fs::create_dir(path).unwrap();
8235 }
8236 let mut cfg = Config::default();
8237 cfg.graph.worktree_root = Some(repo.clone());
8238 cfg.verify.gate = vec![format!(
8239 "CARGO_TARGET_DIR='{}' cargo build",
8240 cache.display()
8241 )];
8242 cfg.verify.build_cache = BuildCache::Isolated;
8243 let denied = |blocked: &Path| {
8244 disk_gate_with(
8245 &repo,
8246 &cfg,
8247 || home.clone(),
8248 |path| Ok(if path == blocked { 0 } else { u64::MAX }),
8249 )
8250 .is_some()
8251 };
8252 assert!(!denied(&cache));
8253 assert!(denied(&home_parent));
8254 }
8255
8256 #[test]
8257 fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
8258 let mut cfg = Config::default();
8259 cfg.disk.min_free_bytes = 0;
8260 let repo = Path::new("/any/repo/path");
8261 assert_eq!(
8262 disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(0)),
8263 None,
8264 "a zero floor never measures at all"
8265 );
8266 }
8267
8268 #[test]
8269 fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
8270 let cfg = Config::default();
8271 let repo = Path::new("/any/repo/path");
8272 let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| {
8273 Err(anyhow::anyhow!("no df on this box"))
8274 })
8275 .expect("a measurement failure must close the gate, not open it");
8276 assert!(reason.contains("could not measure"), "{reason}");
8277 }
8278
8279 #[test]
8280 fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
8281 let ordinary = task();
8282 let next = advance_interrupt(
8283 Interrupt::Idle,
8284 std::slice::from_ref(&ordinary.id),
8285 std::slice::from_ref(&ordinary),
8286 );
8287 assert_eq!(next, Interrupt::Idle);
8288 }
8289
8290 #[test]
8291 fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
8292 let marked = interrupt_task("marked");
8295 let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
8296 assert_eq!(next, Interrupt::Idle);
8297 }
8298
8299 #[test]
8300 fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
8301 let marked = interrupt_task("marked");
8302 let next = advance_interrupt(
8303 Interrupt::Idle,
8304 &["running".to_owned()],
8305 std::slice::from_ref(&marked),
8306 );
8307 assert_eq!(
8308 next,
8309 Interrupt::Parking {
8310 parked: vec!["running".to_owned()],
8311 interrupt_task: "marked".to_owned(),
8312 }
8313 );
8314 }
8315
8316 #[test]
8325 fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
8326 let marked = interrupt_task("marked");
8327
8328 let two = advance_interrupt(
8329 Interrupt::Idle,
8330 &["a".to_owned(), "b".to_owned()],
8331 std::slice::from_ref(&marked),
8332 );
8333 assert_eq!(two, Interrupt::Idle);
8334
8335 let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
8336 assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
8337 }
8338
8339 #[test]
8340 fn parking_holds_until_every_parked_id_has_actually_left_flight() {
8341 let state = Interrupt::Parking {
8342 parked: vec!["running".to_owned()],
8343 interrupt_task: "marked".to_owned(),
8344 };
8345 let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
8347 assert_eq!(still_going, state);
8348
8349 let stopped_but_not_yet_dispatched =
8353 advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
8354 assert_eq!(stopped_but_not_yet_dispatched, state);
8355
8356 let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
8358 assert_eq!(
8359 dispatched,
8360 Interrupt::Running {
8361 parked: vec!["running".to_owned()],
8362 interrupt_task: "marked".to_owned(),
8363 }
8364 );
8365 }
8366
8367 #[test]
8368 fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
8369 let state = Interrupt::Running {
8370 parked: vec!["running".to_owned()],
8371 interrupt_task: "marked".to_owned(),
8372 };
8373 let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
8374 assert_eq!(still_running, state);
8375
8376 let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
8383 assert_eq!(
8384 ended,
8385 Interrupt::Resuming {
8386 parked: vec!["running".to_owned()]
8387 }
8388 );
8389 }
8390
8391 #[test]
8392 fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
8393 let state = Interrupt::Resuming {
8394 parked: vec!["running".to_owned()],
8395 };
8396 let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
8397 assert_eq!(still_waiting, state);
8398
8399 let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
8400 assert_eq!(dispatched, Interrupt::Idle);
8401 }
8402
8403 #[test]
8409 fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
8410 {
8411 let state = Interrupt::Parking {
8412 parked: vec!["running".to_owned()],
8413 interrupt_task: "marked".to_owned(),
8414 };
8415 let next = advance_interrupt(state, &[], &[]);
8418 assert_eq!(
8419 next,
8420 Interrupt::Resuming {
8421 parked: vec!["running".to_owned()]
8422 },
8423 "abandoning the interrupt must not abandon the resume it owes"
8424 );
8425 }
8426
8427 #[test]
8430 fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
8431 let state = Interrupt::Resuming {
8432 parked: vec!["running".to_owned()],
8433 };
8434 let next = advance_interrupt(state, &[], &[]);
8435 assert_eq!(
8436 next,
8437 Interrupt::Idle,
8438 "nothing is left to wait for; the loop must not stay wedged"
8439 );
8440 }
8441
8442 #[test]
8443 fn disabled_by_config_the_sequence_can_never_leave_idle() {
8444 let marked = interrupt_task("marked");
8445 let next = advance_interrupt_tick(
8446 false,
8447 Interrupt::Idle,
8448 &["running".to_owned()],
8449 std::slice::from_ref(&marked),
8450 );
8451 assert_eq!(
8452 next,
8453 Interrupt::Idle,
8454 "an unmarked, unconfigured daemon must behave exactly as before"
8455 );
8456 }
8457
8458 #[test]
8459 fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
8460 let state = Interrupt::Parking {
8461 parked: vec!["running".to_owned()],
8462 interrupt_task: "marked".to_owned(),
8463 };
8464 let candidates = vec![interrupt_task("marked"), task()];
8465 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
8466 assert!(
8467 allowed.is_empty(),
8468 "nothing may dispatch - not even the interrupt task itself - \
8469 until the parked run has actually stopped"
8470 );
8471 }
8472
8473 #[test]
8487 fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
8488 for state in [
8489 Interrupt::Parking {
8490 parked: vec!["running".to_owned()],
8491 interrupt_task: "marked".to_owned(),
8492 },
8493 Interrupt::Running {
8494 parked: vec!["running".to_owned()],
8495 interrupt_task: "marked".to_owned(),
8496 },
8497 Interrupt::Resuming {
8498 parked: vec!["running".to_owned()],
8499 },
8500 ] {
8501 let candidates = vec![
8502 interrupt_task("marked"),
8503 urgent_task("hot"),
8504 task_with_id("ordinary"),
8505 ];
8506 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
8507 assert!(
8508 !allowed.iter().any(|t| t.id == "hot"),
8509 "an urgent candidate must wait out the same gate as anything \
8510 else while the run it would run alongside has not actually \
8511 left flight, for state {state:?}: {allowed:?}"
8512 );
8513 }
8514 }
8515
8516 #[test]
8522 fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
8523 let state = Interrupt::Resuming {
8524 parked: vec!["hot".to_owned()],
8525 };
8526 let candidates = vec![urgent_task("hot"), task()];
8527 let allowed = interrupt_gate(&state, &[], candidates);
8528 assert_eq!(
8529 allowed.iter().filter(|t| t.id == "hot").count(),
8530 1,
8531 "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
8532 );
8533 }
8534
8535 #[test]
8536 fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
8537 let state = Interrupt::Parking {
8538 parked: vec!["running".to_owned()],
8539 interrupt_task: "marked".to_owned(),
8540 };
8541 let other = task();
8542 let candidates = vec![interrupt_task("marked"), other.clone()];
8543 let allowed = interrupt_gate(&state, &[], candidates);
8544 assert_eq!(allowed.len(), 1);
8545 assert_eq!(allowed[0].id, "marked");
8546 }
8547
8548 #[test]
8549 fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
8550 let state = Interrupt::Running {
8551 parked: vec!["running".to_owned()],
8552 interrupt_task: "marked".to_owned(),
8553 };
8554 let candidates = vec![task(), task()];
8555 let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
8556 assert!(allowed.is_empty());
8557 }
8558
8559 #[test]
8566 fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
8567 let state = Interrupt::Resuming {
8568 parked: vec!["a".to_owned(), "c".to_owned()],
8569 };
8570 let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
8571 let allowed = interrupt_gate(&state, &[], candidates);
8572 assert_eq!(
8573 allowed.len(),
8574 1,
8575 "at most one candidate may be offered while resuming: {allowed:?}"
8576 );
8577 assert_eq!(allowed[0].id, "a");
8578 }
8579
8580 #[test]
8581 fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
8582 let state = Interrupt::Resuming {
8583 parked: vec!["a".to_owned()],
8584 };
8585 let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
8586 assert!(allowed.is_empty());
8587 }
8588
8589 #[test]
8595 fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
8596 let running = task(); let marked = interrupt_task("marked");
8598
8599 let mut state = Interrupt::Idle;
8600 let in_flight = vec![running.id.clone()];
8602 state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
8603 let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
8604 assert!(gated.is_empty(), "still waiting on `running` to park");
8605
8606 state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
8608 let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
8609 assert_eq!(
8610 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8611 vec!["marked"],
8612 "only the interrupt task may be offered to the dispatcher now"
8613 );
8614
8615 state = advance_interrupt_tick(
8617 true,
8618 state,
8619 &["marked".to_owned()],
8620 std::slice::from_ref(&running),
8621 );
8622 let gated = interrupt_gate(
8623 &state,
8624 &["marked".to_owned()],
8625 vec![marked.clone(), running.clone()],
8626 );
8627 assert!(
8628 gated.is_empty(),
8629 "the parked run must not be offered back while the interrupt \
8630 task is still running"
8631 );
8632
8633 let other = task_with_id("other");
8637 state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
8638 assert_eq!(
8639 state,
8640 Interrupt::Resuming {
8641 parked: vec![running.id.clone()]
8642 }
8643 );
8644 let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
8645 assert_eq!(
8646 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8647 vec![running.id.as_str()],
8648 "exactly the parked run resumes - not the unrelated task, even \
8649 though it was offered first"
8650 );
8651
8652 state = advance_interrupt_tick(
8656 true,
8657 state,
8658 std::slice::from_ref(&running.id),
8659 std::slice::from_ref(&other),
8660 );
8661 assert_eq!(state, Interrupt::Idle);
8662 let gated = interrupt_gate(
8663 &state,
8664 std::slice::from_ref(&running.id),
8665 vec![other.clone()],
8666 );
8667 assert_eq!(
8668 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8669 vec![other.id.as_str()],
8670 "ordinary dispatch is unrestricted again"
8671 );
8672 }
8673
8674 #[test]
8675 fn every_run_status_settles_the_task_it_came_from() {
8676 let table = [
8678 (RunStatus::Merged, TaskStatus::Done, 1),
8679 (RunStatus::Ready, TaskStatus::Done, 1),
8680 (RunStatus::Stalled, TaskStatus::Failed, 0),
8681 (RunStatus::Blocked, TaskStatus::Failed, 1),
8682 (RunStatus::Failed, TaskStatus::Failed, 1),
8683 (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
8684 (RunStatus::Prep, TaskStatus::Failed, 1),
8685 (RunStatus::Implementing, TaskStatus::Failed, 1),
8686 (RunStatus::Judging, TaskStatus::Failed, 1),
8687 (RunStatus::Deliberating, TaskStatus::Failed, 1),
8688 (RunStatus::Voting, TaskStatus::Failed, 1),
8689 (RunStatus::Reviewing, TaskStatus::Failed, 1),
8690 (RunStatus::Gating, TaskStatus::Failed, 1),
8691 ];
8692 for (run, want, attempts) in table {
8693 let mut t = task();
8694 t.start("20260902-000000-aaaa".to_owned());
8695 settle(
8696 &mut t,
8697 Verdict {
8698 status: run,
8699 left_pr: false,
8700 parked: false,
8701 quota_hit: matches!(run, RunStatus::Stalled),
8702 no_viable_candidates: false,
8703 },
8704 "why",
8705 2,
8706 );
8707 assert_eq!(t.status, want, "task status after {}", label(run));
8708 assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
8709 }
8710 }
8711
8712 #[test]
8713 fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
8714 let mut stalled = task();
8715 stalled.start("20260902-000000-aaaa".to_owned());
8716 settle(
8717 &mut stalled,
8718 Verdict {
8719 status: RunStatus::Stalled,
8720 left_pr: false,
8721 parked: false,
8722 quota_hit: true,
8723 no_viable_candidates: false,
8724 },
8725 "quota",
8726 1,
8727 );
8728 assert_eq!(stalled.attempts, 0);
8729 assert!(
8730 stalled.status.runnable(),
8731 "a machine problem must leave the task in line"
8732 );
8733
8734 let mut blocked = task();
8735 blocked.start("20260902-000000-aaaa".to_owned());
8736 settle(
8737 &mut blocked,
8738 Verdict {
8739 status: RunStatus::Blocked,
8740 left_pr: false,
8741 parked: false,
8742 quota_hit: false,
8743 no_viable_candidates: false,
8744 },
8745 "findings open",
8746 1,
8747 );
8748 assert_eq!(blocked.attempts, 1);
8749 assert_eq!(
8750 blocked.status,
8751 TaskStatus::Held,
8752 "the last attempt hands the task to a human"
8753 );
8754 }
8755
8756 #[test]
8757 fn a_run_that_opened_a_pull_request_is_never_re_competed() {
8758 let mut delivered = task();
8761 delivered.start("20260903-080619-01c2".to_owned());
8762 settle(
8763 &mut delivered,
8764 Verdict {
8765 status: RunStatus::Blocked,
8766 left_pr: true,
8767 parked: false,
8768 quota_hit: false,
8769 no_viable_candidates: false,
8770 },
8771 "no check status",
8772 4,
8773 );
8774 assert_eq!(
8775 delivered.status,
8776 TaskStatus::Held,
8777 "a pull request waiting on CI or a person is not a retryable failure"
8778 );
8779 assert!(
8780 !delivered.status.runnable(),
8781 "the loop must not pick this task up again"
8782 );
8783 assert_eq!(
8784 delivered.last_error.as_deref(),
8785 Some("no check status"),
8786 "the operator needs to be told what the gate was waiting for"
8787 );
8788
8789 let mut empty_handed = task();
8792 empty_handed.start("20260903-080619-01c2".to_owned());
8793 settle(
8794 &mut empty_handed,
8795 Verdict {
8796 status: RunStatus::Blocked,
8797 left_pr: false,
8798 parked: false,
8799 quota_hit: false,
8800 no_viable_candidates: false,
8801 },
8802 "findings open",
8803 4,
8804 );
8805 assert_eq!(empty_handed.status, TaskStatus::Failed);
8806 assert!(empty_handed.status.runnable());
8807 }
8808
8809 #[test]
8810 fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
8811 let mut noop = task();
8817 noop.start("20260912-131304-391f".to_owned());
8818 settle(
8819 &mut noop,
8820 Verdict {
8821 status: RunStatus::VerifiedNoop,
8822 left_pr: false,
8823 parked: false,
8824 quota_hit: false,
8825 no_viable_candidates: true,
8826 },
8827 "candidate A: already fixed by b32cfc4, on main",
8828 4,
8829 );
8830 assert_eq!(
8831 noop.status,
8832 TaskStatus::Held,
8833 "an unverified claim is a request for a human, not a failure"
8834 );
8835 assert!(
8836 !noop.status.runnable(),
8837 "the loop must not requeue this on the same unverified claim"
8838 );
8839 assert_eq!(noop.attempts, 1);
8844 }
8845
8846 #[test]
8847 fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
8848 let mut parked = task();
8853 parked.start("20260903-183634-2d98".to_owned());
8854 settle(
8855 &mut parked,
8856 Verdict {
8857 status: RunStatus::Implementing,
8858 left_pr: false,
8859 quota_hit: false,
8860 parked: true,
8861 no_viable_candidates: false,
8862 },
8863 "parked after `implementing`",
8864 2,
8865 );
8866 assert_eq!(parked.attempts, 0, "a park is refunded");
8867 assert!(
8868 parked.status.runnable(),
8869 "and the task stays in line so the next loop resumes its run"
8870 );
8871 assert_eq!(parked.status, TaskStatus::Parked);
8872 assert_eq!(
8873 parked.park_reason.as_deref(),
8874 Some("parked after `implementing`"),
8875 "the card says where it stopped"
8876 );
8877 assert_eq!(parked.last_error, None, "nothing failed");
8878
8879 let mut broken = task();
8883 broken.start("20260903-183634-2d98".to_owned());
8884 settle(
8885 &mut broken,
8886 Verdict {
8887 status: RunStatus::Implementing,
8888 left_pr: false,
8889 quota_hit: false,
8890 parked: false,
8891 no_viable_candidates: false,
8892 },
8893 "returned mid-flight",
8894 2,
8895 );
8896 assert_eq!(broken.attempts, 1);
8897 }
8898
8899 #[test]
8900 fn only_a_rate_limit_buys_the_task_its_attempt_back() {
8901 let mut flaky = task();
8906 flaky.start("20260903-123023-e633".to_owned());
8907 settle(
8908 &mut flaky,
8909 Verdict {
8910 status: RunStatus::Stalled,
8911 left_pr: false,
8912 parked: false,
8913 quota_hit: false,
8914 no_viable_candidates: false,
8915 },
8916 "verdict rests on 1 of 3 judges",
8917 2,
8918 );
8919 assert_eq!(
8920 flaky.attempts, 1,
8921 "flakiness spends an attempt, so `max_attempts` still bounds it"
8922 );
8923 assert!(flaky.status.runnable(), "and it is still worth retrying");
8924
8925 let mut limited = task();
8927 limited.start("20260903-123023-e633".to_owned());
8928 settle(
8929 &mut limited,
8930 Verdict {
8931 status: RunStatus::Stalled,
8932 left_pr: false,
8933 parked: false,
8934 quota_hit: true,
8935 no_viable_candidates: false,
8936 },
8937 "judge-2, judge-3 out of quota",
8938 2,
8939 );
8940 assert_eq!(limited.attempts, 0, "a quota window is refunded");
8941 assert!(limited.status.runnable());
8942
8943 let mut worn = task();
8946 for _ in 0..2 {
8947 worn.release();
8948 }
8949 worn.start("20260903-123023-e633".to_owned());
8950 worn.attempts = 2;
8951 settle(
8952 &mut worn,
8953 Verdict {
8954 status: RunStatus::Stalled,
8955 left_pr: false,
8956 parked: false,
8957 quota_hit: false,
8958 no_viable_candidates: false,
8959 },
8960 "no quorum again",
8961 2,
8962 );
8963 assert_eq!(worn.status, TaskStatus::Held);
8964 assert!(!worn.status.runnable());
8965 }
8966
8967 #[test]
8968 fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
8969 let mut wiped_out = task();
8976 wiped_out.start("20260907-025000-a1b2".to_owned());
8977 settle(
8978 &mut wiped_out,
8979 Verdict {
8980 status: RunStatus::Failed,
8981 left_pr: false,
8982 parked: false,
8983 quota_hit: true,
8984 no_viable_candidates: true,
8985 },
8986 "no candidate produced a change; nothing to judge",
8987 2,
8988 );
8989 assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
8990 assert!(
8991 wiped_out.status.runnable(),
8992 "a machine problem must leave the task in line"
8993 );
8994
8995 let mut partial_progress = task();
9001 partial_progress.start("20260907-025500-c3d4".to_owned());
9002 settle(
9003 &mut partial_progress,
9004 Verdict {
9005 status: RunStatus::Failed,
9006 left_pr: false,
9007 parked: false,
9008 quota_hit: true,
9009 no_viable_candidates: false,
9010 },
9011 "gate failed on the winning candidate",
9012 2,
9013 );
9014 assert_eq!(
9015 partial_progress.attempts, 1,
9016 "a candidate that actually produced a change spends the attempt \
9017 even though some other seat hit its quota"
9018 );
9019 assert!(partial_progress.status.runnable());
9020 }
9021
9022 #[test]
9023 fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
9024 let mut t = task();
9030 t.start("20260907-025000-a1b2".to_owned());
9031 let mut state = run_state(RunStatus::Failed);
9032 state.quota.push(QuotaLoss {
9033 cause: crate::agent::QuotaCause::UsageLimit,
9034 agent: String::new(),
9035 seat: "cand-a".to_owned(),
9036 node: "implement".to_owned(),
9037 at: Timestamp::now(),
9038 reset: None,
9039 });
9040 assert!(
9041 state.viable().is_empty(),
9042 "no candidate was added, so nothing is viable"
9043 );
9044 reclaim(&mut t, Some(state), 2, "en");
9045 assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
9046 assert!(t.status.runnable());
9047 }
9048
9049 #[test]
9050 fn a_held_task_is_never_offered_to_the_loop() {
9051 let dir = tempfile::tempdir().unwrap();
9052 let queue = Queue::at(dir.path().to_path_buf());
9053 for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
9054 let mut t = task();
9055 t.id = format!("2026090{n}-000000-000{n}");
9056 t.priority = priority;
9057 queue.put(&mut t).unwrap();
9058 }
9059 let mut held = task();
9060 held.id = "20260909-000000-9999".to_owned();
9061 held.priority = 99;
9062 held.hold_machine(None);
9063 queue.put(&mut held).unwrap();
9064
9065 let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
9066 assert_eq!(order.len(), 3);
9067 assert!(!order.contains(&held.id));
9068 assert_eq!(
9069 order.first().cloned(),
9070 queue.next_runnable().map(|t| t.id),
9071 "the loop's first candidate is exactly what the queue offers"
9072 );
9073 assert_eq!(
9074 order,
9075 vec![
9076 "20260902-000000-0002".to_owned(),
9077 "20260903-000000-0003".to_owned(),
9078 "20260901-000000-0001".to_owned(),
9079 ],
9080 "priority first, then oldest, so nothing starves"
9081 );
9082 }
9083
9084 #[test]
9085 fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
9086 let dir = tempfile::tempdir().unwrap();
9087 let queue = Queue::at(dir.path().to_path_buf());
9088 let mut old = task();
9089 old.id = "20260101-000000-old0".to_owned();
9090 queue.put(&mut old).unwrap();
9091 let mut fresh = task();
9092 fresh.id = "20260101-000000-new0".to_owned();
9093 queue.put(&mut fresh).unwrap();
9094
9095 std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
9099 std::thread::sleep(Duration::from_millis(60));
9100 let live = queue.claim(&fresh.id).unwrap();
9101
9102 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
9103 assert_eq!(swept, vec![old.id.clone()]);
9104 assert!(
9105 queue.claim(&old.id).is_ok(),
9106 "an unparseable lock older than the threshold is swept"
9107 );
9108 assert!(
9109 queue.claim(&fresh.id).is_err(),
9110 "a live pid protects its lock regardless of age"
9111 );
9112 drop(live);
9113 }
9114
9115 #[test]
9116 fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
9117 let dir = tempfile::tempdir().unwrap();
9120 let queue = Queue::at(dir.path().to_path_buf());
9121 let mut t = task();
9122 t.id = "20260101-000000-live".to_owned();
9123 queue.put(&mut t).unwrap();
9124
9125 let claim = queue.claim(&t.id).unwrap();
9126 std::thread::sleep(Duration::from_millis(60));
9127
9128 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
9129 assert!(
9130 swept.is_empty(),
9131 "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
9132 );
9133 assert!(
9134 queue.claim(&t.id).is_err(),
9135 "the lock still protects its task"
9136 );
9137 drop(claim);
9138 }
9139
9140 fn injected_dead_pid() -> u32 {
9143 std::process::id().checked_add(1).unwrap_or(1)
9144 }
9145
9146 #[test]
9147 fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
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-dead".to_owned();
9152 queue.put(&mut t).unwrap();
9153 let dead_pid = injected_dead_pid();
9154
9155 std::fs::write(
9160 dir.path().join(format!("{}.lock", t.id)),
9161 dead_pid.to_string(),
9162 )
9163 .unwrap();
9164
9165 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
9166 pid != dead_pid
9167 });
9168 assert_eq!(
9169 swept,
9170 vec![t.id.clone()],
9171 "a dead owner is reclaimed immediately, not after STALE_CLAIM"
9172 );
9173 assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
9174 }
9175
9176 #[test]
9177 fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
9178 let dir = tempfile::tempdir().unwrap();
9179 let queue = Queue::at(dir.path().to_path_buf());
9180 let mut t = task();
9181 t.id = "20260101-000000-late".to_owned();
9182 queue.put(&mut t).unwrap();
9183 let dead_pid = injected_dead_pid();
9184
9185 assert!(
9188 sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
9189 "nothing has claimed the task yet"
9190 );
9191
9192 std::fs::write(
9195 dir.path().join(format!("{}.lock", t.id)),
9196 dead_pid.to_string(),
9197 )
9198 .unwrap();
9199
9200 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
9204 pid != dead_pid
9205 });
9206 assert_eq!(swept, vec![t.id.clone()]);
9207 }
9208
9209 #[test]
9210 fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
9211 crate::run::pin_test_home();
9216 let dir = tempfile::tempdir().unwrap();
9217 let queue = Queue::at(dir.path().to_path_buf());
9218 let mut t = task();
9219 t.id = "20260101-000000-crsh".to_owned();
9220 t.status = TaskStatus::Running;
9221 t.attempts = 1;
9222 t.runs.push("20260904-000000-4043".to_owned());
9226 queue.put(&mut t).unwrap();
9227 let dead_pid = injected_dead_pid();
9228
9229 std::fs::write(
9232 dir.path().join(format!("{}.lock", t.id)),
9233 dead_pid.to_string(),
9234 )
9235 .unwrap();
9236
9237 assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
9243 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
9244
9245 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
9246 pid != dead_pid
9247 });
9248 assert_eq!(swept, vec![t.id.clone()]);
9249
9250 let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
9251 assert_eq!(reclaimed, vec![t.id.clone()]);
9252 let after = queue.get(&t.id).unwrap();
9253 assert_eq!(
9254 after.status,
9255 TaskStatus::Held,
9256 "no run.json to recover from, so a human is asked"
9257 );
9258 assert_eq!(
9259 after.runs,
9260 vec!["20260904-000000-4043".to_owned()],
9261 "the crashed run's id is kept as evidence, not discarded"
9262 );
9263 }
9264
9265 #[test]
9266 fn a_lock_is_kept_when_the_process_query_is_unavailable() {
9267 let dir = tempfile::tempdir().unwrap();
9268 let queue = Queue::at(dir.path().to_path_buf());
9269 let mut t = task();
9270 t.id = "20260101-000000-unknown".to_owned();
9271 queue.put(&mut t).unwrap();
9272 let dead_pid = injected_dead_pid();
9273 std::fs::write(
9274 dir.path().join(format!("{}.lock", t.id)),
9275 dead_pid.to_string(),
9276 )
9277 .unwrap();
9278
9279 let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
9280 assert!(swept.is_empty(), "an unknown pid must keep its lock");
9281 assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
9282 }
9283
9284 fn run_state_in(status: RunStatus, language: &str) -> RunState {
9285 let mut s = run_state(status);
9286 s.config.graph.language = language.to_owned();
9287 s
9288 }
9289
9290 fn unstarted_verdict(status: RunStatus) -> Verdict {
9291 Verdict {
9292 status,
9293 left_pr: false,
9294 quota_hit: false,
9295 parked: false,
9296 no_viable_candidates: false,
9297 }
9298 }
9299
9300 #[test]
9301 fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
9302 let mut t = task();
9303 t.attempts = 1;
9304 settle_in(
9305 &mut t,
9306 unstarted_verdict(RunStatus::AlreadyInBase),
9307 "already in main",
9308 1,
9309 phrases("en"),
9310 None,
9311 );
9312 assert_eq!(t.status, TaskStatus::Done);
9313 assert_eq!(t.attempts, 0);
9314 }
9315
9316 #[test]
9317 fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
9318 let reason = |language: &str| {
9319 let mut t = task();
9320 settle_in(
9321 &mut t,
9322 unstarted_verdict(RunStatus::Judging),
9323 "boom",
9324 1,
9325 phrases(language),
9326 None,
9327 );
9328 t.last_error.or(t.hold_reason).unwrap_or_default()
9329 };
9330 assert!(
9331 reason("en").starts_with("the graph stopped at `"),
9332 "{}",
9333 reason("en")
9334 );
9335 assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
9336 assert!(reason("日本語").contains("boom"));
9337 assert_eq!(reason("fr"), reason("en"));
9338 }
9339
9340 #[test]
9341 fn describe_follows_the_run_language_and_keeps_the_run_id() {
9342 let en = describe(&run_state_in(RunStatus::Stalled, "en"));
9343 assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
9344 let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
9345 assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
9346 assert!(ja.contains("[run "), "{ja}");
9347 let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
9348 assert!(ended.starts_with("run 終了: "), "{ended}");
9349 let mut de = run_state_in(RunStatus::Failed, "de");
9350 let mut en = run_state_in(RunStatus::Failed, "en");
9351 de.id = "same".to_owned();
9352 en.id = "same".to_owned();
9353 assert_eq!(describe(&de), describe(&en));
9354 }
9355
9356 #[test]
9357 fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
9358 use crate::handover::Refused;
9359 let cases = [
9360 Refused::Foreign {
9361 branch: "b".into(),
9362 path: "/w/x".into(),
9363 why: "made by hand".into(),
9364 },
9365 Refused::Unsafe {
9366 branch: "b".into(),
9367 path: "/w/x".into(),
9368 why: "its worktree has uncommitted changes (a.rs)".into(),
9369 },
9370 Refused::ReleaseFailed {
9371 branch: "b".into(),
9372 path: "/w/x".into(),
9373 run: "ab12".into(),
9374 },
9375 ];
9376 for r in &cases {
9377 let en = (phrases("en").handover_refused)(r);
9378 assert_eq!(en, r.to_string());
9379 let ja = (phrases("ja").handover_refused)(r);
9380 assert!(
9381 !ja.contains("is checked out") && !ja.contains("try again"),
9382 "{ja}"
9383 );
9384 assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
9385 if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
9386 assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
9387 }
9388 }
9389 assert!(phrases("en").handover_hint.contains("release the task"));
9390 assert!(phrases("ja").handover_hint.contains("解放"));
9391 }
9392
9393 #[test]
9394 fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
9395 let build = |lang: &str| {
9396 let mut s = run_state_in(RunStatus::Blocked, lang);
9397 s.id = "same".to_owned();
9398 s.config.graph.review_rounds = 3;
9399 let mut r = review_round(3);
9400 r.expected = 3;
9401 r.answered = 1;
9402 s.reviews.push(r);
9403 s.event(
9404 "review",
9405 "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
9406 );
9407 s
9408 };
9409 let en = describe(&build("en"));
9410 assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
9411 let ja = describe(&build("ja"));
9412 assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
9413 assert!(!ja.contains("never answered"), "{ja}");
9414 assert!(ja.contains("[run "), "{ja}");
9415
9416 let mut failed = build("ja");
9419 failed.reviews[0].e2e.push(crate::run::CommandOutcome {
9420 command: "cargo test".to_owned(),
9421 code: Some(1),
9422 output_tail: String::new(),
9423 duration_ms: 0,
9424 resource_blocked: false,
9425 });
9426 failed.event("review", "stopped; e2e failed: cargo test");
9427 let ja = describe(&failed);
9428 assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
9429 assert!(!ja.contains("席のレビュアー"), "{ja}");
9430 }
9431
9432 #[test]
9433 fn refusals_and_recovery_prose_follow_the_language() {
9434 let home = crate::run::test_home();
9435 let t = held_task_with("r1");
9436 let q = action_question(
9437 "r1",
9438 ask::ChoiceAction::Resume {
9439 run: "r1".to_owned(),
9440 },
9441 );
9442 let refuse = |p: &Phrases| match decide_action(&home, &t, &q, p, |_: &str| bail!("gone")) {
9443 ActionDecision::Refuse(s) => s,
9444 other => panic!("{other:?}"),
9445 };
9446 assert!(refuse(phrases("en")).contains("could not be read: gone"));
9447 assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
9448 assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
9449
9450 let mut held = task();
9451 reclaim(&mut held, None, 2, "ja");
9452 assert!(held.hold_reason.unwrap().contains("保留にしました"));
9453 let mut held = task();
9454 reclaim(&mut held, None, 2, "xx");
9455 assert!(held.hold_reason.unwrap().contains("held for a human"));
9456 }
9457
9458 fn run_state(status: RunStatus) -> RunState {
9459 let mut state = RunState::new(
9460 PathBuf::from("/repo"),
9461 "main".to_owned(),
9462 "abc1234def".to_owned(),
9463 "add retries".to_owned(),
9464 Config::default(),
9465 );
9466 state.status = status;
9467 state
9468 }
9469
9470 #[test]
9471 fn settlement_audits_the_loaded_run_instead_of_reloading_a_stale_snapshot() {
9472 crate::run::pin_test_home();
9473 let dir = tempfile::tempdir().unwrap();
9474 let mut state = run_state(RunStatus::Blocked);
9475 state.id = "20260101-000000-audit".into();
9476 state.save_under(dir.path()).unwrap();
9477 let mut t = task();
9478 t.start(state.id.clone());
9479 state.status = RunStatus::Ready;
9482 settle_and_diagnose(
9483 &mut t,
9484 unstarted_verdict(RunStatus::Ready),
9485 "Verified local delivery",
9486 2,
9487 &state,
9488 );
9489 let completion = t.completion_history.last().unwrap();
9490 assert_eq!(completion.actor, CompletionActor::DaemonSettle);
9491 assert_eq!(completion.prior_status, TaskStatus::Running);
9492 assert_eq!(
9493 completion.reason.as_deref(),
9494 Some("Verified local delivery")
9495 );
9496 let snapshot = completion.run.as_ref().unwrap();
9497 assert_eq!(snapshot.id, state.id);
9498 assert_eq!(snapshot.status, Some(RunStatus::Ready));
9499 assert_eq!(
9500 RunState::load_under(&state.id, dir.path()).unwrap().status,
9501 RunStatus::Blocked,
9502 "settlement records the actual outcome without rewriting run history"
9503 );
9504 }
9505
9506 fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
9507 Candidate {
9508 index: 0,
9509 label,
9510 agent: "claude".to_owned(),
9511 branch: format!("magi/x/{label}"),
9512 worktree: PathBuf::from("/repo"),
9513 summary: summary.to_owned(),
9514 stat: String::new(),
9515 files: 0,
9516 commits: usize::from(!empty),
9517 empty,
9518 failed: failed.map(str::to_owned),
9519 verified_noop: None,
9520 duration_ms: 0,
9521 folded: false,
9522 }
9523 }
9524
9525 #[test]
9526 fn diagnostic_names_the_failing_gate_checks_and_their_output() {
9527 let mut state = run_state(RunStatus::Blocked);
9528 state.gate = vec![
9529 CommandOutcome {
9530 command: "cargo make check".to_owned(),
9531 code: Some(0),
9532 output_tail: "ok".to_owned(),
9533 duration_ms: 0,
9534 resource_blocked: false,
9535 },
9536 CommandOutcome {
9537 command: "cargo test".to_owned(),
9538 code: Some(101),
9539 output_tail: "thread 'x' panicked: assertion failed".to_owned(),
9540 duration_ms: 0,
9541 resource_blocked: false,
9542 },
9543 ];
9544 let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
9545 assert!(d.contains("cargo test"), "{d}");
9546 assert!(
9547 !d.contains("cargo make check"),
9548 "a passing check is not a diagnostic: {d}"
9549 );
9550 assert!(d.contains("assertion failed"), "{d}");
9551 }
9552
9553 #[test]
9554 fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
9555 let mut state = run_state(RunStatus::Blocked);
9556 state.event(
9557 "land",
9558 "stopped: the fixer produced no commit while 2 check(s) were failing \
9559 (build, lint); stopping instead of looping on an unchanged tree",
9560 );
9561 let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
9562 assert!(d.contains("build"), "{d}");
9563 assert!(d.contains("lint"), "{d}");
9564 assert!(d.contains("fixer produced no commit"), "{d}");
9565 }
9566
9567 #[test]
9568 fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
9569 let state = run_state(RunStatus::VerifiedNoop);
9574 let d = describe(&state);
9575 assert!(
9576 d.contains("agent-verified no-op"),
9577 "expected the display label, not the wire spelling: {d}"
9578 );
9579 assert!(!d.contains("verified_noop"), "{d}");
9580 }
9581
9582 #[test]
9583 fn diagnostic_keeps_gate_panic_before_large_backtrace() {
9584 let mut state = run_state(RunStatus::Failed);
9585 state.gate.push(crate::run::CommandOutcome {
9586 command: "cargo test".into(),
9587 code: Some(101),
9588 output_tail: format!(
9589 "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
9590 " 41: 0x1234 - backtrace frame\n".repeat(10000)
9591 ),
9592 duration_ms: 1,
9593 resource_blocked: false,
9594 });
9595 let d = diagnostic(&state).unwrap();
9596 assert!(d.contains("panicked at widget.rs:12"), "{d}");
9597 assert!(d.contains("assertion failed: widget missing"));
9598 assert!(d.contains("widget log"));
9599 }
9600
9601 #[test]
9602 fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
9603 let mut state = run_state(RunStatus::Failed);
9609 state.candidates = vec![candidate(
9610 'A',
9611 "opened pull request #42, merged it, tagged v1.2.3 and published the release",
9612 true,
9613 None,
9614 )];
9615 let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
9616 assert!(d.contains("candidate A"), "{d}");
9617 assert!(d.contains("tagged v1.2.3"), "{d}");
9618 }
9619
9620 #[test]
9621 fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
9622 let mut state = run_state(RunStatus::Failed);
9623 state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
9624 let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
9625 assert!(d.contains("candidate A"), "{d}");
9626 assert!(d.contains("agent timed out"), "{d}");
9627 }
9628
9629 #[test]
9630 fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
9631 let mut state = run_state(RunStatus::Failed);
9634 state.candidates = vec![candidate('A', "did the work", false, None)];
9635 assert!(diagnostic(&state).is_none());
9636 }
9637
9638 #[test]
9639 fn diagnostic_is_bounded_however_much_a_run_printed() {
9640 let mut state = run_state(RunStatus::Blocked);
9641 state.gate = vec![
9642 CommandOutcome {
9643 command: "cargo test".to_owned(),
9644 code: Some(101),
9645 output_tail: "x".repeat(50_000),
9646 duration_ms: 0,
9647 resource_blocked: false,
9648 },
9649 CommandOutcome {
9650 command: "cargo clippy".to_owned(),
9651 code: Some(1),
9652 output_tail: "y".repeat(50_000),
9653 duration_ms: 0,
9654 resource_blocked: false,
9655 },
9656 ];
9657 state.candidates = vec![
9658 candidate('A', &"z".repeat(50_000), true, None),
9659 candidate('B', &"w".repeat(50_000), true, None),
9660 ];
9661 let d = diagnostic(&state).expect("plenty here to diagnose");
9662 assert!(
9663 d.len() <= DIAGNOSTIC_MAX,
9664 "diagnostic grew to {} bytes, unbounded",
9665 d.len()
9666 );
9667 }
9668
9669 #[test]
9670 fn selected_delivery_guards_survive_recovery_failure_accounting() {
9671 for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
9672 let mut t = task();
9673 let mut state = run_state(status);
9674 t.pr_recovery = Some(crate::pr_recovery::Selection {
9675 url: "url".into(),
9676 branch: format!("magi/task-{}", t.id),
9677 head: "a".repeat(40),
9678 source_head: None,
9679 source_run: None,
9680 source_proof: None,
9681 disposition: Some(crate::pr_recovery::Disposition::Land),
9682 instruction: t.instruction.clone(),
9683 approved_at: Timestamp::now(),
9684 });
9685 state.pr_recovery = t.pr_recovery.clone();
9686 t.start(state.id.clone());
9687 settle_and_diagnose(
9688 &mut t,
9689 Verdict {
9690 status,
9691 left_pr: false,
9692 quota_hit: false,
9693 parked: false,
9694 no_viable_candidates: false,
9695 },
9696 "delivery stopped",
9697 5,
9698 &state,
9699 );
9700 assert_eq!(t.status, TaskStatus::Held);
9701 let reason = t.hold_reason.as_deref().unwrap();
9702 if status == RunStatus::Ready {
9703 assert!(reason.contains("Selected PR delivery is incomplete"));
9704 assert!(t.recovery_budget.is_none());
9705 } else {
9706 assert!(reason.contains("Selected recovery stopped"));
9707 assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
9708 }
9709 assert!(t.pr_recovery.is_some());
9710 }
9711 }
9712
9713 #[test]
9714 fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
9715 let mut state = run_state(RunStatus::Voting);
9716 state.base_sync = Some(crate::run::BaseSync {
9717 tip: "base-tip".into(),
9718 behind: 3,
9719 attempts: 4,
9720 conflict: Some("base stopped".into()),
9721 already_in: None,
9722 });
9723 state.record_base_sync_stop("candidate-head");
9724 let mut t = task();
9725 t.start(state.id.clone());
9726 let verdict = Verdict {
9727 status: RunStatus::Blocked,
9728 left_pr: false,
9729 quota_hit: false,
9730 parked: false,
9731 no_viable_candidates: false,
9732 };
9733 settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
9734 assert_eq!(
9735 t.status,
9736 TaskStatus::Held,
9737 "unspent task attempts cannot start another competition"
9738 );
9739 let at = t.held_at;
9740 let cause = t.hold_notice_cause.clone();
9741 state.begin_pass();
9742 t.release_operator("test-resume", None);
9743 t.start(state.id.clone());
9744 settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
9745 assert_eq!(t.status, TaskStatus::Held);
9746 assert_eq!(t.held_at, at);
9747 assert_eq!(t.hold_notice_cause, cause);
9748 }
9749
9750 #[test]
9751 fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
9752 let mut state = run_state(RunStatus::Blocked);
9753 state.gate = vec![CommandOutcome {
9754 command: "cargo test".to_owned(),
9755 code: Some(101),
9756 output_tail: "assertion failed".to_owned(),
9757 duration_ms: 0,
9758 resource_blocked: false,
9759 }];
9760 let verdict = Verdict {
9761 status: RunStatus::Blocked,
9762 left_pr: false,
9763 quota_hit: false,
9764 parked: false,
9765 no_viable_candidates: false,
9766 };
9767
9768 let mut t = task();
9771 t.start("run-1".to_owned());
9772 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
9773 assert_eq!(t.status, TaskStatus::Failed);
9774 assert!(t.diagnostic.is_none());
9775
9776 t.start("run-2".to_owned());
9779 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
9780 assert_eq!(t.status, TaskStatus::Held);
9781 let d = t.diagnostic.expect("a held task must carry its diagnostic");
9782 assert!(d.contains("cargo test"), "{d}");
9783 }
9784
9785 #[test]
9786 fn a_held_task_names_the_open_question_it_is_waiting_on() {
9787 crate::run::pin_test_home();
9792 let home = crate::run::home();
9793 let state = run_state(RunStatus::VerifiedNoop);
9794 let mut q = ask::Question::new(
9795 state.id.clone(),
9796 "implement".to_owned(),
9797 "impl-A".to_owned(),
9798 "is this really a no-op?".to_owned(),
9799 String::new(),
9800 Vec::new(),
9801 );
9802 Questions::at(home.join("questions")).put(&mut q).unwrap();
9803
9804 let verdict = Verdict {
9805 status: RunStatus::VerifiedNoop,
9806 left_pr: false,
9807 quota_hit: false,
9808 parked: false,
9809 no_viable_candidates: false,
9810 };
9811 let mut t = task();
9812 t.start(state.id.clone());
9813 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
9814
9815 assert_eq!(t.status, TaskStatus::Held);
9816 let reason = t.hold_reason.expect("a held task must record why");
9817 assert!(
9818 reason.starts_with("run ended agent-verified no-op"),
9819 "the original settle reason must survive unchanged: {reason}"
9820 );
9821 assert!(
9822 reason.contains(q.short()),
9823 "the open question's id must be named so the notice is actionable: {reason}"
9824 );
9825 }
9826
9827 #[test]
9828 fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
9829 crate::run::pin_test_home();
9830 let state = run_state(RunStatus::VerifiedNoop);
9831
9832 let verdict = Verdict {
9833 status: RunStatus::VerifiedNoop,
9834 left_pr: false,
9835 quota_hit: false,
9836 parked: false,
9837 no_viable_candidates: false,
9838 };
9839 let mut t = task();
9840 t.start(state.id.clone());
9841 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
9842
9843 assert_eq!(t.status, TaskStatus::Held);
9844 assert_eq!(
9845 t.hold_reason.as_deref(),
9846 Some("run ended agent-verified no-op"),
9847 "nothing to append when the question was already answered or never asked"
9848 );
9849 }
9850
9851 #[test]
9852 fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
9853 crate::run::pin_test_home();
9854 let mut first = run_state(RunStatus::Blocked);
9855 first.id = "20260101-000000-sup1".to_owned();
9856 first.save().unwrap();
9857 let mut second = run_state(RunStatus::Merged);
9858 second.id = "20260101-000000-sup2".to_owned();
9859 second.save().unwrap();
9860
9861 let mut t = task();
9862 t.runs = vec![first.id.clone(), second.id.clone()];
9863 t.status = TaskStatus::Done;
9864
9865 supersede_prior_runs(&t, &crate::run::home());
9866
9867 assert_eq!(
9868 RunState::load(&first.id).unwrap().status,
9869 RunStatus::Superseded,
9870 "the first attempt's Blocked no longer needs anyone's attention"
9871 );
9872 assert_eq!(
9873 RunState::load(&second.id).unwrap().status,
9874 RunStatus::Merged,
9875 "the run that actually succeeded is left exactly as it was"
9876 );
9877 }
9878
9879 #[test]
9880 fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
9881 crate::run::pin_test_home();
9887 let mut first = run_state(RunStatus::Blocked);
9888 first.id = "20260101-000000-sup9".to_owned();
9889 first.driver_pid = Some(std::process::id());
9892 first.driver_started_at = Some(
9893 crate::proc::process_started_at(std::process::id())
9894 .expect("this test process's own start time must be queryable"),
9895 );
9896 first.save().unwrap();
9897 let mut second = run_state(RunStatus::Merged);
9898 second.id = "20260101-000000-supa".to_owned();
9899 second.save().unwrap();
9900
9901 let mut t = task();
9902 t.runs = vec![first.id.clone(), second.id.clone()];
9903 t.status = TaskStatus::Done;
9904
9905 supersede_prior_runs(&t, &crate::run::home());
9906
9907 assert_eq!(
9908 RunState::load(&first.id).unwrap().status,
9909 RunStatus::Blocked,
9910 "a live driver_pid means something is still actually working this run, \
9911 even though no daemon claims it - rewriting under it would just be \
9912 undone the next time that process saves"
9913 );
9914 }
9915
9916 #[test]
9917 fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
9918 let dir = tempfile::tempdir().unwrap();
9924 let home = dir.path().to_path_buf();
9925 let queue = Queue::at(dir.path().join("queue"));
9926
9927 let mut first = run_state(RunStatus::Blocked);
9928 first.id = "20260101-000000-supd".to_owned();
9929 first.driver_pid = Some(std::process::id());
9930 first.driver_started_at = Some(
9931 crate::proc::process_started_at(std::process::id())
9932 .expect("this test process's own start time must be queryable"),
9933 );
9934 first.save_under(&home).unwrap();
9935 let mut second = run_state(RunStatus::Merged);
9936 second.id = "20260101-000000-supe".to_owned();
9937 second.save_under(&home).unwrap();
9938
9939 let mut t = task();
9940 t.runs = vec![first.id.clone(), second.id.clone()];
9941 t.status = TaskStatus::Done;
9942 queue.put(&mut t).unwrap();
9943
9944 resweep_superseded_attempts(&queue, &home);
9945 assert_eq!(
9946 RunState::load_under(&first.id, &home).unwrap().status,
9947 RunStatus::Blocked,
9948 "still live on the first pass, so still untouched"
9949 );
9950
9951 let mut stale = RunState::load_under(&first.id, &home).unwrap();
9957 stale.driver_started_at = Some("1".to_owned());
9958 stale.save_under(&home).unwrap();
9959
9960 resweep_superseded_attempts(&queue, &home);
9961 assert_eq!(
9962 RunState::load_under(&first.id, &home).unwrap().status,
9963 RunStatus::Superseded,
9964 "the second pass catches up what the first one correctly skipped"
9965 );
9966 }
9967
9968 #[test]
9969 fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
9970 crate::run::pin_test_home();
9971 let mut first = run_state(RunStatus::Blocked);
9972 first.id = "20260101-000000-sup3".to_owned();
9973 first.save().unwrap();
9974 let mut second = run_state(RunStatus::Blocked);
9975 second.id = "20260101-000000-sup4".to_owned();
9976 second.save().unwrap();
9977
9978 let mut t = task();
9979 t.runs = vec![first.id.clone(), second.id.clone()];
9980 t.status = TaskStatus::Failed;
9984
9985 supersede_prior_runs(&t, &crate::run::home());
9986
9987 assert_eq!(
9988 RunState::load(&first.id).unwrap().status,
9989 RunStatus::Blocked
9990 );
9991 assert_eq!(
9992 RunState::load(&second.id).unwrap().status,
9993 RunStatus::Blocked
9994 );
9995 }
9996
9997 #[test]
9998 fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
9999 crate::run::pin_test_home();
10003 let mut first = run_state(RunStatus::Blocked);
10004 first.id = "20260101-000000-sup5".to_owned();
10005 first.save().unwrap();
10006
10007 let mut t = task();
10008 t.runs = vec![first.id.clone()];
10009 t.status = TaskStatus::Done;
10010
10011 supersede_prior_runs(&t, &crate::run::home());
10012
10013 assert_eq!(
10014 RunState::load(&first.id).unwrap().status,
10015 RunStatus::Blocked,
10016 "a single-attempt task has no earlier run to supersede"
10017 );
10018 }
10019
10020 #[test]
10021 fn supersede_prior_runs_preserves_blocked_work_after_an_audited_manual_close() {
10022 for status in [
10023 RunStatus::Blocked,
10024 RunStatus::Stalled,
10025 RunStatus::Failed,
10026 RunStatus::Ready,
10027 RunStatus::Merged,
10028 ] {
10029 let dir = tempfile::tempdir().unwrap();
10030 let home = dir.path();
10031 let mut first = run_state(RunStatus::Blocked);
10032 first.id = "20260101-000000-supb".to_owned();
10033 first.save_under(home).unwrap();
10034 let mut second = run_state(status);
10035 second.id = "20260101-000000-supc".to_owned();
10036 second.save_under(home).unwrap();
10037
10038 let mut t = task();
10039 t.runs = vec![first.id.clone(), second.id.clone()];
10040 t.hold_manual(Some("Unmerged work remains".into()));
10041 let mut context = CompletionContext::new(
10042 CompletionActor::Cli,
10043 Some("Discard the unmerged attempts".into()),
10044 home,
10045 &t,
10046 );
10047 context.discard = true;
10048 t.succeed(context);
10049 assert_eq!(t.completion_history.len(), 1);
10050
10051 supersede_prior_runs(&t, home);
10052
10053 assert_eq!(
10054 RunState::load_under(&first.id, home).unwrap().status,
10055 RunStatus::Blocked,
10056 "an audited manual close is not proof the earlier work landed"
10057 );
10058 assert_eq!(
10059 RunState::load_under(&second.id, home).unwrap().status,
10060 status,
10061 "the latest attempt retains its actual outcome"
10062 );
10063 }
10064 }
10065
10066 #[test]
10067 fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
10068 crate::run::pin_test_home();
10072 let mut failed = run_state(RunStatus::Failed);
10073 failed.id = "20260101-000000-sup6".to_owned();
10074 failed.save().unwrap();
10075 let mut noop = run_state(RunStatus::VerifiedNoop);
10076 noop.id = "20260101-000000-sup7".to_owned();
10077 noop.save().unwrap();
10078 let mut winner = run_state(RunStatus::Ready);
10079 winner.id = "20260101-000000-sup8".to_owned();
10080 winner.save().unwrap();
10081
10082 let mut t = task();
10083 t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
10084 t.status = TaskStatus::Done;
10085
10086 supersede_prior_runs(&t, &crate::run::home());
10087
10088 assert_eq!(
10089 RunState::load(&failed.id).unwrap().status,
10090 RunStatus::Failed
10091 );
10092 assert_eq!(
10093 RunState::load(&noop.id).unwrap().status,
10094 RunStatus::VerifiedNoop
10095 );
10096 }
10097
10098 fn approval_question(run: &str) -> ask::Question {
10099 ask::Question::new(
10100 run.to_owned(),
10101 land::APPROVAL_NODE.to_owned(),
10102 "land".to_owned(),
10103 "merge?".to_owned(),
10104 String::new(),
10105 vec!["merge".to_owned(), "hold".to_owned()],
10106 )
10107 }
10108
10109 #[test]
10110 fn land_resume_state_leaves_a_fresh_open_question_waiting() {
10111 crate::run::pin_test_home();
10112 let mut state = run_state(RunStatus::Landing);
10113 state.id = "20260101-000000-fre1".to_owned();
10114 state.parked = true;
10115 state.save().unwrap();
10116 ask::Questions::open()
10117 .put(&mut approval_question(&state.id))
10118 .unwrap();
10119
10120 let mut t = task();
10121 t.runs.push(state.id.clone());
10122 assert_eq!(
10123 land_resume_state(&t),
10124 LandResume::StillWaiting,
10125 "nobody has answered and the timeout has not passed"
10126 );
10127 }
10128
10129 #[test]
10130 fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
10131 crate::run::pin_test_home();
10132 let mut state = run_state(RunStatus::Gating);
10133 state.id = "20260101-000000-gt01".to_owned();
10134 state.parked = true;
10135 state.config.graph.answer_timeout = 60;
10136 state.github_text = Some(crate::run::GithubTextAsk {
10137 rewrite: None,
10138 fingerprint: "f".into(),
10139 title: true,
10140 body: false,
10141 categories: vec!["title-language".into()],
10142 question: None,
10143 asks: 1,
10144 resolved: false,
10145 chosen_title: None,
10146 choice: None,
10147 publication: None,
10148 });
10149 state.save().unwrap();
10150 let store = ask::Questions::open();
10151 let mut q = ask::Question::new(
10152 state.id.clone(),
10153 crate::github_text::ASK_NODE.to_owned(),
10154 crate::github_text::ASK_SEAT.to_owned(),
10155 "s".into(),
10156 String::new(),
10157 vec!["use fallback".into()],
10158 );
10159 store.put(&mut q).unwrap();
10160 let mut t = task();
10161 t.runs.push(state.id.clone());
10162 assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
10163 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
10164 store.put(&mut q).unwrap();
10165 assert_eq!(land_resume_state(&t), LandResume::Ready);
10166 assert!(!store.get(&q.id).unwrap().status.open());
10167 state.github_text.as_mut().unwrap().resolved = true;
10169 state.save().unwrap();
10170 assert_eq!(land_resume_state(&t), LandResume::NotLanding);
10171 }
10172
10173 #[test]
10174 fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
10175 crate::run::pin_test_home();
10180 let mut state = run_state(RunStatus::Landing);
10181 state.id = "20260101-000000-exp1".to_owned();
10182 state.parked = true;
10183 state.config.graph.answer_timeout = 60;
10184 state.save().unwrap();
10185
10186 let store = ask::Questions::open();
10187 let mut q = approval_question(&state.id);
10188 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
10189 store.put(&mut q).unwrap();
10190
10191 let mut t = task();
10192 t.runs.push(state.id.clone());
10193 assert_eq!(
10194 land_resume_state(&t),
10195 LandResume::Ready,
10196 "an expired question must not be waited on forever"
10197 );
10198
10199 let after = store.get(&q.id).unwrap();
10200 assert!(
10201 !after.status.open(),
10202 "the question is abandoned, not silently ignored"
10203 );
10204 assert!(
10205 after.resolution().is_none(),
10206 "an abandoned question is not read as a decision"
10207 );
10208 }
10209
10210 #[test]
10211 fn reclaim_settles_a_running_task_against_its_last_run() {
10212 let mut t = task();
10213 t.start("20260904-000000-4043".to_owned());
10214 reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
10215 assert_eq!(
10216 t.status,
10217 TaskStatus::Done,
10218 "a run that actually finished must not stay `running` forever"
10219 );
10220 }
10221
10222 #[test]
10223 fn reclaim_preserves_dispatched_inquiries_until_a_committed_pass() {
10224 let dir = tempfile::tempdir().unwrap();
10225 let queue = Queue::at(dir.path().join("queue"));
10226 let mut task = task();
10227 let mut run = run_state(RunStatus::Blocked);
10228 run.reserve_under(dir.path()).unwrap();
10229 run.driver_exited = true;
10230 run.save_under(dir.path()).unwrap();
10231 queue.put(&mut task).unwrap();
10232 let stale = task.clone();
10233 task.resume_override = Some(crate::queue::OperatorResume {
10234 question_id: "pending-resume".into(),
10235 at: Timestamp::now(),
10236 conductor_rehold: None,
10237 forced: true,
10238 pinned_run: Some(run.id.clone()),
10239 });
10240 task.start(run.id.clone());
10241 queue.put(&mut task).unwrap();
10242 let mut recovered = queue.get(&task.id).unwrap();
10244 let disk = RunState::load_under(&run.id, dir.path()).unwrap();
10245 reclaim(&mut recovered, Some(disk), 2, "en");
10246 queue.put(&mut recovered).unwrap();
10247 assert!(recovered.resume_override.is_none());
10248 assert_eq!(
10249 recovered.dispatched_resumes.get("pending-resume"),
10250 Some(&run.id)
10251 );
10252 let mut stale = stale;
10253 queue.put(&mut stale).unwrap();
10254 assert_eq!(
10255 stale.dispatched_resumes, recovered.dispatched_resumes,
10256 "a stale task writer cannot erase dispatch ownership"
10257 );
10258 let mut resumed = RunState::load_under(&run.id, dir.path()).unwrap();
10259 assert!(resumed.decision_starts.is_empty());
10260 resumed.carry_dispatched_resumes(&queue.get(&task.id).unwrap());
10261 assert!(
10262 resumed.decision_starts.is_empty(),
10263 "handoff is not execution proof"
10264 );
10265 resumed.begin_pass();
10266 resumed.save_under(dir.path()).unwrap();
10267 let mut disk = RunState::load_under(&run.id, dir.path()).unwrap();
10268 assert_eq!(disk.decision_starts.get("pending-resume"), Some(&0));
10269 disk.carry_dispatched_resumes(&recovered);
10270 disk.begin_pass();
10271 assert_eq!(
10272 disk.decision_starts.get("pending-resume"),
10273 Some(&0),
10274 "later execution must preserve the original pass receipt"
10275 );
10276 }
10277
10278 #[test]
10279 fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
10280 let mut t = task();
10281 t.start("20260904-000000-4043".to_owned());
10282 t.last_error = Some("earlier trouble".to_owned());
10283 let mut state = run_state(RunStatus::Judging);
10284 state.parked = true;
10285 reclaim(&mut t, Some(state), 1, "en");
10286 assert_eq!(t.status, TaskStatus::Parked);
10287 assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
10288 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
10289 assert!(t.park_reason.is_some());
10290 assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
10291 assert!(!t.fresh_start);
10292 assert!(t.status.runnable());
10293 }
10294
10295 #[test]
10296 fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
10297 let mut t = task();
10298 t.start("20260904-000000-4043".to_owned());
10299 t.last_error = Some("earlier trouble".to_owned());
10300 settle(
10301 &mut t,
10302 Verdict {
10303 status: RunStatus::Judging,
10304 left_pr: false,
10305 quota_hit: false,
10306 parked: true,
10307 no_viable_candidates: false,
10308 },
10309 "parked after `judging`",
10310 1,
10311 );
10312 assert_eq!(t.status, TaskStatus::Parked);
10313 assert_eq!(t.attempts, 0);
10314 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
10315 assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
10316 assert_eq!(t.schema, crate::queue::SCHEMA);
10317 assert!(
10318 crate::notices::task_held(&t).is_none(),
10319 "a park is not news"
10320 );
10321 t.start("20260904-000000-4043".to_owned());
10322 assert_eq!(t.park_reason, None);
10323 }
10324
10325 #[test]
10326 fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
10327 let mut t = task();
10331 t.start("20260904-000000-4043".to_owned());
10332 reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
10333 assert_eq!(t.status, TaskStatus::Failed);
10334 assert!(t.status.runnable());
10335 }
10336
10337 #[test]
10338 fn a_settled_parked_pass_records_its_cause_and_the_refund() {
10339 let mut t = task();
10340 t.start("20260904-000000-4043".to_owned());
10341 assert_eq!(t.attempts, 1);
10342 let mut run = run_state(RunStatus::Implementing);
10343 run.id = "20260904-000000-4043".to_owned();
10344 run.begin_pass();
10345 let cause = crate::run::ParkCause::Upgrade {
10346 from: "0.121.0".to_owned(),
10347 to: Some("0.121.1".to_owned()),
10348 };
10349 run.end_pass_parked(cause.clone());
10350 run.parked = true;
10351 let verdict = Verdict {
10352 status: run.status,
10353 left_pr: false,
10354 quota_hit: false,
10355 parked: true,
10356 no_viable_candidates: false,
10357 };
10358 let mut orphan = t.clone();
10361 reclaim(&mut orphan, Some(run.clone()), 2, "en");
10362 assert_eq!(orphan.status, TaskStatus::Parked);
10363 assert_eq!(orphan.attempts, 0);
10364 assert_eq!(
10365 orphan.upgrade_resume_key(),
10366 Some((run.passes[0].started_at, orphan.id.as_str()))
10367 );
10368 settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
10369 assert_eq!(t.attempts, 0);
10370 assert_eq!(t.passes.len(), 1);
10371 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
10372 assert_eq!(t.passes[0].parked, Some(cause));
10373 assert_eq!(t.passes[0].pass_index, 0);
10374 assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
10375 assert!(t.upgrade_resume_key().is_some());
10376
10377 t.start("20260904-000000-4043".to_owned());
10380 run.begin_pass();
10381 run.status = RunStatus::Failed;
10382 let verdict = Verdict {
10383 status: RunStatus::Failed,
10384 left_pr: false,
10385 quota_hit: false,
10386 parked: false,
10387 no_viable_candidates: false,
10388 };
10389 settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
10390 assert_eq!(t.passes.len(), 2);
10391 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
10392 assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
10393 assert_eq!(t.passes[1].pass_index, 1);
10394 assert_eq!(t.attempts, 1);
10395 }
10396
10397 #[test]
10398 fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
10399 let mut t = task();
10400 t.start("20260904-000000-4043".to_owned());
10401 reclaim(&mut t, None, 2, "en");
10402 assert_eq!(t.status, TaskStatus::Held);
10403 assert!(
10404 t.last_error
10405 .as_deref()
10406 .is_some_and(|e| e.contains("running")),
10407 "the operator needs to know why this task was held"
10408 );
10409 }
10410
10411 #[test]
10412 fn sync_base_only_orphan_holds_without_replay_or_attempt_change() {
10413 let dir = tempfile::tempdir().unwrap();
10414 let queue = Queue::at(dir.path().to_path_buf());
10415 let mut task = task();
10416 let run = "20261124-000000-dead";
10417 task.link_run(run);
10418 task.attempts = 2;
10419 task.status = TaskStatus::Running;
10420 task.sync_only = Some(crate::base_sync_only::Request {
10421 run: run.into(),
10422 at: Timestamp::now(),
10423 });
10424 queue.put(&mut task).unwrap();
10425 assert_eq!(
10426 reclaim_orphaned_running(&queue, 3, &Default::default()),
10427 vec![task.id.clone()]
10428 );
10429 let saved = queue.get(&task.id).unwrap();
10430 assert_eq!(saved.status, TaskStatus::Held);
10431 assert_eq!(saved.attempts, 2);
10432 assert_eq!(saved.execution_runs(), [run]);
10433 assert!(
10434 saved
10435 .last_error
10436 .unwrap()
10437 .contains("verification was not allowed")
10438 );
10439 assert!(reclaim_orphaned_running(&queue, 3, &Default::default()).is_empty());
10440 }
10441
10442 #[test]
10443 fn sync_base_only_completed_orphan_holds_without_charging_or_double_refunding() {
10444 use crate::base_sync_only::{Outcome, Pass, Request};
10445
10446 let mut state = run_state(RunStatus::Blocked);
10447 let mut task = task();
10448 let request = Request {
10449 run: state.id.clone(),
10450 at: Timestamp::now(),
10451 };
10452 task.start(state.id.clone());
10453 task.sync_only = Some(request.clone());
10454 task.attempts = 2;
10456 let mut pass = Pass::new(request, &state);
10457 pass.result = Outcome::AlreadyCurrent;
10458 state.sync_only_passes.push(pass);
10459 state.begin_pass();
10460
10461 reclaim(&mut task, Some(state), 3, "en");
10462
10463 assert_eq!(task.status, TaskStatus::Held);
10464 assert_eq!(task.attempts, 2);
10465 assert!(task.sync_only.is_none());
10466 let detail = task.hold_reason.unwrap();
10467 assert!(detail.contains("HEAD already contains the base"));
10468 assert!(detail.contains("verification was not allowed"));
10469 }
10470
10471 #[test]
10472 fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
10473 let dir = tempfile::tempdir().unwrap();
10474 let queue = Queue::at(dir.path().to_path_buf());
10475
10476 let mut orphaned = task();
10478 orphaned.id = "20260904-000000-orph".to_owned();
10479 orphaned.status = TaskStatus::Running;
10480 orphaned.attempts = 1;
10481 queue.put(&mut orphaned).unwrap();
10482
10483 let mut alive = task();
10484 alive.id = "20260904-000000-live".to_owned();
10485 alive.status = TaskStatus::Running;
10486 alive.attempts = 1;
10487 queue.put(&mut alive).unwrap();
10488 let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
10489
10490 let mut queued = task();
10491 queued.id = "20260904-000000-wait".to_owned();
10492 queue.put(&mut queued).unwrap();
10493
10494 let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
10495 assert_eq!(reclaimed, vec![orphaned.id.clone()]);
10496
10497 assert_eq!(
10498 queue.get(&orphaned.id).unwrap().status,
10499 TaskStatus::Held,
10500 "nothing was driving it and there was no run to recover"
10501 );
10502 assert_eq!(
10503 queue.get(&alive.id).unwrap().status,
10504 TaskStatus::Running,
10505 "a live claim must protect the task it belongs to"
10506 );
10507 assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
10508 }
10509
10510 fn read_run_under(home: &Path, id: &str) -> RunState {
10516 let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
10517 serde_json::from_str(&body).unwrap()
10518 }
10519
10520 #[test]
10521 fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
10522 let dir = tempfile::tempdir().unwrap();
10523 let home = dir.path().to_path_buf();
10524 let now = Timestamp::now();
10525 let overrun_seat = || crate::run::ActiveSeat {
10526 node: "implement".to_owned(),
10527 started_at: now - jiff::SignedDuration::new(21_000, 0),
10528 timeout_secs: 3_600,
10529 attempt: 0,
10530 task: None,
10531 command: None,
10532 index: None,
10533 total: None,
10534 };
10535
10536 let mut dead = run_state(RunStatus::Implementing);
10537 dead.id = "20260101-000000-dead".to_owned();
10538 dead.active.insert("impl-A".to_owned(), overrun_seat());
10539 dead.driver_pid = Some(4242);
10542 dead.save_under(&home).unwrap();
10543
10544 let mut alive = run_state(RunStatus::Implementing);
10547 alive.id = "20260101-000000-aliv".to_owned();
10548 alive.active.insert("impl-A".to_owned(), overrun_seat());
10549 alive.save_under(&home).unwrap();
10550 let mut status = Status::new();
10551 status.current = vec![Current {
10552 worker: None,
10553 task: "20260101-000000-task".to_owned(),
10554 run: alive.id.clone(),
10555 }];
10556 write_status_to(&home.join("daemon.json"), &status).unwrap();
10557
10558 let questions = Questions::at(home.join("questions"));
10562 let mut q = ask::Question::new(
10563 dead.id.clone(),
10564 "implement".to_owned(),
10565 "impl-A".to_owned(),
10566 "Which storage backend?".to_owned(),
10567 String::new(),
10568 vec!["SQLite".to_owned(), "Redis".to_owned()],
10569 );
10570 questions.put(&mut q).unwrap();
10571
10572 let abandoned = reclaim_abandoned_runs_with(
10573 &home,
10574 now,
10575 |pid| if pid == 4242 { Some(false) } else { None },
10576 |_| panic!("a query answering Dead outright needs no identity corroboration"),
10577 );
10578 assert_eq!(abandoned, vec![dead.id.clone()]);
10579
10580 let reloaded = read_run_under(&home, &dead.id);
10581 assert_eq!(reloaded.status, RunStatus::Failed);
10582 assert!(reloaded.active.is_empty());
10583 assert!(
10584 !questions.get(&q.id).unwrap().status.open(),
10585 "the failed run's own open question must be settled in the same pass"
10586 );
10587
10588 let still_alive = read_run_under(&home, &alive.id);
10589 assert_eq!(
10590 still_alive.status,
10591 RunStatus::Implementing,
10592 "a live daemon's claim protects it"
10593 );
10594 assert!(!still_alive.active.is_empty());
10595 }
10596
10597 #[test]
10607 fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
10608 let dir = tempfile::tempdir().unwrap();
10609 let home = dir.path().to_path_buf();
10610 let now = Timestamp::now();
10611
10612 let mut manual = run_state(RunStatus::Reviewing);
10613 manual.id = "20260101-000000-manl".to_owned();
10614 manual.active.insert(
10615 "review-1".to_owned(),
10616 crate::run::ActiveSeat {
10617 node: "review".to_owned(),
10618 started_at: now - jiff::SignedDuration::new(21_000, 0),
10619 timeout_secs: 3_600,
10620 attempt: 0,
10621 task: None,
10622 command: None,
10623 index: None,
10624 total: None,
10625 },
10626 );
10627 manual.driver_pid = Some(4242);
10631 manual.driver_started_at = Some("1790000000".to_owned());
10632 manual.save_under(&home).unwrap();
10633
10634 let abandoned = reclaim_abandoned_runs_with(
10635 &home,
10636 now,
10637 |pid| if pid == 4242 { Some(true) } else { None },
10638 |pid| {
10639 if pid == 4242 {
10640 Some("1790000000".to_owned())
10641 } else {
10642 None
10643 }
10644 },
10645 );
10646 assert!(
10647 abandoned.is_empty(),
10648 "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
10649 );
10650
10651 let reloaded = read_run_under(&home, &manual.id);
10652 assert_eq!(reloaded.status, RunStatus::Reviewing);
10653 assert!(!reloaded.active.is_empty());
10654 }
10655
10656 #[test]
10657 fn an_already_claimed_task_is_skipped_rather_than_failed() {
10658 let dir = tempfile::tempdir().unwrap();
10659 let queue = Queue::at(dir.path().to_path_buf());
10660 let mut only = task();
10661 queue.put(&mut only).unwrap();
10662
10663 let _elsewhere = queue.claim(&only.id).unwrap();
10664 let candidates = runnable(&queue);
10665 assert_eq!(candidates.len(), 1, "the task is still runnable");
10666 assert!(
10667 queue.claim(&candidates[0].id).is_err(),
10668 "the loop cannot take a claim somebody else holds"
10669 );
10670
10671 let after = queue.get(&only.id).unwrap();
10672 assert_eq!(after.status, TaskStatus::Queued);
10673 assert_eq!(
10674 after.attempts, 0,
10675 "losing the race is not an attempt at the task"
10676 );
10677 assert_eq!(after.last_error, None);
10678 }
10679
10680 #[test]
10681 fn the_status_file_round_trips_and_its_heartbeat_advances() {
10682 let dir = tempfile::tempdir().unwrap();
10683 let path = dir.path().join("daemon.json");
10684
10685 let mut status = Status::new();
10686 status.idle = false;
10687 status.completed = 7;
10688 status.current = vec![Current {
10689 worker: None,
10690 task: "20260902-000000-t111".to_owned(),
10691 run: "20260902-000001-r111".to_owned(),
10692 }];
10693 write_status_to(&path, &status).unwrap();
10694 let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
10695 assert_eq!(first.schema, SCHEMA);
10696 assert_eq!(first.pid, std::process::id());
10697 assert!(!first.idle);
10698 assert_eq!(first.completed, 7);
10699 assert_eq!(first.current, status.current);
10700 assert!(
10701 !path.with_extension("json.tmp").exists(),
10702 "the temp file is renamed, not left behind"
10703 );
10704
10705 std::thread::sleep(Duration::from_millis(5));
10706 status.updated_at = Timestamp::now();
10707 status.polls = 3;
10708 write_status_to(&path, &status).unwrap();
10709 let second: Status =
10710 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
10711 assert!(
10712 second.updated_at > first.updated_at,
10713 "a reader can only detect staleness if the heartbeat moves"
10714 );
10715 assert_eq!(
10716 second.started_at, first.started_at,
10717 "the start time is not a heartbeat"
10718 );
10719 assert_eq!(second.polls, 3);
10720 }
10721
10722 #[test]
10723 fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
10724 let dir = tempfile::tempdir().unwrap();
10725
10726 assert!(read_status(dir.path()).is_none(), "no file, no daemon");
10727
10728 let mut status = Status::new();
10729 status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
10730 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10731 let stale = read_status(dir.path()).unwrap();
10732 assert!(
10733 !stale.running(Timestamp::now()),
10734 "a minute without a heartbeat is a dead daemon, not a busy one"
10735 );
10736 assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
10737
10738 status.updated_at = Timestamp::now();
10739 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10740 let fresh = read_status(dir.path()).unwrap();
10741 assert!(fresh.running(Timestamp::now()));
10742 }
10743
10744 #[test]
10745 fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
10746 let dir = tempfile::tempdir().unwrap();
10747 let now = Timestamp::now();
10748 let mine = "20260903-080619-01c2";
10749
10750 assert!(
10751 !is_working_on(dir.path(), mine, now),
10752 "no status file means nobody is working on anything"
10753 );
10754
10755 let mut status = Status::new();
10756 status.current = vec![Current {
10757 worker: None,
10758 task: "20260903-080340-0167".to_owned(),
10759 run: mine.to_owned(),
10760 }];
10761 status.updated_at = now;
10762 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10763 assert!(is_working_on(dir.path(), mine, now));
10764 assert!(
10765 !is_working_on(dir.path(), "20260903-105039-3cbf", now),
10766 "a daemon busy with one run is not working on another"
10767 );
10768
10769 status.updated_at = now - jiff::SignedDuration::from_secs(600);
10772 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10773 assert!(
10774 !is_working_on(dir.path(), mine, now),
10775 "a stale heartbeat is a dead daemon, so its run is a leftover"
10776 );
10777 }
10778
10779 #[test]
10780 fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
10781 let dir = tempfile::tempdir().unwrap();
10782 let now = Timestamp::now();
10783
10784 assert!(
10785 !is_working_on_short(dir.path(), "01c2", now),
10786 "no status file means nobody is working on anything"
10787 );
10788
10789 let mut status = Status::new();
10790 status.current = vec![Current {
10791 worker: None,
10792 task: "20260903-080340-0167".to_owned(),
10793 run: "20260903-080619-01c2".to_owned(),
10794 }];
10795 status.updated_at = now;
10796 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10797 assert!(
10798 is_working_on_short(dir.path(), "01c2", now),
10799 "the run's short id is the last block of its full id"
10800 );
10801 assert!(
10802 !is_working_on_short(dir.path(), "3cbf", now),
10803 "a daemon busy with one worktree bay is not working on another"
10804 );
10805 }
10806
10807 #[test]
10808 fn a_newer_status_file_still_yields_a_reading() {
10809 let dir = tempfile::tempdir().unwrap();
10810 std::fs::write(
10813 dir.path().join("daemon.json"),
10814 serde_json::json!({
10815 "schema": 2,
10816 "updated_at": Timestamp::now().to_string(),
10817 "idle": true,
10818 "surprise": { "nested": [1, 2, 3] },
10819 })
10820 .to_string(),
10821 )
10822 .unwrap();
10823
10824 let reading = read_status(dir.path()).expect("a forward-compatible read");
10825 assert!(reading.running(Timestamp::now()));
10826 assert!(reading.idle);
10827 assert!(reading.current.is_empty());
10828 }
10829
10830 #[test]
10831 fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
10832 let dir = tempfile::tempdir().unwrap();
10838 std::fs::write(
10839 dir.path().join("daemon.json"),
10840 serde_json::json!({
10841 "schema": 1,
10842 "pid": 4242,
10843 "updated_at": Timestamp::now().to_string(),
10844 "idle": false,
10845 "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
10846 "completed": 3,
10847 "polls": 9,
10848 })
10849 .to_string(),
10850 )
10851 .unwrap();
10852
10853 let reading = read_status(dir.path()).expect("an older shape must still parse");
10854 assert!(reading.running(Timestamp::now()));
10855 assert_eq!(
10856 reading.current,
10857 vec![Current {
10858 worker: None,
10859 task: "20260902-140501-aaaa".to_owned(),
10860 run: "20260902-140502-bbbb".to_owned(),
10861 }]
10862 );
10863 }
10864
10865 #[test]
10866 fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
10867 let dir = tempfile::tempdir().unwrap();
10868 std::fs::write(
10869 dir.path().join("daemon.json"),
10870 serde_json::json!({
10871 "schema": 1,
10872 "updated_at": Timestamp::now().to_string(),
10873 "idle": true,
10874 "current": null,
10875 })
10876 .to_string(),
10877 )
10878 .unwrap();
10879 let with_null = read_status(dir.path()).expect("null must still parse");
10880 assert!(with_null.current.is_empty());
10881
10882 std::fs::write(
10883 dir.path().join("daemon.json"),
10884 serde_json::json!({
10885 "schema": 1,
10886 "updated_at": Timestamp::now().to_string(),
10887 "idle": true,
10888 })
10889 .to_string(),
10890 )
10891 .unwrap();
10892 let absent = read_status(dir.path()).expect("a missing field must still parse");
10893 assert!(absent.current.is_empty());
10894 }
10895
10896 #[test]
10897 fn a_task_without_a_repository_runs_in_the_daemons_default() {
10898 let fallback = Path::new("/default");
10899 let mut blank = task();
10900 blank.repo = PathBuf::new();
10901 assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
10902 let mut dot = task();
10903 dot.repo = PathBuf::from(".");
10904 assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
10905 assert_eq!(
10906 repo_for(&task(), fallback),
10907 PathBuf::from("/repo"),
10908 "a task that names a repository keeps it"
10909 );
10910 }
10911
10912 #[test]
10913 fn new_tasks_inherit_the_daemon_build_cache_but_historical_tasks_remain_shared() {
10914 let dir = tempfile::tempdir().unwrap();
10915 let repo = dir.path();
10916 let path = repo.join("explicit.toml");
10917 std::fs::write(
10918 &path,
10919 "[verify]\nbuild_cache = 'isolated'\n[graph]\njudges = 1\n",
10920 )
10921 .unwrap();
10922 let opts = Opts {
10923 config: Some(path),
10924 ..Opts::default()
10925 };
10926 let queue = Queue::at(repo.join("queue"));
10927 let mut new = task();
10928 queue.put(&mut new).unwrap();
10929 let resolved = |task: &Task| prepare_for(repo, &opts, task).unwrap();
10930 assert_eq!(
10931 resolved(&queue.get(&new.id).unwrap()).verify.build_cache,
10932 BuildCache::Isolated
10933 );
10934
10935 let mut old = task();
10936 old.schema = 22;
10937 queue.put(&mut old).unwrap();
10938 let mut old = queue.get(&old.id).unwrap();
10939 let config = resolved(&old);
10940 assert_eq!(config.verify.build_cache, BuildCache::Shared);
10941 assert_eq!(config.graph.judges, 1, "preserve daemon config inheritance");
10942 old.hold_manual(Some("wait".into()));
10943 queue.put(&mut old).unwrap();
10944
10945 let mut saved = queue.get(&old.id).unwrap();
10946 assert_eq!(resolved(&saved).verify.build_cache, BuildCache::Shared);
10947 saved
10948 .overrides
10949 .as_mut()
10950 .unwrap()
10951 .merge_over(&crate::queue::RunOverrides {
10952 build_cache: Some(BuildCache::Isolated),
10953 ..Default::default()
10954 });
10955 queue.put(&mut saved).unwrap();
10956 assert_eq!(
10957 resolved(&queue.get(&saved.id).unwrap()).verify.build_cache,
10958 BuildCache::Isolated
10959 );
10960 }
10961
10962 #[test]
10963 fn urgent_build_cache_precedes_config_but_not_an_explicit_choice() {
10964 let dir = tempfile::tempdir().unwrap();
10965 let path = dir.path().join("explicit.toml");
10966 let write = |verify: &str| {
10967 std::fs::write(&path, format!("[verify]\nbuild_cache = 'shared'\n{verify}")).unwrap();
10968 };
10969 write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test\"]\n");
10970 let opts = Opts {
10971 config: Some(path.clone()),
10972 ..Opts::default()
10973 };
10974 let mut task = task();
10975 task.set_urgent(true).unwrap();
10976 let resolved = |task: &Task| {
10977 prepare_for(dir.path(), &opts, task)
10978 .unwrap()
10979 .verify
10980 .build_cache
10981 };
10982 assert_eq!(resolved(&task), BuildCache::Isolated);
10983 task.change_build_cache(Some(BuildCache::Shared)).unwrap();
10984 assert_eq!(resolved(&task), BuildCache::Shared);
10985 task.change_build_cache(None).unwrap();
10986 assert_eq!(resolved(&task), BuildCache::Isolated);
10987 task.set_urgent(false).unwrap();
10988 assert_eq!(resolved(&task), BuildCache::Shared);
10989
10990 task.set_urgent(true).unwrap();
10994 write("e2e = [\"npm test\"]\n");
10995 assert_eq!(resolved(&task), BuildCache::Shared);
10996 write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test | tee log\"]\n");
10997 assert_eq!(resolved(&task), BuildCache::Shared);
10998 task.change_build_cache(Some(BuildCache::Isolated)).unwrap();
11000 assert_eq!(resolved(&task), BuildCache::Isolated);
11001 }
11002
11003 #[test]
11004 fn task_implementers_edit_inherits_daemon_config_and_merge() {
11005 let dir = tempfile::tempdir().unwrap();
11006 let path = dir.path().join("explicit.toml");
11007 std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
11008 let opts = Opts {
11009 config: Some(path),
11010 merge: Some("none".into()),
11011 ..Default::default()
11012 };
11013 let mut t = task();
11014 t.set_implementers(
11015 2,
11016 &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
11017 .unwrap(),
11018 )
11019 .unwrap();
11020 let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
11021 assert_eq!(cfg.graph.implementers, 2);
11022 assert_eq!(cfg.graph.judges, 1);
11023 assert_eq!(cfg.merge.mode, MergeMode::None);
11024 t.set_implementers(1, &cfg).unwrap();
11025 let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
11026 apply_task_implementers(&mut cfg, &t);
11027 assert_eq!(cfg.graph.implementers, 1);
11028 assert_eq!(cfg.graph.judges, 1);
11029 assert_eq!(cfg.merge.mode, MergeMode::None);
11030 }
11031
11032 #[test]
11033 fn task_implementers_direct_overrides_stay_isolated_after_edits() {
11034 let dir = tempfile::tempdir().unwrap();
11035 let repo = dir.path().join("repo");
11036 std::fs::create_dir(&repo).unwrap();
11037 std::fs::write(
11038 repo.join("magi.toml"),
11039 "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
11040 )
11041 .unwrap();
11042 let daemon_config = dir.path().join("daemon.toml");
11043 std::fs::write(
11044 &daemon_config,
11045 "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
11046 )
11047 .unwrap();
11048 let opts = Opts {
11049 config: Some(daemon_config),
11050 merge: Some("pr".into()),
11051 ..Default::default()
11052 };
11053 let q = Queue::at(dir.path().join("queue"));
11054 let validation: Config =
11055 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
11056 .unwrap();
11057 for record in ["{}", r#"{"candidates":2}"#] {
11059 let overrides = serde_json::from_str(record).unwrap();
11060 let filing = crate::direct::Filing {
11061 instruction: "work".into(),
11062 title: "direct".into(),
11063 repo: repo.clone(),
11064 source: crate::queue::Source::Human,
11065 solo: false,
11066 overrides,
11067 review_of: None,
11068 sources: Default::default(),
11069 };
11070 let filed =
11071 crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
11072 let crate::direct::Filed::Standalone {
11073 mut task,
11074 claim: _claim,
11075 } = filed
11076 else {
11077 panic!("local filing")
11078 };
11079 let before = prepare_for(&repo, &opts, &task).unwrap();
11080 assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
11081 assert_eq!(
11082 before.merge.mode,
11083 MergeMode::None,
11084 "daemon --merge must not leak"
11085 );
11086 for n in [2, 1, 2] {
11087 task.set_implementers(n, &validation).unwrap();
11088 q.put(&mut task).unwrap();
11089 task = q.get(&task.id).unwrap();
11090 assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
11091 let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
11092 apply_task_implementers(&mut cfg, &task);
11093 assert_eq!(cfg.graph.implementers, usize::from(n));
11094 assert_eq!(cfg.graph.judges, 2);
11095 assert_eq!(cfg.merge.mode, MergeMode::None);
11096 }
11097 }
11098 }
11099
11100 #[test]
11101 fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
11102 let cfg: Config =
11103 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
11104 .unwrap();
11105 let mut t = task();
11106 t.review_of = Some("review-target".into());
11107 t.hold_manual(Some("retry".into()));
11108 let mut previous = RunState::new(
11109 PathBuf::from("/repo"),
11110 "main".into(),
11111 "abc1234".into(),
11112 "review".into(),
11113 cfg.clone(),
11114 );
11115 previous.config.graph.implementers = 2;
11116 for count in [1, 3] {
11117 t.set_implementers(count, &cfg).unwrap();
11118 t.release();
11119 assert_eq!(t.review_of.as_deref(), Some("review-target"));
11120 for proposed in [
11121 Starter::Resume(previous.id.clone()),
11122 Starter::Review("recovery-target".into()),
11123 ] {
11124 assert_eq!(
11125 starter_with_implementers(&t, Some(&previous), proposed),
11126 Starter::Review("review-target".into())
11127 );
11128 }
11129 let mut configured = cfg.clone();
11130 apply_task_implementers(&mut configured, &t);
11131 assert_eq!(configured.graph.implementers, usize::from(count));
11132 assert_eq!(previous.config.graph.implementers, 2);
11133 }
11134 }
11135
11136 #[test]
11137 fn task_implementers_dispatch_and_resume_agree() {
11138 let mut t = task();
11139 let cfg: crate::config::Config =
11140 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
11141 .unwrap();
11142 let mut run = RunState::new(
11143 PathBuf::from("/repo"),
11144 "main".into(),
11145 "abc1234".into(),
11146 "work".into(),
11147 cfg.clone(),
11148 );
11149 run.config.graph.implementers = 2;
11150 for n in [2, 1, 3, 2] {
11151 t.set_implementers(n, &cfg).unwrap();
11152 let mut dispatched = cfg.clone();
11153 apply_task_implementers(&mut dispatched, &t);
11154 assert_eq!(dispatched.graph.implementers, usize::from(n));
11155 assert_eq!(implementers_match(&t, &run), n == 2);
11156 for proposed in [
11157 Starter::Resume(run.id.clone()),
11158 Starter::Review("old-branch".into()),
11159 ] {
11160 let expected = if n == 2 {
11161 proposed.clone()
11162 } else {
11163 Starter::Start
11164 };
11165 assert_eq!(
11166 starter_with_implementers(&t, Some(&run), proposed),
11167 expected
11168 );
11169 }
11170 assert_eq!(
11171 run.config.graph.implementers, 2,
11172 "history must not be rewritten"
11173 );
11174 }
11175 t.solo = false;
11176 t.overrides = None;
11177 assert!(implementers_match(&t, &run));
11178 }
11179
11180 #[test]
11181 fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
11182 let mut solo_cfg = Config::default();
11188 solo_cfg.graph.implementers = 3;
11189 let mut solo_task = task();
11190 solo_task.solo = true;
11191 apply_task_implementers(&mut solo_cfg, &solo_task);
11192 assert_eq!(solo_cfg.graph.implementers, 1);
11193
11194 let mut plain_cfg = Config::default();
11195 plain_cfg.graph.implementers = 3;
11196 let plain_task = task();
11197 assert!(!plain_task.solo);
11198 apply_task_implementers(&mut plain_cfg, &plain_task);
11199 assert_eq!(
11200 plain_cfg.graph.implementers, 3,
11201 "a task that did not ask to run alone keeps the config's candidates"
11202 );
11203 }
11204
11205 fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
11206 QuotaLoss {
11207 cause: crate::agent::QuotaCause::UsageLimit,
11208 agent: String::new(),
11209 seat: seat.into(),
11210 node: "judge".into(),
11211 at: at.parse().unwrap(),
11212 reset: reset.map(str::to_string),
11213 }
11214 }
11215
11216 #[test]
11217 fn authentication_losses_never_arm_a_cooldown_even_with_reset_hints() {
11218 let now = Timestamp::now();
11219 for reset in [None, Some("in 1h")] {
11220 let auth = crate::agent::Quota {
11221 cause: crate::agent::QuotaCause::Authentication,
11222 agent: "alpha".into(),
11223 reset: reset.map(str::to_owned),
11224 };
11225 let loss = QuotaLoss::from_report("advisor-1".into(), "advise", Some(&auth));
11226 assert_eq!(cooldown_until(&[loss], now), None);
11227 }
11228 }
11229
11230 #[test]
11231 fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
11232 let old: Vec<QuotaLoss> = (1..=4)
11233 .map(|i| {
11234 loss(
11235 &format!("judge-{i}"),
11236 "2026-09-23T05:23:00Z",
11237 Some("2:40pm (Asia/Tokyo)"),
11238 )
11239 })
11240 .collect();
11241 let fresh = losses_this_attempt(&old, &old);
11242 assert!(fresh.is_empty());
11243 assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
11244 }
11246
11247 #[test]
11248 fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
11249 let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
11250 let now = Timestamp::now();
11251 let mut after = old.clone();
11252 after.push(loss("judge-2", &now.to_string(), None));
11253 let fresh = losses_this_attempt(&old, &after);
11254 assert_eq!(fresh, vec![after[1].clone()]);
11255 let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
11256 assert_eq!(
11257 until,
11258 now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
11259 );
11260 }
11261
11262 #[test]
11263 fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
11264 let before = vec![
11267 loss("judge-1", "2026-09-23T05:23:00Z", None),
11268 loss("judge-2", "2026-09-23T05:24:00Z", None),
11269 ];
11270 let after = vec![
11271 loss("judge-2", "2026-09-23T05:24:00Z", None),
11272 loss("judge-1", "2026-09-24T01:00:00Z", None),
11273 ];
11274 assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
11275 }
11276
11277 #[test]
11278 fn merge_overrides_are_parsed_or_refused() {
11279 assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
11280 assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
11281 assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
11282 assert!(merge_mode("squash").is_err());
11283 }
11284
11285 #[test]
11286 fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
11287 let now = Timestamp::now();
11288 let fallback = Duration::from_secs(300);
11289 let cap = Duration::from_secs(1800);
11290
11291 assert_eq!(quota_wait(None, now, fallback, cap), fallback);
11293
11294 let soon = now + jiff::SignedDuration::from_secs(600);
11296 assert_eq!(
11297 quota_wait(Some(soon), now, fallback, cap),
11298 Duration::from_secs(600)
11299 );
11300
11301 let past = now - jiff::SignedDuration::from_secs(60);
11304 assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
11305
11306 let far = now + jiff::SignedDuration::from_secs(3 * 3600);
11309 assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
11310 }
11311
11312 #[test]
11313 fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
11314 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
11315
11316 let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
11317 assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
11318
11319 let already_past =
11323 parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
11324 assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
11325
11326 assert!(
11327 parse_reset_hint("session limit reached", now, now).is_none(),
11328 "free text with no recognised shape is not guessed at"
11329 );
11330 assert!(
11331 parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
11332 "an unresolvable zone name is not guessed at either"
11333 );
11334 }
11335
11336 #[test]
11337 fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
11338 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
11339
11340 let at = parse_reset_hint(
11341 "You've hit your usage limit. Visit \
11342 https://chatgpt.com/codex/settings/usage to purchase more \
11343 credits or try again at Sep 19th, 2026 5:10 PM.",
11344 now,
11345 now,
11346 )
11347 .expect("the codex reset wording is a recognised shape");
11348 assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
11349
11350 let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
11355 .expect("an explicit year needs no rollover");
11356 assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
11357
11358 assert!(
11359 parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
11360 "a two-digit year is not the documented shape and is not guessed at"
11361 );
11362 assert!(
11363 parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
11364 "a four-letter month name is not the documented three-letter abbreviation"
11365 );
11366 assert!(
11367 parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
11368 "an explicit zone on the dated shape is a format nobody has \
11369 documented, and is refused rather than guessed at as UTC"
11370 );
11371 }
11372
11373 #[test]
11374 fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
11375 let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
11376 let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
11377
11378 let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
11379 assert_eq!(at.as_second() - recorded.as_second(), 3769);
11380
11381 let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
11382 assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
11383
11384 for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
11385 assert!(
11386 parse_reset_hint(bad, now, recorded).is_none(),
11387 "{bad:?} must not be guessed at"
11388 );
11389 }
11390 }
11391
11392 fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
11396 let config = dir.join("magi.toml");
11397 std::fs::write(
11398 &config,
11399 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
11400 )
11401 .unwrap();
11402 let opts = Opts {
11403 poll: Duration::from_secs(30),
11404 config: Some(config),
11405 repo: dir.join("repo"),
11409 ..Opts::default()
11410 };
11411 let home = dir.join("home");
11420 let stamps = home.join("service-ticks");
11423 std::fs::create_dir_all(&stamps).unwrap();
11424 for service in ["waiter", "deputies", "release-watch"] {
11425 std::fs::write(
11426 stamps.join(service),
11427 Timestamp::now().as_second().to_string(),
11428 )
11429 .unwrap();
11430 }
11431 for operation in [
11432 "conductor",
11433 "maintenance",
11434 "housekeeping",
11435 "disk-pressure",
11436 "cache",
11437 "fetch",
11438 "chat-goals",
11439 ] {
11440 std::fs::write(
11441 stamps.join(format!("daemon-{operation}")),
11442 serde_json::to_vec(&Timestamp::now()).unwrap(),
11443 )
11444 .unwrap();
11445 }
11446 let worktrees = dir.join("wt");
11447 (
11448 opts,
11449 Queue::at(dir.join("queue")),
11450 home.join("daemon.json"),
11451 home,
11452 worktrees,
11453 )
11454 }
11455
11456 #[tokio::test]
11457 async fn disk_wait_maintenance_recovers_while_another_task_is_running() {
11458 let dir = tempfile::tempdir().unwrap();
11459 let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
11460 let mut waiting = task();
11461 waiting.repo = opts.repo.clone();
11462 waiting.hold_machine(crate::disk::gate(1, 100));
11463 waiting.mark_disk_capacity();
11464 waiting.attempts = 2;
11465 queue.put(&mut waiting).unwrap();
11466 let mut busy = task();
11467 busy.status = TaskStatus::Running;
11468 queue.put(&mut busy).unwrap();
11469 let payload = serde_json::to_value(ServiceWorker {
11470 opts,
11471 queue: queue.root().to_owned(),
11472 worktrees_root: worktrees,
11473 operation: "maintenance".into(),
11474 })
11475 .unwrap();
11476 run_service_worker(&home, payload.clone()).await.unwrap();
11477 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Queued);
11478 assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
11479 assert_eq!(queue.get(&busy.id).unwrap().status, TaskStatus::Running);
11480 run_service_worker(&home, payload).await.unwrap();
11481 assert!(
11482 crate::worker::active(&home).unwrap().is_empty(),
11483 "monitoring only queues; normal dispatch owns launches"
11484 );
11485 assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
11486 }
11487
11488 #[tokio::test]
11489 async fn source_eviction_service_receipts_explain_idle_and_active_skips() {
11490 let dir = tempfile::tempdir().unwrap();
11491 let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
11492 let cfg = Config::default();
11493 start_service(
11494 &home,
11495 &opts,
11496 &queue,
11497 &worktrees,
11498 "housekeeping",
11499 Some(&cfg),
11500 true,
11501 )
11502 .await
11503 .unwrap();
11504 let receipt = home.join("source-eviction-housekeeping-dispatch.json");
11505 let read = |path: &Path| -> serde_json::Value {
11506 serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap()
11507 };
11508 assert_eq!(read(&receipt)["detail"], "cadence not due");
11509 std::fs::remove_file(home.join("service-ticks/daemon-housekeeping")).unwrap();
11510 start_service(
11511 &home,
11512 &opts,
11513 &queue,
11514 &worktrees,
11515 "housekeeping",
11516 Some(&cfg),
11517 true,
11518 )
11519 .await
11520 .unwrap();
11521 assert_eq!(
11522 read(&receipt)["detail"],
11523 "active work or runnable task queue"
11524 );
11525 assert_eq!(read(&receipt)["version"], env!("CARGO_PKG_VERSION"));
11526 assert_eq!(read(&receipt)["auto_fold"], cfg.disk.auto_fold);
11527 std::fs::remove_file(home.join("service-ticks/daemon-disk-pressure")).unwrap();
11528 start_service(
11529 &home,
11530 &opts,
11531 &queue,
11532 &worktrees,
11533 "disk-pressure",
11534 Some(&cfg),
11535 false,
11536 )
11537 .await
11538 .unwrap();
11539 assert_eq!(
11540 read(&home.join("source-eviction-disk-pressure-dispatch.json"))["detail"],
11541 "no active work; idle housekeeping owns scan"
11542 );
11543 assert!(crate::worker::active(&home).unwrap().is_empty());
11544 }
11545
11546 #[tokio::test]
11547 async fn goal_observation_service_does_not_block_scheduler_decisions() {
11548 let dir = tempfile::tempdir().unwrap();
11549 let (opts, _, _, home, worktrees) = idle_loop(dir.path());
11550 let queue = Queue::at(home.join("queue"));
11551 let mut task = task();
11552 task.repo = opts.repo.clone();
11553 task.chat = Some("decision-chat".into());
11554 task.hold_machine(Some("waiting for a decision".into()));
11555 queue.put(&mut task).unwrap();
11556 let questions = Questions::at(home.join("questions"));
11557 let mut question = action_question(&task.id, ask::ChoiceAction::Done);
11558 question.node = crate::conduct::NODE.into();
11559 question.status = ask::QuestionStatus::Open;
11560 question.answer = None;
11561 question.answered_at = None;
11562 questions.put(&mut question).unwrap();
11563 questions
11564 .update(&question.id, |q| {
11565 q.answer(ask::Answer::Choice("resume で続行する".into()))
11566 })
11567 .unwrap();
11568
11569 let talks = crate::talk::Talks::at(home.join("talks"));
11570 let mut decision_chat = crate::talk::seeded_for_test("decision-chat", opts.repo.clone());
11571 decision_chat.pending = "Keep this unsent status question".into();
11572 talks.put(&mut decision_chat).unwrap();
11573 let mut talk = crate::talk::seeded_for_test("observing-chat", opts.repo.clone());
11574 talk.goals.push(serde_json::from_value(serde_json::json!({
11575 "id":"goal","purpose":"follow the retained job","scope":"one task",
11576 "condition":{"description":"land the result","kind":"runs_merged"},
11577 "state":"runnable","step":"reading the forge","source_turn":0,"owner_input":"land this job",
11578 "tasks":[],"runs":[],"watches":[],"evidence":"","wake":1,"handled":0,
11579 "started":1,"wakes":1,"last_checked":null,"fingerprint":""
11580 })).unwrap());
11581 talks.put(&mut talk).unwrap();
11582
11583 let directory = home.join("workers/jobs/abcdef");
11586 std::fs::create_dir_all(&directory).unwrap();
11587 let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
11588 crate::pr_head::try_lock_file(&lease).unwrap();
11589 let mut job = crate::worker::Job {
11590 id: "abcdef".into(),
11591 sequence: 1,
11592 kind: "daemon-service".into(),
11593 key: "service:daemon-chat-goals".into(),
11594 payload: serde_json::Value::Null,
11595 generation: "fixture".into(),
11596 version: None,
11597 status: crate::worker::Status::Running,
11598 result: None,
11599 pid: Some(std::process::id()),
11600 created_at: Timestamp::now().as_second() as u64,
11601 finished_at: None,
11602 };
11603 let record = directory.join("job.json");
11604 std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11605 let status = Arc::new(Mutex::new(Status::new()));
11606 let stop = Stop::new();
11607 let mut dispatch = Box::pin(poll(
11608 &opts,
11609 &queue,
11610 &status,
11611 &home,
11612 &worktrees,
11613 &stop,
11614 DispatchLimits {
11615 max_concurrent: 1,
11616 pause_for_interrupts: false,
11617 recovery_cfg: None,
11618 },
11619 ));
11620 std::future::poll_fn(|cx| {
11621 assert!(dispatch.as_mut().poll(cx).is_pending());
11622 std::task::Poll::Ready(())
11623 })
11624 .await;
11625 assert!(lock(&status).polls > 0);
11626 let saved = queue.get(&task.id).unwrap();
11627 assert_eq!(saved.status, TaskStatus::Done);
11628 assert!(saved.action_applied(&question.id));
11629 assert!(
11630 talks
11631 .get("decision-chat")
11632 .unwrap()
11633 .pending
11634 .contains("Keep this unsent status question")
11635 );
11636 let goal = talks.get(&talk.id).unwrap().goals.remove(0);
11637 assert_eq!(goal.state, crate::chat_goal::State::Runnable);
11638 assert_eq!(
11639 goal.started,
11640 Some(1),
11641 "only the observation worker may reconcile its goal"
11642 );
11643 assert_eq!(crate::worker::active(&home).unwrap()[0].id, job.id);
11644
11645 stop.stop();
11646 dispatch.await.unwrap();
11647 job.status = crate::worker::Status::Finished;
11648 std::fs::write(record, serde_json::to_vec(&job).unwrap()).unwrap();
11649 drop(lease);
11650 }
11651
11652 #[test]
11653 fn a_stop_is_idempotent_and_once_set_stays_set() {
11654 let stop = Stop::new();
11655 assert!(!stop.stopped());
11656
11657 stop.stop();
11658 assert!(stop.stopped());
11659 stop.stop();
11660 assert!(stop.stopped(), "a second stop is not a toggle");
11661
11662 let shared = stop.clone();
11663 assert!(
11664 shared.stopped(),
11665 "a clone is the same stop; that is how the loop and its caller share one"
11666 );
11667 }
11668
11669 #[tokio::test]
11670 async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
11671 for operation in ["conductor", "maintenance", "housekeeping"] {
11672 let dir = tempfile::tempdir().unwrap();
11673 let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
11674 opts.once = true;
11675 opts.poll = Duration::from_millis(1);
11676 let mut state = run_state(RunStatus::Ready);
11679 state.reserve_under(&home).unwrap();
11680 state.save_under(&home).unwrap();
11681 let mut task = task();
11682 task.runs.push(state.id.clone());
11683 queue.put(&mut task).unwrap();
11684 let claim = queue.claim(&task.id).unwrap();
11685
11686 let directory = home.join("workers/jobs/abcdef");
11689 std::fs::create_dir_all(&directory).unwrap();
11690 let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
11691 crate::pr_head::try_lock_file(&lease).unwrap();
11692 let mut job = crate::worker::Job {
11693 id: "abcdef".into(),
11694 sequence: 1,
11695 kind: "daemon-service".into(),
11696 key: format!("service:daemon-{operation}"),
11697 payload: serde_json::Value::Null,
11698 generation: "fixture".into(),
11699 version: None,
11700 status: crate::worker::Status::Running,
11701 result: None,
11702 pid: Some(std::process::id()),
11703 created_at: Timestamp::now().as_second() as u64,
11704 finished_at: None,
11705 };
11706 let record = directory.join("job.json");
11707 std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11708
11709 let status = Arc::new(Mutex::new(Status::new()));
11710 let stop = Stop::new();
11711 let mut drain = Box::pin(poll(
11712 &opts,
11713 &queue,
11714 &status,
11715 &home,
11716 &worktrees,
11717 &stop,
11718 DispatchLimits {
11719 max_concurrent: 1,
11720 pause_for_interrupts: false,
11721 recovery_cfg: None,
11722 },
11723 ));
11724 std::future::poll_fn(|cx| {
11725 use std::future::Future;
11726 assert!(
11727 drain.as_mut().poll(cx).is_pending(),
11728 "--once must wait for {operation} to release its queue claim"
11729 );
11730 std::task::Poll::Ready(())
11731 })
11732 .await;
11733 assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
11734
11735 let questions = Questions::at(home.join("questions"));
11738 let mut q = action_question(&state.id, ask::ChoiceAction::Done);
11739 questions.put(&mut q).unwrap();
11740 drop(claim);
11741 let expired =
11745 serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
11746 for service in [operation, "housekeeping"] {
11747 std::fs::write(
11748 home.join("service-ticks").join(format!("daemon-{service}")),
11749 &expired,
11750 )
11751 .unwrap();
11752 }
11753 job.status = crate::worker::Status::Finished;
11754 std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11755 drop(lease);
11756 tokio::time::timeout(Duration::from_secs(2), drain)
11757 .await
11758 .expect("the settled service must allow the drain to finish")
11759 .unwrap();
11760 let after = queue.get(&task.id).unwrap();
11761 assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
11762 assert!(after.action_applied(&q.id));
11763 for service in [operation, "housekeeping"] {
11764 assert_eq!(
11765 std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
11766 .unwrap(),
11767 expired,
11768 "the final once rescan must not restart {service}"
11769 );
11770 }
11771 }
11772 }
11773
11774 #[test]
11775 fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
11776 let stop = Stop::new();
11777 stop.busy.store(1, Ordering::SeqCst);
11778 assert!(
11779 !stop.finishing(),
11780 "a busy loop nobody has asked to stop is just running"
11781 );
11782
11783 stop.stop();
11784 assert!(
11785 stop.finishing(),
11786 "a stop asked for mid-run has not landed until the run is settled"
11787 );
11788
11789 stop.busy.store(0, Ordering::SeqCst);
11790 assert!(
11791 !stop.finishing(),
11792 "once the run is settled the stop has landed and there is nothing to finish"
11793 );
11794 }
11795
11796 #[test]
11797 fn finishing_stays_true_until_the_last_of_several_runs_exits() {
11798 let stop = Stop::new();
11799 stop.busy.store(2, Ordering::SeqCst);
11800 stop.stop();
11801 assert!(stop.finishing(), "two runs still in flight");
11802
11803 stop.busy.store(1, Ordering::SeqCst);
11804 assert!(
11805 stop.finishing(),
11806 "one run finished, but a sibling is still working"
11807 );
11808
11809 stop.busy.store(0, Ordering::SeqCst);
11810 assert!(
11811 !stop.finishing(),
11812 "the last run out is what actually lands the stop"
11813 );
11814 }
11815
11816 #[tokio::test]
11817 async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
11818 let dir = tempfile::tempdir().unwrap();
11819 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
11820 let stop = Stop::new();
11821 stop.stop();
11822
11823 let began = std::time::Instant::now();
11824 tokio::time::timeout(
11825 Duration::from_secs(2),
11826 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
11827 )
11828 .await
11829 .expect("a stopped loop must return, not sit out its poll interval")
11830 .expect("the loop's own setup and teardown must not fail");
11831 assert!(
11832 began.elapsed() < opts.poll,
11833 "returned only after {:?}, which is a poll interval, not a stop",
11834 began.elapsed()
11835 );
11836 }
11837
11838 #[tokio::test]
11839 async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
11840 let dir = tempfile::tempdir().unwrap();
11841 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
11842 let stop = Stop::new();
11843
11844 let asker = {
11847 let stop = stop.clone();
11848 tokio::spawn(async move {
11849 tokio::time::sleep(Duration::from_millis(20)).await;
11850 stop.stop();
11851 })
11852 };
11853
11854 let began = std::time::Instant::now();
11855 tokio::time::timeout(
11856 Duration::from_secs(2),
11857 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
11858 )
11859 .await
11860 .expect("a stop asked for while idle must wake the wait")
11861 .expect("the loop's own setup and teardown must not fail");
11862 asker.await.unwrap();
11863 assert!(
11864 began.elapsed() < opts.poll,
11865 "returned only after {:?}, so the stop waited on the sleep",
11866 began.elapsed()
11867 );
11868 }
11869
11870 #[tokio::test]
11871 async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
11872 let dir = tempfile::tempdir().unwrap();
11873 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
11874 let stop = Stop::new();
11875 stop.stop();
11876
11877 tokio::time::timeout(
11878 Duration::from_secs(2),
11879 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
11880 )
11881 .await
11882 .expect("a stopped loop must return")
11883 .expect("the loop's own setup and teardown must not fail");
11884
11885 assert!(
11886 home.is_dir(),
11887 "the loop did publish a status file, so its removal is the teardown and not an absence"
11888 );
11889 assert!(
11890 !status_file.exists(),
11891 "a stopped loop clears its status file"
11892 );
11893 assert!(
11894 read_status(&home).is_none(),
11895 "a reader must see no daemon at all, not a heartbeat that merely stopped"
11896 );
11897 }
11898
11899 #[tokio::test]
11900 async fn housekeeping_worker_settles_questions_without_a_scheduler() {
11901 let dir = tempfile::tempdir().unwrap();
11902 let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
11903
11904 let mut settled = RunState::new(
11905 dir.path().join("repo"),
11906 "main".to_owned(),
11907 "abc1234".to_owned(),
11908 "fixture".to_owned(),
11909 Config::default(),
11910 );
11911 settled.status = RunStatus::Ready;
11912 let run_dir = home.join("runs").join(&settled.id);
11913 std::fs::create_dir_all(&run_dir).unwrap();
11914 std::fs::write(
11915 run_dir.join("run.json"),
11916 serde_json::to_string_pretty(&settled).unwrap(),
11917 )
11918 .unwrap();
11919 let questions = Questions::at(home.join("questions"));
11920 let mut question = ask::Question::new(
11921 settled.id.clone(),
11922 "review".to_owned(),
11923 "reviewer-1".to_owned(),
11924 "Continue?".to_owned(),
11925 String::new(),
11926 Vec::new(),
11927 );
11928 questions.put(&mut question).unwrap();
11929
11930 run_service_worker(
11931 &home,
11932 serde_json::to_value(ServiceWorker {
11933 opts,
11934 queue: queue.root().to_path_buf(),
11935 worktrees_root: worktrees,
11936 operation: "housekeeping".to_owned(),
11937 })
11938 .unwrap(),
11939 )
11940 .await
11941 .unwrap();
11942
11943 assert_eq!(
11944 questions.get(&question.id).unwrap().status,
11945 ask::QuestionStatus::Abandoned,
11946 "the independent housekeeping worker settles ended-run questions"
11947 );
11948 }
11949
11950 #[test]
11951 fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
11952 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
11953
11954 assert!(
11955 cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
11956 "never checked before: due at once"
11957 );
11958
11959 let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
11960 assert!(
11961 !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
11962 "well inside the interval: not due yet"
11963 );
11964
11965 let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
11966 assert!(
11967 !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
11968 "exactly at the edge: not yet due, same convention as `clean::due`"
11969 );
11970
11971 let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
11972 assert!(
11973 cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
11974 "past the interval: due again"
11975 );
11976 }
11977
11978 fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
11983 let config = dir.join("magi.toml");
11984 std::fs::write(
11990 &config,
11991 format!(
11992 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
11993 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
11994 cache_dir.display()
11995 ),
11996 )
11997 .unwrap();
11998 Opts {
11999 config: Some(config),
12000 repo: dir.join("repo"),
12001 ..Opts::default()
12002 }
12003 }
12004
12005 #[tokio::test]
12006 async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
12007 let dir = tempfile::tempdir().unwrap();
12008 let home = dir.path().join("home");
12009 let cache_dir = dir.path().join("cache");
12010 std::fs::create_dir_all(&cache_dir).unwrap();
12011 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
12012 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
12013
12014 let running = Stop::new();
12017 let mut last_checked = None;
12018 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
12019 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
12020 .await;
12021 assert_eq!(
12022 crate::disk::dir_size(&cache_dir),
12023 0,
12024 "over the cap on the first check ever: pruned at once, no idle queue required"
12025 );
12026 assert_eq!(last_checked, Some(t0));
12027
12028 std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
12030 let too_soon = t0 + jiff::SignedDuration::from_secs(1);
12031 maybe_prune_cache_between_runs(
12032 &opts.repo,
12033 &opts,
12034 &home,
12035 &running,
12036 &mut last_checked,
12037 too_soon,
12038 )
12039 .await;
12040 assert_eq!(
12041 crate::disk::dir_size(&cache_dir),
12042 10,
12043 "too soon since the last check: left alone rather than rescanned every call"
12044 );
12045 assert_eq!(
12046 last_checked,
12047 Some(t0),
12048 "an idle check does not reset the clock"
12049 );
12050
12051 let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
12053 maybe_prune_cache_between_runs(
12054 &opts.repo,
12055 &opts,
12056 &home,
12057 &running,
12058 &mut last_checked,
12059 due_again,
12060 )
12061 .await;
12062 assert_eq!(
12063 crate::disk::dir_size(&cache_dir),
12064 0,
12065 "due again: pruned back under the cap"
12066 );
12067 }
12068
12069 #[tokio::test]
12077 async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
12078 let dir = tempfile::tempdir().unwrap();
12079 let home = dir.path().join("home");
12080 let cache_dir = dir.path().join("cache");
12081 std::fs::create_dir_all(&cache_dir).unwrap();
12082 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
12083 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
12084
12085 let stop = Stop::new();
12086 stop.stop();
12087 assert!(
12088 !stop.finishing(),
12089 "no run is in flight at a between-runs boundary, so nothing else \
12090 would tell the operator this stop had not taken effect yet"
12091 );
12092
12093 let mut last_checked = None;
12094 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
12095 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
12096 .await;
12097 assert_eq!(
12098 crate::disk::dir_size(&cache_dir),
12099 10,
12100 "over its cap, and due for the first check ever, but a stop outranks \
12101 it: the cap is a standing policy the next start measures again"
12102 );
12103 assert_eq!(
12104 last_checked, None,
12105 "a check that never happened must not claim the interval"
12106 );
12107 }
12108
12109 #[tokio::test]
12112 async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
12113 let dir = tempfile::tempdir().unwrap();
12114 let cache_dir = dir.path().join("cache");
12115 std::fs::create_dir_all(&cache_dir).unwrap();
12116 std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
12117
12118 let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
12119 opts.poll = Duration::from_millis(20);
12120 opts.max_attempts = 1_000;
12121
12122 let queue = Queue::at(dir.path().join("queue"));
12123 for i in 0..128 {
12124 let mut task = Task::new(
12125 format!("queued work {i}"),
12126 format!("queued work {i}"),
12127 opts.repo.clone(),
12128 Source::Human,
12129 );
12130 queue.put(&mut task).unwrap();
12131 }
12132
12133 let home = dir.path().join("home");
12134 let worktrees = dir.path().join("wt");
12135 run_service_worker(
12136 &home,
12137 serde_json::to_value(ServiceWorker {
12138 opts,
12139 queue: queue.root().to_path_buf(),
12140 worktrees_root: worktrees,
12141 operation: "cache".to_owned(),
12142 })
12143 .unwrap(),
12144 )
12145 .await
12146 .unwrap();
12147 let after = queue.list();
12148 assert_eq!(after.len(), 128);
12149 assert!(
12150 after
12151 .iter()
12152 .all(|task| task.status.runnable() && task.attempts == 0)
12153 );
12154
12155 assert_eq!(
12156 crate::disk::dir_size(&cache_dir),
12157 0,
12158 "an oversized cache must not be left to grow unboundedly just because the \
12159 queue kept the loop busy the whole time"
12160 );
12161 }
12162
12163 #[test]
12164 fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
12165 let dir = tempfile::tempdir().unwrap();
12166 let queue = Queue::at(dir.path().join("queue"));
12167 let questions = Questions::at(dir.path().join("questions"));
12168 let mut task = task();
12169 queue.put(&mut task).unwrap();
12170
12171 let mut task_question = ask::Question::new(
12172 task.id.clone(),
12173 crate::conduct::NODE.to_owned(),
12174 "conduct".to_owned(),
12175 "Which backend?".to_owned(),
12176 String::new(),
12177 Vec::new(),
12178 );
12179 questions.put(&mut task_question).unwrap();
12180 task.block(vec![task_question.id.clone()], None);
12181 queue.put(&mut task).unwrap();
12182
12183 let mut run_question = ask::Question::new(
12184 "20260101-000000-run1".to_owned(),
12185 "review".to_owned(),
12186 "reviewer-1".to_owned(),
12187 "Run question".to_owned(),
12188 String::new(),
12189 Vec::new(),
12190 );
12191 questions.put(&mut run_question).unwrap();
12192
12193 let mut coincidental = ask::Question::new(
12198 task.id.clone(),
12199 "review".to_owned(),
12200 "reviewer-1".to_owned(),
12201 "Unrelated review question".to_owned(),
12202 String::new(),
12203 Vec::new(),
12204 );
12205 questions.put(&mut coincidental).unwrap();
12206
12207 reconcile_task_questions(&queue, &questions);
12208 assert!(questions.get(&task_question.id).unwrap().status.open());
12209 assert!(questions.get(&run_question.id).unwrap().status.open());
12210 assert!(questions.get(&coincidental.id).unwrap().status.open());
12211
12212 task.release();
12213 queue.put(&mut task).unwrap();
12214 reconcile_task_questions(&queue, &questions);
12215 assert_eq!(
12216 questions.get(&task_question.id).unwrap().status,
12217 ask::QuestionStatus::Abandoned
12218 );
12219 assert!(
12220 questions.get(&run_question.id).unwrap().status.open(),
12221 "run questions remain the run janitor's responsibility"
12222 );
12223 assert!(
12224 questions.get(&coincidental.id).unwrap().status.open(),
12225 "a non-conductor question must not be abandoned just because its \
12226 run id coincides with a task id"
12227 );
12228 }
12229
12230 #[test]
12231 fn a_freshly_started_running_task_is_never_stalled() {
12232 let dir = tempfile::tempdir().unwrap();
12233 let mut t = task();
12234 t.start("run-1".to_owned());
12235 assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
12238 }
12239
12240 #[test]
12241 fn a_long_running_task_with_no_live_daemon_is_stalled() {
12242 let dir = tempfile::tempdir().unwrap();
12243 let mut t = task();
12244 t.start("run-1".to_owned());
12245 t.updated_at = Timestamp::now()
12246 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
12247 assert!(is_stalled(&t, dir.path(), Timestamp::now()));
12248 assert_eq!(
12249 stalled_tasks(
12250 &Queue::at(dir.path().join("q")),
12251 dir.path(),
12252 Timestamp::now()
12253 )
12254 .len(),
12255 0,
12256 "the task was never written to this queue"
12257 );
12258 }
12259
12260 #[test]
12261 fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
12262 let dir = tempfile::tempdir().unwrap();
12263 let mut t = task();
12264 t.id = "20260903-080340-0167".to_owned();
12265 t.start("20260903-080619-01c2".to_owned());
12266 t.updated_at = Timestamp::now()
12267 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
12268
12269 let mut status = Status::new();
12270 status.current = vec![Current {
12271 worker: None,
12272 task: t.id.clone(),
12273 run: "20260903-080619-01c2".to_owned(),
12274 }];
12275 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12276
12277 assert!(
12278 !is_stalled(&t, dir.path(), Timestamp::now()),
12279 "a live daemon's own heartbeat rules out stalled, however long the task has run"
12280 );
12281 }
12282
12283 fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
12287 let path = queue.path_of(id);
12288 let body = std::fs::read_to_string(&path).unwrap();
12289 let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
12290 let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
12291 v["updated_at"] = serde_json::Value::String(old.to_string());
12292 std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
12293 }
12294
12295 #[test]
12296 fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
12297 let dir = tempfile::tempdir().unwrap();
12310 let queue = Queue::at(dir.path().join("queue"));
12311 let home = dir.path().join("home");
12312
12313 let mut t = task();
12314 t.id = "20260101-000001-lock".to_owned();
12315 t.start("run-1".to_owned());
12316 queue.put(&mut t).unwrap();
12317 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
12318 std::fs::write(
12319 dir.path().join("queue").join(format!("{}.lock", t.id)),
12320 "not a pid",
12321 )
12322 .unwrap();
12323
12324 let now = Timestamp::now();
12325 assert!(
12326 reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
12327 "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
12328 and reclaim must leave the task alone"
12329 );
12330 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
12331
12332 let stalled = stalled_tasks(&queue, &home, now);
12333 assert_eq!(
12334 stalled.len(),
12335 1,
12336 "reclaim's inability to claim it yet must not hide it from the conductor"
12337 );
12338 assert_eq!(stalled[0].id, t.id);
12339 }
12340
12341 #[test]
12342 fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
12343 let dir = tempfile::tempdir().unwrap();
12344 crate::run::set_home(dir.path().join("run-home"));
12345 let queue = Queue::at(dir.path().join("queue"));
12346 let home = dir.path().join("home");
12347 let questions = Questions::at(dir.path().join("questions"));
12348
12349 let mut t = task();
12350 t.id = "20260101-000003-dead".to_owned();
12351 t.start("missing-run".to_owned());
12352 queue.put(&mut t).unwrap();
12353 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
12354
12355 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
12358 assert_eq!(
12359 stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
12360 [&t.id]
12361 );
12362 assert_eq!(
12363 reclaim_orphaned_running(&queue, 2, &Default::default()),
12364 [t.id.clone()]
12365 );
12366 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12367
12368 crate::conduct::apply(
12371 &queue,
12372 &questions,
12373 &crate::conduct::Verdict {
12374 decisions: vec![crate::conduct::Decision {
12375 id: t.id.clone(),
12376 recovery: Some(crate::conduct::Recovery::Requeue),
12377 ..crate::conduct::Decision::default()
12378 }],
12379 },
12380 )
12381 .unwrap();
12382 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
12383 }
12384
12385 #[test]
12386 fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
12387 let dir = tempfile::tempdir().unwrap();
12388 let queue = Queue::at(dir.path().join("queue"));
12389 let home = dir.path().join("home");
12390
12391 let mut fresh = task();
12392 fresh.id = "20260101-000001-aaaa".to_owned();
12393 fresh.start("run-1".to_owned());
12394 queue.put(&mut fresh).unwrap();
12395
12396 let mut old = task();
12397 old.id = "20260101-000002-bbbb".to_owned();
12398 old.start("run-2".to_owned());
12399 queue.put(&mut old).unwrap();
12400 backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
12401
12402 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
12403 assert_eq!(stalled.len(), 1);
12404 assert_eq!(stalled[0].id, old.id);
12405 }
12406
12407 #[test]
12408 fn queued_and_finished_task_views_partition_by_status() {
12409 let dir = tempfile::tempdir().unwrap();
12410 let queue = Queue::at(dir.path().join("queue"));
12411
12412 let mut queued = task();
12413 queued.id = "20260101-000001-aaaa".to_owned();
12414 queue.put(&mut queued).unwrap();
12415
12416 let mut failed = task();
12417 failed.id = "20260101-000002-bbbb".to_owned();
12418 failed.start("run-1".to_owned());
12419 failed.fail("gate red", 5);
12420 queue.put(&mut failed).unwrap();
12421
12422 let mut held = task();
12423 held.id = "20260101-000003-cccc".to_owned();
12424 held.hold_machine(None);
12425 queue.put(&mut held).unwrap();
12426
12427 let mut running = task();
12428 running.id = "20260101-000004-dddd".to_owned();
12429 running.start("run-2".to_owned());
12430 queue.put(&mut running).unwrap();
12431
12432 let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
12433 assert_eq!(queued_ids, [queued.id.clone()]);
12434
12435 let mut finished_ids: Vec<String> =
12436 finished_tasks(&queue).into_iter().map(|t| t.id).collect();
12437 finished_ids.sort_unstable();
12438 let mut want = vec![failed.id.clone(), held.id.clone()];
12439 want.sort_unstable();
12440 assert_eq!(finished_ids, want);
12441 }
12442
12443 #[test]
12444 fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
12445 for short in [false, true] {
12446 let dir = tempfile::tempdir().unwrap();
12447 let queue = Queue::at(dir.path().join("queue"));
12448 let questions = ask::Questions::at(dir.path().join("questions"));
12449 let mut running = task();
12450 running.id = "20261013-192213-feb2".into();
12451 running.start("existing-run".into());
12452 queue.put(&mut running).unwrap();
12453 let mut middle = task();
12454 middle.id = "20261013-193611-ca5b".into();
12455 middle.block(
12456 vec![if short {
12457 "feb2".into()
12458 } else {
12459 running.id.clone()
12460 }],
12461 None,
12462 );
12463 queue.put(&mut middle).unwrap();
12464 let mut waiting = task();
12465 waiting.id = "20261013-202849-ee37".into();
12466 waiting.block(
12467 vec![if short {
12468 "ca5b".into()
12469 } else {
12470 middle.id.clone()
12471 }],
12472 Some("wait for implementation".into()),
12473 );
12474 queue.put(&mut waiting).unwrap();
12475 assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
12476 let inv = crate::blockers::Inventory::load(&queue, &questions);
12477 assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
12478 assert!(inv.stuck().is_empty());
12479 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12480 assert!(report.quarantined.is_empty());
12481 assert!(report.asked.is_empty());
12482 resolve_blockers(&queue, &questions);
12483 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12484 assert!(questions.list().is_empty());
12485 running.succeed(CompletionContext::new(
12488 CompletionActor::DaemonSettle,
12489 None,
12490 dir.path(),
12491 &running,
12492 ));
12493 queue.put(&mut running).unwrap();
12494 resolve_blockers(&queue, &questions);
12495 assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
12496 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12497 middle = queue.get(&middle.id).unwrap();
12498 middle.succeed(CompletionContext::new(
12499 CompletionActor::DaemonSettle,
12500 None,
12501 dir.path(),
12502 &middle,
12503 ));
12504 queue.put(&mut middle).unwrap();
12505 resolve_blockers(&queue, &questions);
12506 let after = queue.get(&waiting.id).unwrap();
12507 assert_eq!(after.status, TaskStatus::Queued);
12508 assert!(after.blocked_by.is_empty());
12509 assert_eq!(after.instruction, waiting.instruction);
12510 }
12511 }
12512
12513 #[test]
12514 fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
12515 for future_schema in [false, true] {
12516 let name = "20261013-193611-ca5b";
12517 let mut future = task();
12518 future.id = name.into();
12519 future.schema = crate::queue::SCHEMA + 1;
12520 let contents = if future_schema {
12521 serde_json::to_string(&future).unwrap()
12522 } else {
12523 "corrupt".into()
12524 };
12525 let dir = tempfile::tempdir().unwrap();
12526 let queue = Queue::at(dir.path().join("queue"));
12527 let questions = ask::Questions::at(dir.path().join("questions"));
12528 let mut waiting = task();
12529 waiting.id = "20261013-202849-ee37".into();
12530 waiting.block(vec!["ca5b".into()], None);
12531 queue.put(&mut waiting).unwrap();
12532 std::fs::write(queue.path_of(name), contents).unwrap();
12533 assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
12534 assert!(
12535 crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
12536 );
12537 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12538 assert!(report.asked.is_empty());
12539 resolve_blockers(&queue, &questions);
12540 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12541 assert!(questions.list().is_empty());
12542 }
12543 let dir = tempfile::tempdir().unwrap();
12544 let queue = Queue::at(dir.path().join("queue"));
12545 let questions = ask::Questions::at(dir.path().join("questions"));
12546 let mut waiting = task();
12547 waiting.id = "20261013-202849-ee37".into();
12548 waiting.block(vec!["ca5b".into()], None);
12549 queue.put(&mut waiting).unwrap();
12550 let mut done = task();
12551 done.id = "20261013-193611-ca5b".into();
12552 done.succeed(CompletionContext::new(
12553 CompletionActor::Cli,
12554 None,
12555 dir.path(),
12556 &done,
12557 ));
12558 queue.put(&mut done).unwrap();
12559 std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
12562 assert!(queue.get("ca5b").is_err());
12563 assert_eq!(
12564 crate::queue::dependency(&queue, &questions, "ca5b"),
12565 crate::queue::Dependency::Ambiguous
12566 );
12567 resolve_blockers(&queue, &questions);
12568 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12569 assert!(report.asked.is_empty());
12570 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12571 assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
12572 }
12573
12574 #[test]
12575 fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
12576 for held in [false, true] {
12577 for question in [false, true] {
12578 for reference in ["ca5b", "20261013-193611-ca5b"] {
12579 let dir = tempfile::tempdir().unwrap();
12580 let queue = Queue::at(dir.path().join("queue"));
12581 let questions = ask::Questions::at(dir.path().join("questions"));
12582 let mut prerequisite = task();
12583 prerequisite.id = "20261013-193611-ca5b".into();
12584 prerequisite.start("existing-run".into());
12585 queue.put(&mut prerequisite).unwrap();
12586 let mut waiting = task();
12587 waiting.id = "20261013-202849-ee37".into();
12588 if held {
12589 waiting.hold_machine(Some("waiting for separate consent".into()));
12590 }
12591 queue.put(&mut waiting).unwrap();
12592 let reason = "Deleting saved data requires separate owner consent";
12593 crate::conduct::apply(
12594 &queue,
12595 &questions,
12596 &crate::conduct::Verdict {
12597 decisions: vec![crate::conduct::Decision {
12598 id: waiting.id.clone(),
12599 blocked_by: vec![reference.into()],
12600 question: question.then(|| "May the saved data be deleted?".into()),
12601 recovery: (!question).then_some(crate::conduct::Recovery::Hold),
12602 reason: Some(reason.into()),
12603 ..crate::conduct::Decision::default()
12604 }],
12605 },
12606 )
12607 .unwrap();
12608 let before = queue.get(&waiting.id).unwrap();
12609 if question {
12610 assert_eq!(before.status, TaskStatus::Blocked);
12611 let q = questions.get(&before.blocked_by[0]).unwrap();
12612 assert_eq!(q.summary, "May the saved data be deleted?");
12613 assert!(q.status.open());
12614 } else {
12615 assert_eq!(before.status, TaskStatus::Held);
12616 let recorded_reason = before.hold_reason.as_deref().unwrap();
12617 assert!(recorded_reason.starts_with(reason));
12618 if held {
12619 assert!(recorded_reason.contains("waiting for separate consent"));
12620 }
12621 }
12622 prerequisite.succeed(CompletionContext::new(
12623 CompletionActor::DaemonSettle,
12624 None,
12625 dir.path(),
12626 &prerequisite,
12627 ));
12628 queue.put(&mut prerequisite).unwrap();
12629 resolve_blockers(&queue, &questions);
12630 let after = queue.get(&waiting.id).unwrap();
12631 assert_eq!(after.status, before.status);
12632 assert_eq!(after.blocked_by, before.blocked_by);
12633 assert_eq!(after.hold_reason, before.hold_reason);
12634 assert_eq!(after.instruction, waiting.instruction);
12635 if question {
12636 assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
12637 }
12638 assert!(
12639 queue.next_runnable().is_none(),
12640 "dependency completion is not consent"
12641 );
12642 }
12643 }
12644 }
12645 }
12646
12647 #[test]
12648 fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
12649 let dir = tempfile::tempdir().unwrap();
12650 let queue = Queue::at(dir.path().join("queue"));
12651 let questions = ask::Questions::at(dir.path().join("questions"));
12652
12653 let mut dep = task();
12654 dep.id = "20260101-000001-dep0".to_owned();
12655 dep.succeed(CompletionContext::new(
12656 CompletionActor::DaemonSettle,
12657 None,
12658 dir.path(),
12659 &dep,
12660 ));
12661 queue.put(&mut dep).unwrap();
12662
12663 let mut still_going = task();
12664 still_going.id = "20260101-000002-dep1".to_owned();
12665 queue.put(&mut still_going).unwrap();
12666
12667 let mut blocked = task();
12668 blocked.id = "20260101-000003-main".to_owned();
12669 blocked.block(
12670 vec![dep.id.clone(), still_going.id.clone()],
12671 Some("waits on both".to_owned()),
12672 );
12673 queue.put(&mut blocked).unwrap();
12674
12675 resolve_blockers(&queue, &questions);
12676
12677 let after = queue.get(&blocked.id).unwrap();
12678 assert_eq!(
12679 after.status,
12680 TaskStatus::Blocked,
12681 "one dependency is still outstanding"
12682 );
12683 assert_eq!(after.blocked_by, [still_going.id.clone()]);
12684 }
12685
12686 #[test]
12687 fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
12688 let dir = tempfile::tempdir().unwrap();
12689 let queue = Queue::at(dir.path().join("queue"));
12690 let questions = ask::Questions::at(dir.path().join("questions"));
12691
12692 let mut q = crate::ask::Question::new(
12693 "20260101-000001-main".to_owned(),
12694 crate::conduct::NODE.to_owned(),
12695 "conduct".to_owned(),
12696 "Which backend?".to_owned(),
12697 String::new(),
12698 Vec::new(),
12699 );
12700 questions.put(&mut q).unwrap();
12701 q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
12702 .unwrap();
12703 questions.put(&mut q).unwrap();
12704
12705 let mut blocked = task();
12706 blocked.id = "20260101-000001-main".to_owned();
12707 blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
12708 queue.put(&mut blocked).unwrap();
12709
12710 resolve_blockers(&queue, &questions);
12711
12712 let after = queue.get(&blocked.id).unwrap();
12713 assert_eq!(
12714 after.status,
12715 TaskStatus::Queued,
12716 "the only blocker resolved"
12717 );
12718 assert_eq!(after.answers.len(), 1);
12719 assert_eq!(after.answers[0].question, "Which backend?");
12720 assert_eq!(after.answers[0].answer, "SQLite");
12721
12722 let instruction = instruction_for(&after);
12724 assert!(instruction.contains("Which backend?"));
12725 assert!(instruction.contains("SQLite"));
12726 }
12727
12728 #[test]
12729 fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
12730 let dir = tempfile::tempdir().unwrap();
12731 let queue = Queue::at(dir.path().join("queue"));
12732 let questions = ask::Questions::at(dir.path().join("questions"));
12733
12734 let mut q = crate::ask::Question::new(
12735 "20260101-000001-main".to_owned(),
12736 crate::conduct::NODE.to_owned(),
12737 "conduct".to_owned(),
12738 "Is the setup done?".to_owned(),
12739 String::new(),
12740 Vec::new(),
12741 );
12742 q.abandon("no answer within 60s of asking");
12743 questions.put(&mut q).unwrap();
12744
12745 let mut blocked = task();
12746 blocked.id = "20260101-000001-main".to_owned();
12747 blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
12748 queue.put(&mut blocked).unwrap();
12749
12750 resolve_blockers(&queue, &questions);
12751
12752 let after = queue.get(&blocked.id).unwrap();
12753 assert_eq!(
12754 after.status,
12755 TaskStatus::Held,
12756 "never left blocked on nothing"
12757 );
12758 assert!(!after.operator_held(), "a machine hold, for triage");
12759 assert!(
12760 after
12761 .hold_reason
12762 .as_deref()
12763 .unwrap_or_default()
12764 .contains("went unanswered")
12765 );
12766 }
12767
12768 #[test]
12769 fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
12770 let dir = tempfile::tempdir().unwrap();
12776 let queue = Queue::at(dir.path().join("queue"));
12777 let questions = ask::Questions::at(dir.path().join("questions"));
12778
12779 let mut q = crate::ask::Question::new(
12780 "20260101-000001-main".to_owned(),
12781 crate::conduct::NODE.to_owned(),
12782 "conduct".to_owned(),
12783 "How should this be handled?".to_owned(),
12784 String::new(),
12785 Vec::new(),
12786 );
12787 questions.put(&mut q).unwrap();
12788 q.answer(crate::ask::Answer::Text(
12789 "leave it held, a human will look at it later".to_owned(),
12790 ))
12791 .unwrap();
12792 questions.put(&mut q).unwrap();
12793
12794 let mut held = task();
12795 held.id = "20260101-000001-main".to_owned();
12796 held.hold_machine(Some("out of attempts".to_owned()));
12797 held.block(vec![q.id.clone()], Some("what now?".to_owned()));
12798 queue.put(&mut held).unwrap();
12799
12800 resolve_blockers(&queue, &questions);
12801
12802 let after = queue.get(&held.id).unwrap();
12803 assert_eq!(after.status, TaskStatus::Held);
12804 assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
12805 assert_eq!(
12806 after.answers[0].answer,
12807 "leave it held, a human will look at it later"
12808 );
12809 }
12810
12811 #[test]
12812 fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
12813 let dir = tempfile::tempdir().unwrap();
12814 let queue = Queue::at(dir.path().join("queue"));
12815 let questions = ask::Questions::at(dir.path().join("questions"));
12816 let mut dep = task();
12817 dep.id = "20260101-000001-gone".to_owned();
12818 queue.put(&mut dep).unwrap();
12819 let mut blocked = task();
12820 blocked.id = "20260101-000003-main".to_owned();
12821 blocked.block(vec![dep.id.clone()], None);
12822 queue.put(&mut blocked).unwrap();
12823
12824 let claim = queue.claim(&blocked.id).unwrap();
12826 queue.remove(&dep.id, false, &questions).unwrap();
12827 drop(claim);
12828 resolve_blockers(&queue, &questions);
12829
12830 let after = queue.get(&blocked.id).unwrap();
12831 assert_eq!(after.status, TaskStatus::Queued);
12832 assert!(after.blocked_by.is_empty());
12833 }
12834
12835 #[test]
12836 fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
12837 let dir = tempfile::tempdir().unwrap();
12843 let queue = Queue::at(dir.path().join("queue"));
12844 let questions = ask::Questions::at(dir.path().join("questions"));
12845
12846 let mut still_going = task();
12847 still_going.id = "20260101-000002-dep1".to_owned();
12848 queue.put(&mut still_going).unwrap();
12849
12850 let mut blocked = task();
12851 blocked.id = "20260101-000003-main".to_owned();
12852 blocked.block(
12853 vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
12854 Some("waits on both".to_owned()),
12855 );
12856 queue.put(&mut blocked).unwrap();
12857
12858 resolve_blockers(&queue, &questions);
12859
12860 let after = queue.get(&blocked.id).unwrap();
12861 assert_eq!(
12862 after.status,
12863 TaskStatus::Held,
12864 "a missing dependency must not leave the task blocked forever"
12865 );
12866 assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
12867 assert!(after.blocked_by.is_empty());
12868 let reason = after.hold_reason.as_deref().unwrap_or_default();
12869 assert!(
12870 reason.contains("20260101-000001-gone"),
12871 "the missing id must be named so an operator can tell what happened: {reason}"
12872 );
12873 assert!(
12874 reason.contains(&still_going.id),
12875 "the still-valid dependency must not silently vanish from the record: {reason}"
12876 );
12877 }
12878
12879 #[test]
12880 fn instruction_for_is_unchanged_without_any_answers() {
12881 let t = task();
12882 assert_eq!(instruction_for(&t), t.instruction);
12883 }
12884
12885 #[test]
12886 fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
12887 let dir = tempfile::tempdir().unwrap();
12888 let q = Queue::at(dir.path().join("queue"));
12889 let src = dir.path().join("shot.png");
12890 std::fs::write(&src, "x").unwrap();
12891 let mut t = task();
12892 q.attach(&mut t, &[src]).unwrap();
12893 let paths = task_attachments(&q, &t).unwrap();
12894 assert_eq!(paths.len(), 1);
12895 assert!(paths[0].is_absolute() && paths[0].is_file());
12896 std::fs::remove_file(&paths[0]).unwrap();
12897 let err = task_attachments(&q, &t).unwrap_err().to_string();
12898 assert!(err.contains("shot.png"), "{err}");
12899 }
12900
12901 #[tokio::test]
12902 async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
12903 let dir = tempfile::tempdir().unwrap();
12904 let queue_path = dir.path().join("queue");
12905 let queue = Queue::at(queue_path.clone());
12906 let mut t = task();
12907 t.source = Source::Agent {
12908 run: "originating-chat".into(),
12909 node: crate::queue::CHAT_NODE.into(),
12910 };
12911 let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
12912 stage: "config-fetch",
12913 target: "origin/main".into(),
12914 });
12915 record_config_failure(&mut t, &fetch);
12916 t.hold_machine(Some(format!("{fetch:#}")));
12917 let fetch_key = t.chat_notice_due().unwrap();
12918 t.chat_notices.push(fetch_key.clone());
12919 queue.put(&mut t).unwrap();
12920
12921 let queue = Queue::at(queue_path);
12922 let mut t = queue.get(&t.id).unwrap();
12923 let a = dir.path().join("a.toml");
12924 let b = dir.path().join("b.toml");
12925 for (path, text, new_cause) in [
12926 (&a, "[graph", true),
12927 (&a, "[verify", false),
12928 (&a, "[graph]\nimplementers = 'invalid-type'", true),
12929 (&b, "[graph]\nimplementers = 'invalid-type'", true),
12930 ] {
12931 t.release_operator("test", None);
12932 std::fs::write(path, text).unwrap();
12933 let error = Config::discover_fetched(dir.path(), Some(path))
12934 .await
12935 .unwrap_err();
12936 record_config_failure(&mut t, &error);
12937 t.hold_machine(Some(format!("{error:#}")));
12938 let due = t.chat_notice_due();
12939 assert_eq!(due.is_some(), new_cause, "{error:#}");
12940 if let Some(key) = due {
12941 assert_ne!(key, fetch_key);
12942 t.chat_notices.push(key);
12943 }
12944 }
12945 t.succeed(CompletionContext::new(
12946 CompletionActor::DaemonSettle,
12947 None,
12948 dir.path(),
12949 &t,
12950 ));
12951 assert_eq!(
12952 t.chat_notice_due(),
12953 Some(format!(
12954 "done:{}",
12955 t.completion_history.last().unwrap().occurrence
12956 ))
12957 );
12958 }
12959
12960 #[test]
12961 fn different_missing_attachments_have_distinct_persisted_notice_causes() {
12962 let dir = tempfile::tempdir().unwrap();
12963 let queue_path = dir.path().join("queue");
12964 let queue = Queue::at(queue_path.clone());
12965 let mut t = task();
12966 t.source = crate::queue::Source::Agent {
12967 run: "originating-chat".into(),
12968 node: crate::queue::CHAT_NODE.into(),
12969 };
12970 let a = dir.path().join("a.png");
12971 let b = dir.path().join("b.png");
12972 std::fs::write(&a, "a").unwrap();
12973 std::fs::write(&b, "b").unwrap();
12974 queue.attach(&mut t, &[a, b]).unwrap();
12975 let paths = task_attachments(&queue, &t).unwrap();
12976 for path in &paths {
12977 std::fs::remove_file(path).unwrap();
12978 }
12979 let missing = task_attachments(&queue, &t).unwrap_err();
12980 t.attempts += 1;
12981 let reason = missing.to_string();
12982 t.fail_startup_target("startup-attachments", missing.name, reason, 1);
12983 let first = t.chat_notice_due().expect("first attachment notice");
12984 t.chat_notices.push(first.clone());
12985 queue.put(&mut t).unwrap();
12986
12987 let queue = Queue::at(queue_path.clone());
12988 let mut t = queue.get(&t.id).unwrap();
12989 assert!(t.chat_notice_due().is_none(), "restart does not replay");
12990 t.release_operator("test", None);
12991 t.attempts += 1;
12992 let missing = task_attachments(&queue, &t).unwrap_err();
12993 t.fail_startup_target(
12994 "startup-attachments",
12995 missing.name,
12996 "same missing attachment with regenerated wording",
12997 1,
12998 );
12999 assert!(t.chat_notice_due().is_none(), "same object stays quiet");
13000
13001 std::fs::write(&paths[0], "restored").unwrap();
13002 t.release_operator("test", None);
13003 t.attempts += 1;
13004 let missing = task_attachments(&queue, &t).unwrap_err();
13005 let reason = missing.to_string();
13006 t.fail_startup_target("startup-attachments", missing.name, reason, 1);
13007 let second = t
13008 .chat_notice_due()
13009 .expect("different attachment must notify");
13010 assert_ne!(first, second);
13011 assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
13012 }
13013
13014 #[test]
13015 fn resumed_instruction_is_unchanged_without_any_answers() {
13016 let t = task();
13017 assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
13018 }
13019
13020 #[test]
13021 fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
13022 let mut t = task();
13023 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
13024 let old = t.instruction.clone();
13028
13029 let refreshed = resumed_instruction(&old, &t);
13030 assert!(refreshed.starts_with(&old), "the original text is kept");
13031 assert!(refreshed.contains("Which backend?"));
13032 assert!(refreshed.contains("SQLite"));
13033 }
13034
13035 #[test]
13036 fn resumed_instruction_keeps_an_original_answers_heading() {
13037 let mut t = task();
13038 t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
13039 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
13040
13041 let refreshed = resumed_instruction(&t.instruction, &t);
13042
13043 assert!(
13044 refreshed.starts_with(&t.instruction),
13045 "an answers heading in the original instruction is not the appended block"
13046 );
13047 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
13048 assert!(refreshed.contains("Which backend?"));
13049 assert!(refreshed.contains("SQLite"));
13050
13051 let repeated = resumed_instruction(&refreshed, &t);
13052 assert_eq!(
13053 repeated, refreshed,
13054 "only the final appended block is refreshed"
13055 );
13056 }
13057
13058 #[test]
13059 fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
13060 let mut t = task();
13061 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
13062
13063 let once = resumed_instruction(&t.instruction, &t);
13067 let twice = resumed_instruction(&once, &t);
13068 assert_eq!(once, twice);
13069 assert_eq!(once.matches("Which backend?").count(), 1);
13070
13071 t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
13073 let refreshed = resumed_instruction(&once, &t);
13074 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
13075 assert!(refreshed.contains("Which backend?"));
13076 assert!(refreshed.contains("Which cache?"));
13077 }
13078
13079 #[test]
13080 fn prepare_instruction_covers_all_three_starters() {
13081 let mut t = task();
13082 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
13083
13084 assert_eq!(
13087 prepare_instruction(&Starter::Start, None, &t),
13088 Some(instruction_for(&t))
13089 );
13090
13091 let old = t.instruction.clone();
13094 assert_eq!(
13095 prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
13096 Some(resumed_instruction(&old, &t))
13097 );
13098
13099 assert_eq!(
13103 prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
13104 None
13105 );
13106 }
13107
13108 #[test]
13109 fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
13110 assert_eq!(
13111 choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
13112 Starter::Review("magi/eba2/A".to_owned())
13113 );
13114 }
13115
13116 #[test]
13117 fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
13118 assert_eq!(
13119 choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
13120 Starter::Start,
13121 "a vanished review branch must not fall back to resuming the old run either"
13122 );
13123 }
13124
13125 #[test]
13126 fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
13127 let mut t = task();
13128 t.start("old-run".to_owned());
13129 t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
13130 t.release();
13131 let branch = t.review_branch.take();
13132 assert_eq!(
13133 choose_starter(branch.as_deref(), true, Some("old-run")),
13134 Starter::Review("magi/eba2/A".to_owned()),
13135 "a review wins over resuming the old run"
13136 );
13137 }
13138
13139 #[test]
13140 fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
13141 assert_eq!(
13142 choose_starter(None, false, Some("some-run")),
13143 Starter::Resume("some-run".to_owned())
13144 );
13145 assert_eq!(choose_starter(None, false, None), Starter::Start);
13146 }
13147
13148 #[test]
13149 fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
13150 let mut released = task();
13151 released.start("stalled-run".to_owned());
13152 released.requeue();
13153 let unfinished = (!released.fresh_start)
13154 .then(|| Some("stalled-run".to_owned()))
13155 .flatten();
13156 assert_eq!(
13157 choose_starter(None, false, unfinished.as_deref()),
13158 Starter::Start,
13159 "release keeps run history but must not resume it"
13160 );
13161 assert_eq!(released.runs, ["stalled-run"]);
13162 }
13163
13164 #[test]
13165 fn landing_hold_receipt_survives_release_retry_and_checkpoint_removal() {
13166 let dir = tempfile::tempdir().unwrap();
13167 let queue = Queue::at(dir.path().join("queue"));
13168 let mut state = run_state(RunStatus::Blocked);
13169 state.merge_decision = Some(crate::merge_decision::Decision {
13170 question: "hold-inquiry".into(),
13171 target: crate::merge_decision::Target {
13172 pr: "https://example.test/pull/1".into(),
13173 head: "reviewed-head".into(),
13174 language: "en".into(),
13175 },
13176 choice: land::HOLD.into(),
13177 closed: false,
13178 replacement_run: None,
13179 replacement_pr: None,
13180 });
13181 let mut t = task();
13182 t.start(state.id.clone());
13183 settle_and_diagnose(
13184 &mut t,
13185 Verdict {
13186 status: RunStatus::Blocked,
13187 left_pr: true,
13188 quota_hit: false,
13189 parked: false,
13190 no_viable_candidates: false,
13191 },
13192 "held",
13193 2,
13194 &state,
13195 );
13196 queue.put(&mut t).unwrap();
13197 t.release_operator("chat", None);
13198 t.edit("revised".into(), "revised instruction".into())
13199 .unwrap();
13200 queue.put(&mut t).unwrap();
13201 drop(state);
13202 assert_eq!(
13203 queue
13204 .get(&t.id)
13205 .unwrap()
13206 .decision_effects
13207 .get("hold-inquiry"),
13208 Some(&format!("decision: {}", land::HOLD))
13209 );
13210 }
13211
13212 fn stopped_public_run(status: RunStatus) -> RunState {
13213 let mut state = run_state(status);
13214 state.driver_exited = true;
13215 state.config.graph.land = true;
13216 state.config.graph.review_rounds = 1;
13217 state.reviews = vec![review_round(1)];
13218 state.merge = Some(crate::run::MergeOutcome {
13219 mode: MergeMode::Pr,
13220 ok: false,
13221 detail: "landing stopped".into(),
13222 empty: false,
13223 });
13224 state.pr = Some(crate::run::PrRecord {
13225 url: "https://example.test/pull/1".into(),
13226 number: 1,
13227 state: "open".into(),
13228 checks: "red".into(),
13229 round: 1,
13230 rounds: 1,
13231 red_at_merge: Vec::new(),
13232 });
13233 state
13234 }
13235
13236 #[test]
13237 fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
13238 for status in [RunStatus::Blocked, RunStatus::Gating] {
13239 let home = tempfile::tempdir().unwrap();
13240 let mut state = stopped_public_run(status);
13241 state.save_under(home.path()).unwrap();
13242 assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
13243 assert!(!exhausted_review_budget(&state));
13244 let mut task = held_task_with(&state.id);
13245 task.release();
13246 let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
13247 assert_eq!(
13248 choose_starter(None, false, unfinished.as_deref()),
13249 Starter::Resume(state.id.clone())
13250 );
13251 let question = action_question(&state.id, resume_action(&state.id));
13252 assert_eq!(
13253 decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
13254 state.clone()
13255 )),
13256 ActionDecision::Resume(state.id.clone())
13257 );
13258 assert_eq!(
13260 crate::resume::validate(home.path(), &state.id).unwrap().id,
13261 state.id
13262 );
13263 let queue = Queue::at(home.path().join("queue"));
13264 let mut controlled = Task::new(
13265 "resume land".into(),
13266 state.instruction.clone(),
13267 state.repo.clone(),
13268 Source::Agent {
13269 run: "talk".into(),
13270 node: crate::queue::CHAT_NODE.into(),
13271 },
13272 );
13273 controlled.runs.push(state.id.clone());
13274 controlled.hold_machine(Some("land stopped".into()));
13275 queue.put(&mut controlled).unwrap();
13276 let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
13277 assert_eq!(resumed.status, TaskStatus::Queued);
13278 assert_eq!(
13279 resumed.resume_override.unwrap().pinned_run,
13280 Some(state.id.clone())
13281 );
13282 assert_eq!(resumed.attempts, 0);
13283 }
13284 }
13285
13286 #[test]
13287 fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
13288 for review_rounds in [0, 1] {
13289 let home = tempfile::tempdir().unwrap();
13290 let mut state = run_state(RunStatus::Blocked);
13291 state.config.graph.review_rounds = review_rounds;
13292 if review_rounds > 0 {
13293 let mut review = review_round(1);
13294 review.clean = true;
13295 state.reviews = vec![review];
13296 }
13297 state.gate_ran = true;
13298 state.gate = vec![crate::run::CommandOutcome {
13299 command: "verify".into(),
13300 code: Some(1),
13301 output_tail: "gate failed after repair budget exhausted".into(),
13302 duration_ms: 0,
13303 resource_blocked: false,
13304 }];
13305 state.save_under(home.path()).unwrap();
13306 assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
13307 assert!(exhausted_review_budget(&state));
13308 let mut task = held_task_with(&state.id);
13309 task.release();
13310 assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
13311 let question = action_question(&state.id, resume_action(&state.id));
13312 assert_ne!(
13313 decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
13314 state.clone()
13315 )),
13316 ActionDecision::Resume(state.id.clone())
13317 );
13318 let error = crate::resume::validate(home.path(), &state.id)
13319 .unwrap_err()
13320 .to_string();
13321 assert!(!error.contains("review budget exhausted"), "{error}");
13322 assert!(
13323 error.contains(if review_rounds == 0 {
13324 "review is disabled"
13325 } else {
13326 "gate already ran"
13327 }),
13328 "{error}"
13329 );
13330
13331 state.gate_ran = false;
13333 state.gate.clear();
13334 assert!(!exhausted_review_budget(&state));
13335 assert_eq!(
13336 unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
13337 Some(state.id)
13338 );
13339 }
13340 }
13341
13342 #[test]
13343 fn resource_blocked_verification_resumes_the_same_run() {
13344 for (kind, stage) in [
13345 ("cache", "clean"),
13346 ("coordination", "clean"),
13347 ("cache", "review-e2e"),
13348 ("coordination", "no-reviews"),
13349 ("coordination", "handoff"),
13350 ] {
13351 let home = tempfile::tempdir().unwrap();
13352 let mut state = run_state(RunStatus::Blocked);
13353 state.config.graph.review_rounds = 1;
13354 let mut review = review_round(1);
13355 review.clean = true;
13356 state.reviews = vec![review];
13357 if stage == "review-e2e" {
13358 let review = &mut state.reviews[0];
13359 review.clean = false;
13360 review.blocking = 1;
13361 review.e2e = vec![crate::run::CommandOutcome {
13362 command: "verify".into(),
13363 code: None,
13364 output_tail: "resource wait expired".into(),
13365 duration_ms: 0,
13366 resource_blocked: true,
13367 }];
13368 } else if stage == "no-reviews" {
13369 state.config.graph.review_rounds = 0;
13370 state.reviews.clear();
13371 } else if stage == "handoff" {
13372 let review = &mut state.reviews[0];
13375 review.clean = false;
13376 review.blocking = 1;
13377 review.e2e = vec![crate::run::CommandOutcome {
13378 command: "verify".into(),
13379 code: Some(0),
13380 output_tail: String::new(),
13381 duration_ms: 0,
13382 resource_blocked: false,
13383 }];
13384 }
13385 state.gate_ran = false;
13386 state.resource_block = Some(crate::run::ResourceBlock {
13387 cause: crate::run::ResourceBlockCause::Other,
13388 node: if stage == "review-e2e" {
13389 "review"
13390 } else {
13391 "gate"
13392 }
13393 .into(),
13394 kind: kind.into(),
13395 detail: "resource wait expired".into(),
13396 at: jiff::Timestamp::now(),
13397 });
13398 state.save_under(home.path()).unwrap();
13399 assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
13400 assert!(!exhausted_review_budget(&state));
13401 let mut task = held_task_with(&state.id);
13402 task.release();
13403 let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
13404 assert_eq!(
13405 choose_starter(None, false, unfinished.as_deref()),
13406 Starter::Resume(state.id.clone())
13407 );
13408 let question = action_question(&state.id, resume_action(&state.id));
13409 assert_eq!(
13410 decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
13411 state.clone()
13412 )),
13413 ActionDecision::Resume(state.id.clone())
13414 );
13415 assert_eq!(
13416 crate::resume::validate(home.path(), &state.id).unwrap().id,
13417 state.id
13418 );
13419 let queue = Queue::at(home.path().join("queue"));
13420 let mut controlled = Task::new(
13421 "resume verification".into(),
13422 state.instruction.clone(),
13423 state.repo.clone(),
13424 Source::Agent {
13425 run: "talk".into(),
13426 node: crate::queue::CHAT_NODE.into(),
13427 },
13428 );
13429 controlled.runs.push(state.id.clone());
13430 controlled.hold_machine(Some("verification resource unavailable".into()));
13431 queue.put(&mut controlled).unwrap();
13432 let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
13433 assert_eq!(resumed.status, TaskStatus::Queued);
13434 assert_eq!(
13435 resumed.resume_override.unwrap().pinned_run,
13436 Some(state.id.clone())
13437 );
13438 assert_eq!(resumed.attempts, 0);
13439
13440 state.config.graph.review_rounds = 1;
13442 let mut unresolved = review_round(1);
13443 unresolved.blocking = 1;
13444 state.reviews = vec![unresolved];
13445 state.resource_block = None;
13446 state.save_under(home.path()).unwrap();
13447 assert!(exhausted_review_budget(&state));
13448 assert!(crate::resume::validate(home.path(), &state.id).is_err());
13449 }
13450 }
13451
13452 #[tokio::test]
13453 async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
13454 if !crate::standalone_test(
13455 "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
13456 ) {
13457 return;
13458 }
13459 let home = tempfile::tempdir().unwrap();
13460 let mut owner = stopped_public_run(RunStatus::Blocked);
13461 owner.save_under(home.path()).unwrap();
13462 let history = vec![owner.id.clone()];
13463 let repo = owner.repo.clone();
13464 let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
13465 let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
13466 let initial =
13467 std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
13468 assert!(
13469 initial.is_pending(),
13470 "a busy record must not hold or resume the task"
13471 );
13472 owner.retired_to = Some("20260101-000001-bbbb".into());
13473 owner.save_under(home.path()).unwrap();
13474 drop(lock);
13475 let result = tokio::time::timeout(Duration::from_secs(10), lookup)
13476 .await
13477 .expect("ownership lock released")
13478 .expect("read settled owner");
13479 assert!(
13480 result.is_none(),
13481 "the retired owner must not be resumed from a stale read"
13482 );
13483 }
13484
13485 #[tokio::test]
13486 async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
13487 if !crate::standalone_test(
13488 "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
13489 ) {
13490 return;
13491 }
13492 let home = tempfile::tempdir().unwrap();
13493 let mut owner = stopped_public_run(RunStatus::Blocked);
13494 let repo = tempfile::tempdir().unwrap();
13495 crate::git::git(repo.path(), &["init"]).await.unwrap();
13496 owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
13497 owner.id = "20260101-000000-aaaa".into();
13498 owner.save_under(home.path()).unwrap();
13499 let mut successor = run_state(RunStatus::Blocked);
13500 successor.id = "20260101-000001-bbbb".into();
13501 successor.save_under(home.path()).unwrap();
13502 let runs = vec![owner.id.clone(), successor.id.clone()];
13503 assert_eq!(
13504 public_resume_owner(home.path(), &runs, &owner.repo)
13505 .await
13506 .unwrap()
13507 .unwrap()
13508 .id,
13509 owner.id
13510 );
13511 let subdir = owner.repo.join("nested");
13512 std::fs::create_dir(&subdir).unwrap();
13513 assert_eq!(
13514 public_resume_owner(home.path(), &runs, &subdir)
13515 .await
13516 .unwrap()
13517 .unwrap()
13518 .id,
13519 owner.id
13520 );
13521 #[cfg(unix)]
13522 {
13523 let alias = home.path().join("repo-alias");
13524 std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
13525 assert_eq!(
13526 public_resume_owner(home.path(), &runs, &alias.join("nested"))
13527 .await
13528 .unwrap()
13529 .unwrap()
13530 .id,
13531 owner.id
13532 );
13533 }
13534 let different = tempfile::tempdir().unwrap();
13535 crate::git::git(different.path(), &["init"]).await.unwrap();
13536 assert!(
13537 public_resume_owner(home.path(), &runs, different.path())
13538 .await
13539 .is_err()
13540 );
13541 std::fs::remove_file(
13542 home.path()
13543 .join("runs")
13544 .join(&successor.id)
13545 .join("run.json"),
13546 )
13547 .unwrap();
13548 assert!(
13549 public_resume_owner(home.path(), &runs, &owner.repo)
13550 .await
13551 .is_err()
13552 );
13553 }
13554
13555 #[test]
13556 fn an_ordinary_release_keeps_a_resumable_run_available() {
13557 let mut released = task();
13558 released.start("stalled-run".to_owned());
13559 released.release();
13560 let unfinished = (!released.fresh_start)
13561 .then(|| Some("stalled-run".to_owned()))
13562 .flatten();
13563 assert_eq!(
13564 choose_starter(None, false, unfinished.as_deref()),
13565 Starter::Resume("stalled-run".to_owned()),
13566 "manual release must preserve the normal resume path"
13567 );
13568 }
13569
13570 #[test]
13571 fn resume_refusals_explain_admission_without_changing_task_or_run() {
13572 use crate::handover::{ResumeRefusal, resume_refusal_under};
13573 let home = tempfile::tempdir().unwrap();
13574 let mut exhausted = run_state(RunStatus::Blocked);
13575 exhausted.driver_exited = true;
13576 exhausted.config.graph.review_rounds = 3;
13577 exhausted.reviews = (1..=3).map(review_round).collect();
13578 for refusal in [
13579 ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
13580 ResumeRefusal::Status(RunStatus::Ready),
13581 ResumeRefusal::Released("20261022-000000-aaaa".into()),
13582 ResumeRefusal::Retired("retirement-successor".into()),
13583 ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
13584 ] {
13585 let mut state = exhausted.clone();
13586 let expected = match refusal {
13587 ResumeRefusal::Status(_) => {
13588 state.status = RunStatus::Ready;
13589 "status `ready`"
13590 }
13591 ResumeRefusal::Released(ref target) => {
13592 state.released_to = Some(target.clone());
13593 "execution was released"
13594 }
13595 ResumeRefusal::Retired(ref target) => {
13596 state.retired_to = Some(target.clone());
13597 "execution was retired"
13598 }
13599 ResumeRefusal::OwnershipTransferred(ref target) => {
13600 state.pr_taken_over_by = Some(target.clone());
13601 "PR ownership was transferred"
13602 }
13603 _ => "review budget exhausted (3/3 rounds used)",
13604 };
13605 assert_eq!(
13606 resume_refusal_under(&state, Some(home.path())),
13607 Some(refusal.clone())
13608 );
13609 assert_eq!(
13610 refusal.successor(),
13611 state
13612 .released_to
13613 .as_deref()
13614 .or(state.retired_to.as_deref())
13615 .or(state.pr_taken_over_by.as_deref())
13616 );
13617 state.save_under(home.path()).unwrap();
13618 let queue = Queue::at(home.path().join("queue"));
13619 let mut task = Task::new(
13620 "retained implementation".into(),
13621 state.instruction.clone(),
13622 state.repo.clone(),
13623 Source::Agent {
13624 run: "talk".into(),
13625 node: crate::queue::CHAT_NODE.into(),
13626 },
13627 );
13628 task.runs.push(state.id.clone());
13629 task.hold_machine(Some("stopped".into()));
13630 queue.put(&mut task).unwrap();
13631 let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
13632 let before_run = serde_json::to_value(&state).unwrap();
13633 let error = crate::chat_control::resume(&queue, home.path(), &state.id)
13634 .unwrap_err()
13635 .to_string();
13636 assert!(error.contains(expected), "{error}");
13637 assert!(!error.contains("only a stalled or blocked"), "{error}");
13638 if matches!(refusal, ResumeRefusal::Status(_)) {
13639 assert!(
13640 error.contains("is final; there is nothing left to resume"),
13641 "{error}"
13642 );
13643 }
13644 if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
13645 assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
13646 assert!(error.contains("review-only successor with a new review budget"));
13647 assert!(error.contains("does not resume this run"));
13648 }
13649 for target in [
13650 &state.released_to,
13651 &state.retired_to,
13652 &state.pr_taken_over_by,
13653 ]
13654 .into_iter()
13655 .flatten()
13656 {
13657 let short = if state.retired_to.as_ref() == Some(target) {
13658 target.as_str()
13659 } else {
13660 crate::run::short_of(target)
13661 };
13662 assert!(
13663 error.contains(&format!("run {short}; inspect `magi show {short}`")),
13664 "{error}"
13665 );
13666 if short != target {
13667 assert!(!error.contains(target), "full successor id leaked: {error}");
13668 }
13669 }
13670 assert_eq!(
13671 serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
13672 before_task
13673 );
13674 assert_eq!(
13675 serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
13676 .unwrap(),
13677 before_run
13678 );
13679 let question = action_question(&state.id, resume_action(&state.id));
13680 for phrases in [&PHRASES_EN, &PHRASES_JA] {
13681 let decision = decide_action(home.path(), &task, &question, phrases, |id| {
13682 RunState::load_under(id, home.path())
13683 });
13684 let ActionDecision::Refuse(detail) = decision else {
13685 panic!(
13686 "refusal expected: decision={decision:?}, refusal={refusal:?}, run={}, home={}",
13687 state.id,
13688 home.path().display()
13689 );
13690 };
13691 assert!(detail.contains(expected), "{detail}");
13692 }
13693 }
13694 exhausted.status = RunStatus::Ready;
13696 exhausted.released_to = Some("released".into());
13697 exhausted.retired_to = Some("retired".into());
13698 exhausted.pr_taken_over_by = Some("owner".into());
13699 let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
13700 assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
13701 let detail = reason.diagnostic(&exhausted);
13702 for target in ["released", "retired", "owner"] {
13703 assert!(detail.contains(&format!("magi show {target}")));
13704 }
13705 }
13706
13707 #[test]
13708 fn resume_action_ignores_question_checkpoints_in_another_home() {
13709 crate::run::pin_test_home();
13710 let home = tempfile::tempdir().unwrap();
13711 let mut state = run_state(RunStatus::Blocked);
13712 state.id = format!(
13715 "resume-context-{}",
13716 home.path().file_name().unwrap().to_str().unwrap()
13717 );
13718 state.driver_exited = true;
13719 state.config.graph.review_rounds = 1;
13720 state.reviews = vec![review_round(1)];
13721 state.save_under(home.path()).unwrap();
13722 let task = held_task_with(&state.id);
13723 let answer = action_question(&state.id, resume_action(&state.id));
13724 let mut checkpoint = approval_question(&state.id);
13725 let foreign = Questions::open();
13726 foreign.put(&mut checkpoint).unwrap();
13727 let refusal = crate::handover::resume_refusal_under(&state, Some(home.path()));
13728 let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
13729 RunState::load_under(id, home.path())
13730 });
13731 let matching: Vec<_> = foreign
13732 .list()
13733 .into_iter()
13734 .filter(|q| q.run == state.id && q.status.open())
13735 .collect();
13736 std::fs::remove_file(foreign.path_of(&checkpoint.id)).unwrap();
13737 assert!(
13738 matches!(decision, ActionDecision::Refuse(_)),
13739 "decision={decision:?}, refusal={refusal:?}, run={}, home={}, foreign_home={}, matching={matching:?}",
13740 state.id,
13741 home.path().display(),
13742 crate::run::test_home().display()
13743 );
13744 assert_eq!(
13745 refusal,
13746 Some(crate::handover::ResumeRefusal::ReviewBudget { used: 1, limit: 1 })
13747 );
13748 let local = Questions::at(home.path().join("questions"));
13749 for status in [
13750 ask::QuestionStatus::Open,
13751 ask::QuestionStatus::Answered,
13752 ask::QuestionStatus::Abandoned,
13753 ] {
13754 let mut question = checkpoint.clone();
13755 match status {
13756 ask::QuestionStatus::Open => {}
13757 ask::QuestionStatus::Answered => {
13758 question
13759 .answer(ask::Answer::Choice(question.choices[0].clone()))
13760 .unwrap();
13761 }
13762 ask::QuestionStatus::Abandoned => question.abandon("fixture closed"),
13763 }
13764 local.put(&mut question).unwrap();
13765 let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
13766 RunState::load_under(id, home.path())
13767 });
13768 if status.open() {
13769 assert_eq!(decision, ActionDecision::Resume(state.id.clone()));
13770 } else {
13771 assert!(
13772 matches!(decision, ActionDecision::Refuse(ref detail) if detail.contains("review budget exhausted")),
13773 "status={status:?}, decision={decision:?}"
13774 );
13775 }
13776 }
13777 }
13778
13779 #[test]
13780 fn resume_action_checks_the_driver_lease_in_the_supplied_home() {
13781 let home = tempfile::tempdir().unwrap();
13782 let mut state = run_state(RunStatus::Stalled);
13783 state.id = format!(
13784 "resume-driver-{}",
13785 home.path().file_name().unwrap().to_str().unwrap()
13786 );
13787 state.driver_claimed = Some(false);
13788 state.save_under(home.path()).unwrap();
13789 let task = held_task_with(&state.id);
13790 let question = action_question(&state.id, resume_action(&state.id));
13791 let decide = || {
13792 decide_action(home.path(), &task, &question, &PHRASES_EN, |id| {
13793 RunState::load_under(id, home.path())
13794 })
13795 };
13796 let lease = crate::driver::maintenance(home.path(), &state.id).unwrap();
13797 assert_eq!(state.liveness_under(home.path(), false), Liveness::Live);
13798 assert_eq!(
13799 decide(),
13800 ActionDecision::Refuse("run already has a live driver".into())
13801 );
13802 drop(lease);
13803 assert_eq!(decide(), ActionDecision::Resume(state.id.clone()));
13804 }
13805
13806 #[test]
13807 fn resume_checkpoint_admission_uses_the_supplied_question_store() {
13808 let home = tempfile::tempdir().unwrap();
13809 let mut state = run_state(RunStatus::Blocked);
13810 state.driver_exited = true;
13811 state.config.graph.review_rounds = 1;
13812 state.reviews = vec![review_round(1)];
13813 assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
13814 for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
13815 let mut saved = state.clone();
13816 match checkpoint {
13817 "publication" => saved.pr_publication_pending = true,
13818 "approval" => {
13819 saved.land_approval = Some(crate::run::LandApproval {
13820 question: "approval".into(),
13821 head: "head".into(),
13822 })
13823 }
13824 "armed" => saved.land_armed_head = Some("head".into()),
13825 "landing" => saved.status = RunStatus::Landing,
13826 _ => {
13827 let mut question = ask::Question::new(
13828 saved.id.clone(),
13829 "review".into(),
13830 "review-1".into(),
13831 "continue?".into(),
13832 String::new(),
13833 vec!["continue".into()],
13834 );
13835 ask::Questions::at(home.path().join("questions"))
13836 .put(&mut question)
13837 .unwrap();
13838 }
13839 }
13840 saved.save_under(home.path()).unwrap();
13841 assert!(
13842 crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
13843 "{checkpoint}"
13844 );
13845 assert!(
13846 crate::resume::validate(home.path(), &saved.id).is_ok(),
13847 "{checkpoint}"
13848 );
13849 }
13850 }
13851
13852 #[test]
13853 fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
13854 let mut state = run_state(RunStatus::Blocked);
13855 state.config.graph.review_rounds = 3;
13856 state.reviews = vec![review_round(1), review_round(2), review_round(3)];
13857 assert!(exhausted_review_budget(&state));
13858
13859 state.reviews.pop();
13861 assert!(!exhausted_review_budget(&state));
13862
13863 let mut stalled = run_state(RunStatus::Stalled);
13866 stalled.config.graph.review_rounds = 1;
13867 stalled.reviews = vec![review_round(1)];
13868 assert!(!exhausted_review_budget(&stalled));
13869 }
13870
13871 fn review_round(round: usize) -> crate::run::ReviewRound {
13872 crate::run::ReviewRound {
13873 round,
13874 head: "deadbeef".to_owned(),
13875 verified_head: None,
13876 verified_at: None,
13877 reviews: Vec::new(),
13878 e2e: Vec::new(),
13879 verify_retried: false,
13880 e2e_deferred: false,
13881 e2e_defer_reason: None,
13882 fix: None,
13883 blocking: 0,
13884 answered: 1,
13885 expected: 1,
13886 clean: false,
13887 progressed: true,
13888 vote_split: false,
13889 reconsideration: Vec::new(),
13890 verdict: None,
13891 }
13892 }
13893
13894 #[test]
13895 fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
13896 let mut run = RunState::new(
13897 PathBuf::from("/repo"),
13898 "main".to_owned(),
13899 "abc1234def".to_owned(),
13900 "add retries".to_owned(),
13901 Config::default(),
13902 );
13903 run.status = RunStatus::Judging;
13904 run.parked = true;
13905 let mut task = Task::new(
13906 "add retries".to_owned(),
13907 "add retries".to_owned(),
13908 PathBuf::from("/repo"),
13909 crate::queue::Source::Human,
13910 );
13911 task.status = TaskStatus::Failed;
13912 task.runs = vec![run.id.clone()];
13913 let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
13914 assert!(with(&task, &run), "parked after judging is the case");
13915 let mut parked_task = task.clone();
13916 parked_task.status = TaskStatus::Parked;
13917 assert!(with(&parked_task, &run), "the Parked status is the case");
13918
13919 let mut not_parked = run.clone();
13920 not_parked.parked = false;
13921 not_parked.status = RunStatus::Stalled;
13922 assert!(!with(&task, ¬_parked), "a stall is the conductor's");
13923
13924 let mut fresh = task.clone();
13925 fresh.fresh_start = true;
13926 assert!(!with(&fresh, &run), "a requeue asked for a new competition");
13927
13928 let mut review = task.clone();
13929 review.review_branch = Some("magi/x/A".to_owned());
13930 assert!(!with(&review, &run), "review is ranked before resume");
13931
13932 let mut held = task.clone();
13933 held.status = TaskStatus::Held;
13934 assert!(!with(&held, &run), "a hold stays visible to the conductor");
13935
13936 let mut released = run.clone();
13937 released.released_to = Some("20260901-000000-new1".to_owned());
13938 assert!(!with(&task, &released), "nothing left to resume into");
13939
13940 assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
13941 "unreadable"
13942 )));
13943 }
13944
13945 #[test]
13946 fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
13947 let mut released = RunState::new(
13948 PathBuf::from("/repo"),
13949 "main".to_owned(),
13950 "abc1234def".to_owned(),
13951 "add retries".to_owned(),
13952 Config::default(),
13953 );
13954 released.status = RunStatus::Blocked;
13955 assert_eq!(
13956 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
13957 Some(released.id.clone())
13958 );
13959 released.released_to = Some("20260901-000000-new1".to_owned());
13960 assert_eq!(
13961 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
13962 None,
13963 "there is nothing left to resume it into"
13964 );
13965 }
13966
13967 #[test]
13968 fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
13969 let mut exhausted = RunState::new(
13978 PathBuf::from("/repo"),
13979 "main".to_owned(),
13980 "abc1234def".to_owned(),
13981 "add retries".to_owned(),
13982 Config::default(),
13983 );
13984 exhausted.status = RunStatus::Blocked;
13985 exhausted.config.graph.review_rounds = 1;
13986 exhausted.reviews = vec![review_round(1)];
13987
13988 assert_eq!(
13989 unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
13990 None,
13991 "an exhausted `Blocked` run must not be offered as resumable"
13992 );
13993
13994 let mut has_budget_left = RunState::new(
13997 PathBuf::from("/repo"),
13998 "main".to_owned(),
13999 "abc1234def".to_owned(),
14000 "add retries".to_owned(),
14001 Config::default(),
14002 );
14003 has_budget_left.status = RunStatus::Blocked;
14004 has_budget_left.config.graph.review_rounds = 3;
14005 has_budget_left.reviews = vec![review_round(1)];
14006
14007 assert_eq!(
14008 unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
14009 Ok(has_budget_left.clone())
14010 }),
14011 Some(has_budget_left.id.clone())
14012 );
14013 }
14014
14015 #[test]
14016 fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
14017 let mut run = RunState::new(
14018 PathBuf::from("/repo"),
14019 "main".to_owned(),
14020 "abc1234def".to_owned(),
14021 "add retries".to_owned(),
14022 Config::default(),
14023 );
14024 run.status = RunStatus::Blocked;
14025 run.config.graph.review_rounds = 1;
14026 run.reviews = vec![review_round(1)];
14027 run.pr_publication_pending = true;
14028 assert_eq!(
14029 unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
14030 Some(run.id.clone()),
14031 "a spent review budget must not turn a failed publication into a re-competition"
14032 );
14033 }
14034
14035 #[test]
14036 fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
14037 let mut task = Task::new(
14038 "recover work".into(),
14039 "recover work".into(),
14040 PathBuf::from("/repo"),
14041 crate::queue::Source::Human,
14042 );
14043 let mut history = std::collections::BTreeMap::new();
14044 for index in 0..8 {
14045 let mut run = run_state(RunStatus::Blocked);
14046 run.id = format!("20260101-000000-{index:04}");
14047 run.base_commit = format!("upstream-{index}");
14048 if index > 0 {
14050 run.candidates.clear();
14051 }
14052 task.runs.extend([run.id.clone(), run.id.clone()]);
14053 history.insert(run.id.clone(), run);
14054 task.requeue();
14055 }
14056 let check = |task: &Task, starter: &Starter, limit| {
14057 retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
14058 };
14059 assert!(
14060 check(&task, &Starter::Start, 8)
14061 .unwrap()
14062 .contains("8 unretired")
14063 );
14064 assert!(check(&task, &Starter::Start, 9).is_none());
14065 assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
14066 task.release_operator("owner", None);
14067 assert_eq!(task.attempts, 0);
14068 let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
14069 assert!(check(&restored, &Starter::Start, 8).is_some());
14070 assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
14071 assert!(check(&restored, &Starter::Start, 0).is_none());
14072 }
14073
14074 #[test]
14075 fn retained_attempt_bound_includes_failed_startups_without_execution_history() {
14076 let tmp = tempfile::tempdir().unwrap();
14077 let mut task = Task::new(
14078 "recover selected PR".into(),
14079 "preserve implementation".into(),
14080 tmp.path().join("repo"),
14081 crate::queue::Source::Human,
14082 );
14083 let mut failed = run_state(RunStatus::Failed);
14084 failed.id = "20260101-000000-fail".into();
14085 failed.candidates.clear();
14086 failed.prep_complete = Some(false);
14087 failed.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
14088 failed.startup = Some(crate::run::Startup {
14089 kind: "pr-recovery".into(),
14090 branch: Some("selected-public-head".into()),
14091 stage: "worktree-setup".into(),
14092 complete: false,
14093 failure: Some("setup modified a tracked file and failed".into()),
14094 });
14095 let worktree = failed.worktree_root().join("under-review");
14098 std::fs::create_dir_all(&worktree).unwrap();
14099 let retained_edit = worktree.join("implementation");
14100 std::fs::write(&retained_edit, "retained setup edit").unwrap();
14101 task.record_startup_failure(crate::run::StartupFailure {
14102 run: failed.id.clone(),
14103 stage: "worktree-setup".into(),
14104 });
14105 let task: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
14106 assert!(task.runs.is_empty() && task.passes.is_empty());
14107 assert_eq!(task.attempts, 0);
14108 let starter = Starter::Review("selected-public-head".into());
14109 assert!(
14110 retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone()))
14111 .unwrap()
14112 .contains("1 unretired")
14113 );
14114 assert!(retained_attempt_hold(&task, &starter, 2, |_| Ok(failed.clone())).is_none());
14115 assert!(
14116 retained_attempt_hold(&task, &starter, 2, |_| anyhow::bail!("unreadable"))
14117 .unwrap()
14118 .contains("Cannot verify")
14119 );
14120 let mut mixed = task.clone();
14122 mixed.runs.push(failed.id.clone());
14123 mixed
14124 .startup_failures
14125 .push(task.startup_failures[0].clone());
14126 assert!(retained_attempt_hold(&mixed, &starter, 2, |_| Ok(failed.clone())).is_none());
14127 failed.retired_to = Some("verified-recovery-owner".into());
14128 assert!(retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone())).is_none());
14129 assert!(
14130 retained_attempt_hold(&task, &Starter::Resume(failed.id.clone()), 1, |_| {
14131 panic!("resuming the existing owner must not allocate a new attempt")
14132 })
14133 .is_none()
14134 );
14135 assert_eq!(
14136 std::fs::read_to_string(retained_edit).unwrap(),
14137 "retained setup edit"
14138 );
14139 assert!(task.runs.is_empty() && task.passes.is_empty());
14140 assert_eq!(task.attempts, 0);
14141 }
14142
14143 #[test]
14144 fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
14145 let mut task = Task::new(
14146 "recover work".into(),
14147 "recover work".into(),
14148 PathBuf::from("/repo"),
14149 crate::queue::Source::Human,
14150 );
14151 let mut run = run_state(RunStatus::Superseded);
14152 run.candidates.clear();
14153 task.runs.push(run.id.clone());
14154 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
14155 run.retired_to = Some("authority".into());
14156 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
14157 run.retired_to = None;
14158 run.released_to = Some("authority".into());
14159 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
14160 assert!(
14161 retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
14162 .unwrap()
14163 .contains("Cannot verify")
14164 );
14165 assert!(
14167 retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
14168 panic!("resume must not load historical attempts")
14169 })
14170 .is_none()
14171 );
14172 }
14173
14174 #[test]
14175 fn retired_resume_requires_a_valid_same_repository_authority() {
14176 let mut source = run_state(RunStatus::Blocked);
14177 let mut empty = run_state(RunStatus::Blocked);
14178 empty.retired_to = Some(source.id.clone());
14179 let runs = vec![source.id.clone(), empty.id.clone()];
14180 let resolve = |source: &RunState, empty: &RunState| {
14181 unfinished_run_with(&runs, "fixture", |id| {
14182 if id == source.id {
14183 Ok(source.clone())
14184 } else if id == empty.id {
14185 Ok(empty.clone())
14186 } else {
14187 bail!("unreadable authority")
14188 }
14189 })
14190 };
14191 assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
14192 assert_eq!(
14193 choose_starter(None, false, resolve(&source, &empty).as_deref()),
14194 Starter::Resume(source.id.clone())
14195 );
14196 source.retired_to = Some(empty.id.clone());
14197 assert!(
14198 resolve(&source, &empty).is_none(),
14199 "cycles do not revive obsolete runs"
14200 );
14201 source.retired_to = None;
14202 source.repo = PathBuf::from("/another-repository");
14203 assert!(resolve(&source, &empty).is_none());
14204 source.repo = empty.repo.clone();
14205 source.released_to = Some("later".into());
14206 assert!(resolve(&source, &empty).is_none());
14207 empty.retired_to = Some("unlisted-run".into());
14208 assert!(resolve(&source, &empty).is_none());
14209 }
14210
14211 #[test]
14212 fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
14213 let mut older_stalled = RunState::new(
14221 PathBuf::from("/repo"),
14222 "main".to_owned(),
14223 "abc1234def".to_owned(),
14224 "add retries".to_owned(),
14225 Config::default(),
14226 );
14227 older_stalled.status = RunStatus::Stalled;
14228
14229 let mut newest_exhausted = RunState::new(
14230 PathBuf::from("/repo"),
14231 "main".to_owned(),
14232 "abc1234def".to_owned(),
14233 "add retries".to_owned(),
14234 Config::default(),
14235 );
14236 newest_exhausted.status = RunStatus::Blocked;
14237 newest_exhausted.config.graph.review_rounds = 1;
14238 newest_exhausted.reviews = vec![review_round(1)];
14239
14240 assert_eq!(
14241 unfinished_run_with(
14242 &[older_stalled.id.clone(), newest_exhausted.id.clone()],
14243 "t",
14244 |_| Ok(newest_exhausted.clone())
14245 ),
14246 None,
14247 "the newest run is exhausted, so nothing here is worth resuming - \
14248 least of all the older, already-superseded run"
14249 );
14250 }
14251
14252 #[test]
14253 fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
14254 assert_eq!(
14255 unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
14256 Err(anyhow::anyhow!("fixture is absent"))
14257 }),
14258 None
14259 );
14260 }
14261
14262 fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
14263 let mut q = ask::Question::new(
14264 run.to_owned(),
14265 "implement".to_owned(),
14266 "impl-A".to_owned(),
14267 "continue?".to_owned(),
14268 String::new(),
14269 vec!["resume で続行する".to_owned(), "other".to_owned()],
14270 );
14271 q.actions.insert("resume で続行する".to_owned(), action);
14272 q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
14273 .unwrap();
14274 q
14275 }
14276
14277 fn held_task_with(run: &str) -> Task {
14278 let mut t = task();
14279 t.runs = vec![run.to_owned()];
14280 t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
14281 t
14282 }
14283
14284 fn resume_action(run: &str) -> ask::ChoiceAction {
14285 ask::ChoiceAction::Resume { run: run.into() }
14286 }
14287
14288 #[test]
14289 fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
14290 let home = crate::run::test_home();
14291 for parked in [false, true] {
14292 let mut t = task();
14293 t.start("A".into());
14294 t.start("B".into());
14295 assert_eq!(t.runs, vec!["A", "B"]);
14296 t.start("A".into());
14297 let mut resumed = run_state(RunStatus::Blocked);
14298 resumed.id = "A".into();
14299 resumed.parked = parked;
14300 resumed.driver_exited = true;
14301 t.hold_machine(Some("resumed run stopped".into()));
14302 let q = action_question("A", resume_action("A"));
14303 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
14304 assert_eq!(
14305 decide_action(&home, &t, &q, &PHRASES_EN, |id| {
14306 assert_eq!(id, "A");
14307 Ok(resumed.clone())
14308 }),
14309 ActionDecision::Resume("A".into())
14310 );
14311 assert_eq!(
14312 action_standing(&t, &action_question("B", resume_action("B"))),
14313 ActionStanding::Stale
14314 );
14315 t.release_operator("cli", None);
14316 let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
14317 assert_eq!(id, "A");
14318 Ok(resumed.clone())
14319 });
14320 assert_eq!(
14321 choose_starter(None, false, unfinished.as_deref()),
14322 Starter::Resume("A".into())
14323 );
14324 assert_eq!(t.runs, vec!["B", "A"]);
14325 }
14326 }
14327
14328 #[test]
14329 fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
14330 let home = crate::run::test_home();
14331 let mut state = crate::land::tests::repair_state(true, true);
14332 state.status = RunStatus::Landing;
14333 state.parked = true;
14334 state.driver_exited = true;
14335 let mut q = ask::Question::new(
14336 state.id.clone(),
14337 land::APPROVAL_NODE.into(),
14338 "land".into(),
14339 "Merge?".into(),
14340 String::new(),
14341 vec![land::APPROVE.into(), land::HOLD.into()],
14342 );
14343 q.id = state.id.clone();
14344 state.land_approval = Some(crate::run::LandApproval {
14345 question: q.id.clone(),
14346 head: "current-head".into(),
14347 });
14348 assert!(land::upgrade_repair_choice(&mut q, &state));
14349 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14350 let mut task = held_task_with(&state.id);
14351 task.status = TaskStatus::Parked;
14352 assert_eq!(
14353 decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
14354 ActionDecision::Resume(state.id.clone())
14355 );
14356 q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
14357 q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
14358 task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
14359 assert_eq!(
14360 decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
14361 ActionDecision::Resume(state.id.clone()),
14362 "a repair answer newer than the manual hold resumes the existing owner"
14363 );
14364 task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
14365 for answered_at in [q.answered_at, None] {
14366 let mut older = q.clone();
14367 older.answered_at = answered_at;
14368 let refused = decide_action(&home, &task, &older, &PHRASES_EN, |_| {
14369 panic!("a later manual hold must prevent dispatch")
14370 });
14371 let ActionDecision::Refuse(reason) = refused else {
14372 panic!("expected an actionable refusal, got {refused:?}");
14373 };
14374 assert!(reason.contains("later operator decision"));
14375 assert!(reason.contains(&format!("magi task release {}", task.id)));
14376 }
14377 task.operator_decided_at = None;
14378 let mut superseded = state.clone();
14379 superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
14380 assert_eq!(
14381 decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(superseded)),
14382 ActionDecision::Stale
14383 );
14384 for case in 1..4 {
14385 let mut changed = state.clone();
14386 match case {
14387 1 => changed.status = RunStatus::Blocked,
14388 2 => changed.released_to = Some("new-owner".into()),
14389 _ => changed.land_approval.as_mut().unwrap().head.clear(),
14390 }
14391 assert!(matches!(
14392 decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(changed)),
14393 ActionDecision::Refuse(_)
14394 ));
14395 }
14396 assert!(matches!(
14397 decide_action(&home, &task, &q, &PHRASES_EN, |_| anyhow::bail!(
14398 "missing owner"
14399 )),
14400 ActionDecision::Refuse(_)
14401 ));
14402 task.runs.push("replacement".into());
14403 task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
14404 assert_eq!(
14405 decide_action(&home, &task, &q, &PHRASES_EN, |_| panic!(
14406 "old owner must not load"
14407 )),
14408 ActionDecision::Stale
14409 );
14410 }
14411
14412 #[test]
14413 fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
14414 let mut state = crate::land::tests::repair_state(true, true);
14415 state.status = RunStatus::Landing;
14416 state.parked = true;
14417 state.driver_exited = true;
14418 let mut q = ask::Question::new(
14419 state.id.clone(),
14420 land::APPROVAL_NODE.into(),
14421 "land".into(),
14422 "Merge?".into(),
14423 String::new(),
14424 vec![land::APPROVE.into(), land::HOLD.into()],
14425 );
14426 q.id = state.id.clone();
14427 state.land_approval = Some(crate::run::LandApproval {
14428 question: q.id.clone(),
14429 head: "current-head".into(),
14430 });
14431 state.save().unwrap();
14432 land::upgrade_repair_choice(&mut q, &state);
14433 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14434 Questions::open().put(&mut q).unwrap();
14435 let tmp = tempfile::tempdir().unwrap();
14436 let queue = Queue::at(tmp.path().join("queue"));
14437 let mut task = held_task_with(&state.id);
14438 task.status = TaskStatus::Parked;
14439 queue.put(&mut task).unwrap();
14440 let empty = Arc::new(tokio::sync::Semaphore::new(0));
14441 let free = Arc::new(tokio::sync::Semaphore::new(1));
14442 assert!(matches!(
14443 claim_dispatch(&queue, &task, false, &empty, &free),
14444 Err(SkipReason::OrdinaryCapacity)
14445 ));
14446 assert!(matches!(
14447 claim_dispatch(&queue, &task, true, &free, &free),
14448 Err(SkipReason::CoolingDown)
14449 ));
14450 let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
14451 assert!(claim.permit.is_some());
14452 assert!(matches!(
14453 claim_dispatch(&queue, &task, false, &free, &free),
14454 Err(SkipReason::ClaimUnavailable)
14455 ));
14456 drop(claim);
14457 Questions::open()
14458 .update(&q.id, |q| {
14459 q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
14460 Ok(())
14461 })
14462 .unwrap();
14463 let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
14464 assert!(claim.permit.is_none());
14465 assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
14466 }
14467
14468 #[test]
14469 fn decide_action_resumes_only_the_latest_resumable_run() {
14470 let home = crate::run::test_home();
14471 let t = held_task_with("r1");
14472 let q = action_question("r1", resume_action("r1"));
14473 let load = |s: RunState| move |_: &str| Ok(s);
14474 assert_eq!(
14475 decide_action(
14476 &home,
14477 &t,
14478 &q,
14479 &PHRASES_EN,
14480 load(run_state(RunStatus::Blocked))
14481 ),
14482 ActionDecision::Resume("r1".into())
14483 );
14484 let q_other = action_question("r1", resume_action("r0"));
14486 assert!(matches!(
14487 decide_action(
14488 &home,
14489 &t,
14490 &q_other,
14491 &PHRASES_EN,
14492 load(run_state(RunStatus::Blocked))
14493 ),
14494 ActionDecision::Refuse(_)
14495 ));
14496 assert!(matches!(
14498 decide_action(
14499 &home,
14500 &t,
14501 &q,
14502 &PHRASES_EN,
14503 load(run_state(RunStatus::Ready))
14504 ),
14505 ActionDecision::Refuse(_)
14506 ));
14507 let mut released = run_state(RunStatus::Blocked);
14509 released.released_to = Some("elsewhere".into());
14510 assert!(matches!(
14511 decide_action(&home, &t, &q, &PHRASES_EN, load(released)),
14512 ActionDecision::Refuse(_)
14513 ));
14514 assert!(matches!(
14516 decide_action(&home, &t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
14517 ActionDecision::Refuse(_)
14518 ));
14519 }
14520
14521 #[test]
14522 fn decide_action_ignores_a_question_about_an_earlier_run() {
14523 let home = crate::run::test_home();
14524 let mut t = held_task_with("r1");
14525 t.runs.push("r2".to_owned());
14526 let never = |_: &str| -> Result<RunState> { bail!("not read") };
14527 assert_eq!(
14528 decide_action(
14529 &home,
14530 &t,
14531 &action_question("r1", ask::ChoiceAction::Done),
14532 &PHRASES_EN,
14533 never
14534 ),
14535 ActionDecision::Stale
14536 );
14537 }
14538
14539 #[test]
14540 fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
14541 let home = crate::run::test_home();
14542 let mut t = held_task_with("r1");
14543 let never = |_: &str| -> Result<RunState> { bail!("not read") };
14544 assert_eq!(
14545 decide_action(
14546 &home,
14547 &t,
14548 &action_question("r1", ask::ChoiceAction::Requeue),
14549 &PHRASES_EN,
14550 never
14551 ),
14552 ActionDecision::Requeue
14553 );
14554 let done_q = action_question("r1", ask::ChoiceAction::Done);
14555 assert_eq!(
14556 decide_action(&home, &t, &done_q, &PHRASES_EN, never),
14557 ActionDecision::Done
14558 );
14559 t.mark_action_applied(&done_q.id);
14560 assert_eq!(
14561 decide_action(&home, &t, &done_q, &PHRASES_EN, never),
14562 ActionDecision::Skip
14563 );
14564
14565 let mut plain = action_question("r1", ask::ChoiceAction::Done);
14567 plain.actions.clear();
14568 assert_eq!(
14569 decide_action(&home, &held_task_with("r1"), &plain, &PHRASES_EN, never),
14570 ActionDecision::Skip
14571 );
14572 let mut running = held_task_with("r1");
14574 running.status = TaskStatus::Running;
14575 assert_eq!(
14576 decide_action(
14577 &home,
14578 &running,
14579 &action_question("r1", ask::ChoiceAction::Done),
14580 &PHRASES_EN,
14581 never
14582 ),
14583 ActionDecision::Skip
14584 );
14585 }
14586
14587 #[test]
14588 fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
14589 crate::run::pin_test_home();
14590 for legacy in [false, true] {
14591 let dir = tempfile::tempdir().unwrap();
14592 let queue = Queue::at(dir.path().join("queue"));
14593 let questions = Questions::at(dir.path().join("questions"));
14594 let run = "20260101-000000-hold";
14595 let mut task = held_task_with(run);
14596 task.status = TaskStatus::Parked;
14597 let mut q = ask::Question::new(
14598 run.into(),
14599 land::APPROVAL_NODE.into(),
14600 "land".into(),
14601 "Repair?".into(),
14602 String::new(),
14603 vec![land::REPAIR.into()],
14604 );
14605 q.actions.insert(land::REPAIR.into(), resume_action(run));
14606 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14607 q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
14609 q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
14610 questions.put(&mut q).unwrap();
14611 task.hold_manual(Some("Keep this PR paused".into()));
14612 if legacy {
14613 task.hold_source = None;
14614 }
14615 queue.put(&mut task).unwrap();
14616
14617 apply_task_choice_actions(&queue, &questions, dir.path());
14618 let after = queue.get(&task.id).unwrap();
14619 assert!(after.operator_held());
14620 assert_eq!(after.hold_source, task.hold_source);
14621 assert_eq!(after.operator_decided_at, task.operator_decided_at);
14622 assert_eq!(after.runs, task.runs);
14623 assert_eq!(after.instruction, task.instruction);
14624 assert!(after.resume_override.is_none());
14625 assert!(after.action_applied(&q.id));
14626 let reason = after.hold_reason.as_deref().unwrap();
14627 assert!(reason.starts_with("Keep this PR paused"));
14628 assert!(reason.contains("later operator decision"));
14629 assert!(reason.contains(&format!("magi task release {}", task.id)));
14630
14631 for recovery in [
14632 crate::conduct::Recovery::Review,
14633 crate::conduct::Recovery::Requeue,
14634 ] {
14635 crate::conduct::apply(
14636 &queue,
14637 &questions,
14638 &crate::conduct::Verdict {
14639 decisions: vec![crate::conduct::Decision {
14640 id: task.id.clone(),
14641 recovery: Some(recovery),
14642 ..Default::default()
14643 }],
14644 },
14645 )
14646 .unwrap();
14647 }
14648 apply_task_choice_actions(&queue, &questions, dir.path());
14651 let still_held = queue.get(&task.id).unwrap();
14652 assert!(still_held.operator_held());
14653 assert_eq!(still_held.hold_reason, after.hold_reason);
14654 assert_eq!(still_held.runs, task.runs);
14655 assert!(still_held.review_branch.is_none());
14656 assert!(!still_held.fresh_start);
14657 assert!(queue.next_runnable().is_none());
14658 }
14659 }
14660
14661 #[test]
14662 fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
14663 for held in [false, true] {
14664 for retry in [false, true] {
14665 let dir = tempfile::tempdir().unwrap();
14666 let queue = Queue::at(dir.path().join("queue"));
14667 let questions = Questions::at(dir.path().join("questions"));
14668 let home = dir.path().join("home");
14669 let mut t = task();
14670 if held {
14671 t.hold_machine(Some("driver state unknown".into()));
14672 }
14673 queue.put(&mut t).unwrap();
14674 let verdict = serde_json::from_value(serde_json::json!({
14675 "decisions": [{
14676 "id": t.id,
14677 "question": "Driver state unknown; retry the checks or hold?",
14678 "choices": ["daemon: recheck and retry", "daemon: hold the task"],
14679 "actions": {
14680 "daemon: recheck and retry": {"do": "requeue"},
14681 "daemon: hold the task": {"do": "hold"}
14682 }
14683 }]
14684 }))
14685 .unwrap();
14686 crate::conduct::apply(&queue, &questions, &verdict).unwrap();
14687 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
14688 let mut q = questions.list().pop().unwrap();
14689 let choice = if retry {
14690 "daemon: recheck and retry"
14691 } else {
14692 "daemon: hold the task"
14693 };
14694 assert_eq!(q.actions.len(), 2);
14695 q.answer(ask::Answer::Choice(choice.into())).unwrap();
14696 questions.put(&mut q).unwrap();
14697
14698 questions.beat(&q.id, ask::WaiterKind::Deputy);
14700 for _ in 0..2 {
14701 resolve_blockers(&queue, &questions);
14702 apply_task_choice_actions(&queue, &questions, &home);
14703 let waiting = queue.get(&t.id).unwrap();
14704 assert_eq!(waiting.status, TaskStatus::Blocked);
14705 assert_eq!(waiting.blocked_by, [q.id.clone()]);
14706 assert!(waiting.answers.is_empty());
14707 assert!(!waiting.action_applied(&q.id));
14708 assert!(runnable(&queue).is_empty());
14709 let free = Arc::new(tokio::sync::Semaphore::new(1));
14710 assert!(claim_dispatch(&queue, &t, false, &free, &free).is_err());
14711 }
14712 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
14713
14714 resolve_blockers(&queue, &questions);
14716 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
14717 apply_task_choice_actions(&queue, &questions, &home);
14718 let after = queue.get(&t.id).unwrap();
14719 assert_eq!(
14720 after.status,
14721 if retry {
14722 TaskStatus::Queued
14723 } else {
14724 TaskStatus::Held
14725 }
14726 );
14727 assert!(after.action_applied(&q.id));
14728 assert_eq!(after.operator_held(), !retry);
14729 assert_eq!(after.answers.len(), 1);
14730
14731 let mut changed = after;
14733 if retry {
14734 changed.hold_manual(Some("later hold".into()));
14735 } else {
14736 changed.release_operator("test", None);
14737 }
14738 let expected = changed.status;
14739 queue.put(&mut changed).unwrap();
14740 apply_task_choice_actions(&queue, &questions, &home);
14741 assert_eq!(queue.get(&t.id).unwrap().status, expected);
14742 }
14743 }
14744 }
14745
14746 #[test]
14747 fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
14748 let dir = tempfile::tempdir().unwrap();
14749 let queue = Queue::at(dir.path().join("queue"));
14750 let questions = Questions::at(dir.path().join("questions"));
14751 let home = dir.path().join("home");
14752 let mut state = run_state(RunStatus::Blocked);
14753 state.id = "20260101-000000-act1".to_owned();
14754 state.save_under(&home).unwrap();
14755
14756 let mut t = held_task_with(&state.id);
14757 queue.put(&mut t).unwrap();
14758 let mut q = action_question(&state.id, resume_action(&state.id));
14759 questions.put(&mut q).unwrap();
14760
14761 apply_task_choice_actions(&queue, &questions, &home);
14762 let after = queue.get(&t.id).unwrap();
14763 assert_eq!(after.status, TaskStatus::Queued);
14764 assert!(!after.fresh_start);
14765 assert!(after.action_applied(&q.id));
14766 let pin = after.resume_override.clone().unwrap();
14767 assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
14768 assert!(pin.forced);
14769
14770 let mut again = queue.get(&t.id).unwrap();
14772 again.hold_machine(Some("later".into()));
14773 queue.put(&mut again).unwrap();
14774 apply_task_choice_actions(&queue, &questions, &home);
14775 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14776 }
14777
14778 #[test]
14779 fn done_choice_cannot_discard_unfinished_work_or_record_success_receipts() {
14780 let dir = tempfile::tempdir().unwrap();
14781 let home = dir.path();
14782 let queue = Queue::at(home.join("queue"));
14783 let questions = Questions::at(home.join("questions"));
14784 let mut state = run_state(RunStatus::Blocked);
14785 state.save_under(home).unwrap();
14786 let mut task = held_task_with(&state.id);
14787 queue.put(&mut task).unwrap();
14788 let mut question = action_question(&state.id, ask::ChoiceAction::Done);
14789 questions.put(&mut question).unwrap();
14790
14791 apply_task_choice_actions(&queue, &questions, home);
14792
14793 let after = queue.get(&task.id).unwrap();
14794 assert_eq!(after.status, TaskStatus::Held);
14795 assert!(after.hold_reason.as_deref().unwrap().contains("--discard"));
14796 assert_eq!(after.runs, task.runs);
14797 assert!(after.completion_history.is_empty());
14798 assert!(!after.decision_effects.contains_key(&question.id));
14799 assert_eq!(
14800 RunState::load_under(&state.id, home).unwrap().status,
14801 RunStatus::Blocked
14802 );
14803 }
14804
14805 #[test]
14806 fn a_delivered_answer_is_still_acted_on_exactly_once() {
14807 let dir = tempfile::tempdir().unwrap();
14808 let queue = Queue::at(dir.path().join("queue"));
14809 let questions = Questions::at(dir.path().join("questions"));
14810 let home = dir.path().join("home");
14811 let mut state = run_state(RunStatus::Blocked);
14812 state.id = "20260101-000000-act2".to_owned();
14813 state.save_under(&home).unwrap();
14814
14815 let mut t = held_task_with(&state.id);
14816 queue.put(&mut t).unwrap();
14817 let mut q = action_question(&state.id, resume_action(&state.id));
14818 q.answer_delivered = true;
14819 questions.put(&mut q).unwrap();
14820
14821 apply_task_choice_actions(&queue, &questions, &home);
14824 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
14825 assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
14826
14827 let mut again = queue.get(&t.id).unwrap();
14829 again.hold_machine(Some("later".into()));
14830 queue.put(&mut again).unwrap();
14831 apply_task_choice_actions(&queue, &questions, &home);
14832 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14833 }
14834
14835 #[test]
14836 fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
14837 let dir = tempfile::tempdir().unwrap();
14838 let queue = Queue::at(dir.path().join("queue"));
14839 let questions = Questions::at(dir.path().join("questions"));
14840 let home = dir.path().join("home");
14841 let mut state = run_state(RunStatus::Blocked);
14842 state.id = "20260101-000000-act3".to_owned();
14843 state.save_under(&home).unwrap();
14844 let mut t = held_task_with(&state.id);
14845 queue.put(&mut t).unwrap();
14846 let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
14847 questions.put(&mut q).unwrap();
14848
14849 questions.beat(&q.id, crate::ask::WaiterKind::Asker);
14850 apply_task_choice_actions(&queue, &questions, &home);
14851 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14852
14853 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
14854 apply_task_choice_actions(&queue, &questions, &home);
14855 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
14856 }
14857
14858 #[test]
14859 fn action_standing_tells_the_reasons_apart() {
14860 let mut t = held_task_with("r1");
14861 let q = action_question("r1", ask::ChoiceAction::Requeue);
14862 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
14863 let mut plain = q.clone();
14864 plain.actions.clear();
14865 assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
14866
14867 t.mark_action_applied(&q.id);
14869 assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
14870
14871 let mut t = held_task_with("r1");
14873 t.start("r2".to_owned());
14874 assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
14875 let q2 = action_question("r2", ask::ChoiceAction::Requeue);
14877 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
14878 t.status = TaskStatus::Blocked;
14879 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
14880
14881 let mut c = action_question("r0", ask::ChoiceAction::Requeue);
14883 c.node = crate::conduct::NODE.to_owned();
14884 assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
14885 assert!(!ActionStanding::Busy.daemon_owns());
14886 }
14887
14888 #[test]
14889 fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
14890 let dir = tempfile::tempdir().unwrap();
14891 let queue = Queue::at(dir.path().join("queue"));
14892 let questions = Questions::at(dir.path().join("questions"));
14893 let home = dir.path().join("home");
14894 let mut state = run_state(RunStatus::Ready);
14896 state.id = "20260101-000000-act4".to_owned();
14897 state.save_under(&home).unwrap();
14898 let mut t = held_task_with(&state.id);
14899 t.status = TaskStatus::Running;
14900 queue.put(&mut t).unwrap();
14901 let mut q = action_question(&state.id, ask::ChoiceAction::Done);
14902 q.cwd = Some(dir.path().display().to_string());
14903 questions.put(&mut q).unwrap();
14904
14905 let running = queue.get(&t.id).unwrap();
14908 assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
14909 assert!(matches!(
14910 crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
14911 crate::waiter::Action::Deliver(_)
14912 ));
14913 apply_task_choice_actions(&queue, &questions, &home);
14915 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
14916 let mut back = queue.get(&t.id).unwrap();
14917 back.hold_machine(Some("later".into()));
14918 queue.put(&mut back).unwrap();
14919 apply_task_choice_actions(&queue, &questions, &home);
14920 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
14921 let mut again = queue.get(&t.id).unwrap();
14922 again.hold_machine(Some("again".into()));
14923 queue.put(&mut again).unwrap();
14924 apply_task_choice_actions(&queue, &questions, &home);
14925 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14926 }
14927}