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 if state.is_none_or(RunState::all_candidates_verified_noop) => {
1956 task.handed_off(detail)
1957 }
1958 RunStatus::VerifiedNoop => task.fail(detail, max_attempts),
1959 other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1960 }
1961}
1962
1963pub fn supersede_prior_runs(task: &Task, home: &Path) {
2012 if task
2013 .completion_history
2014 .last()
2015 .is_some_and(|event| event.discard)
2016 {
2017 return;
2018 }
2019 let now = Timestamp::now();
2020 let last_run_succeeded = task
2027 .runs
2028 .last()
2029 .and_then(|id| RunState::load_under(id, home).ok())
2030 .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
2031 for id in task.superseded_attempts(last_run_succeeded) {
2032 let mut state = match RunState::load_under(id, home) {
2033 Ok(s) => s,
2034 Err(e) => {
2035 tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
2036 continue;
2037 }
2038 };
2039 if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
2040 continue;
2041 }
2042 let daemon_claims = is_working_on(home, id, now);
2043 if state.liveness(daemon_claims) == Liveness::Live {
2044 continue;
2045 }
2046 state.status = RunStatus::Superseded;
2047 if let Err(e) = state.save_under(home) {
2048 tracing::warn!("could not mark run {id} superseded: {e:#}");
2049 }
2050 }
2051}
2052
2053fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
2075 for task in queue.list() {
2076 if task.status != TaskStatus::Done || task.runs.len() < 2 {
2077 continue;
2078 }
2079 supersede_prior_runs(&task, home);
2080 }
2081}
2082
2083fn settle_and_diagnose(
2090 task: &mut Task,
2091 verdict: Verdict,
2092 detail: &str,
2093 max_attempts: usize,
2094 state: &RunState,
2095) {
2096 let mut verdict = verdict;
2097 let mut detail = detail;
2098 if verdict.status == RunStatus::VerifiedNoop && !state.all_candidates_verified_noop() {
2099 verdict.status = RunStatus::Failed;
2103 verdict.quota_hit = false;
2104 detail = "no-change result lacks verified evidence";
2105 }
2106 let p = phrases(&state.config.graph.language);
2107 if let Some(d) = &state.merge_decision {
2110 use crate::merge_decision as md;
2111 if task
2112 .execution_runs()
2113 .last()
2114 .is_some_and(|id| id != &state.id)
2115 {
2116 return;
2117 }
2118 if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
2119 task.succeed(CompletionContext::from_run(
2120 CompletionActor::DaemonSettle,
2121 Some(format!("Owner merge decision {}: {}", d.question, d.choice)),
2122 task,
2123 state,
2124 ));
2125 } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
2126 if state.liveness(false) != Liveness::Dead {
2127 task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
2128 return;
2129 }
2130 let replacement = md::Replacement {
2131 question: d.question.clone(),
2132 run: state.id.clone(),
2133 pr: d.target.pr.clone(),
2134 agent: agent.to_owned(),
2135 context: format!(
2136 "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
2137 d.target.pr,
2138 state.id,
2139 serde_json::to_string(&state.reviews).unwrap_or_default()
2140 ),
2141 };
2142 task.requeue();
2143 task.pr_recovery = None;
2144 task.review_of = None;
2145 task.replacement = Some(replacement);
2146 } else {
2147 task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
2148 format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
2149 } 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())) }));
2150 }
2151 task.mark_action_applied(&d.question);
2152 if d.choice.eq_ignore_ascii_case(land::HOLD) {
2153 task.decision_effects
2154 .insert(d.question.clone(), format!("decision: {}", d.choice));
2155 }
2156 if let Some(pass) = state.passes.last() {
2157 task.record_pass_at(
2158 &state.id,
2159 pass.index,
2160 Some(pass.started_at),
2161 task.attempts,
2162 None,
2163 );
2164 }
2165 return;
2166 }
2167 if let Some(replacement) = &task.replacement
2168 && !state.parked
2169 && state.resource_block.is_none()
2170 && (state.viable().is_empty()
2171 || (state.status == RunStatus::Blocked && state.tally.is_none()))
2172 {
2173 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)));
2174 return;
2175 }
2176 if !verdict.parked && verdict.quota_hit && state.status == RunStatus::Stalled {
2177 let mut agents: Vec<_> = state
2178 .quota
2179 .iter()
2180 .filter(|q| {
2181 q.cause == crate::agent::QuotaCause::Authentication
2182 && state
2183 .passes
2184 .last()
2185 .is_none_or(|pass| q.at >= pass.started_at)
2186 })
2187 .map(|q| q.agent.as_str())
2188 .collect();
2189 agents.sort_unstable();
2190 agents.dedup();
2191 if !agents.is_empty() {
2192 task.stall(detail);
2193 task.notice_cause("agent-authentication", None, None);
2194 task.hold_machine(Some(format!("[authentication] Agents {} cannot authenticate; re-authenticate, then resume the held task. No attempt was spent.", agents.join(", "))));
2195 return;
2196 }
2197 }
2198 let attempts_before = task.attempts;
2199 if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
2206 let disk_checked_at = task.disk_checked_at;
2207 task.notice_cause(
2208 &format!("resource:{}:{}", block.kind, block.node),
2209 None,
2210 None,
2211 );
2212 task.last_error = Some(detail.to_owned());
2213 task.diagnostic = None;
2214 task.attempts = task.attempts.saturating_sub(1);
2215 if block.kind == "agent authentication" {
2216 task.hold_machine(Some(format!(
2217 "[authentication] {}; no attempt was spent",
2218 block.detail
2219 )));
2220 } else if block.kind == "agent usage limit" {
2221 if let Some(agent) = &state.config.graph.selected_implementer {
2223 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.")));
2224 } else {
2225 task.status = TaskStatus::Failed;
2226 task.last_error = Some(block.detail.clone());
2227 }
2228 } else if block.kind == "disk pressure" {
2229 task.hold_machine(Some(format!(
2230 "{}{}",
2231 crate::disk::RUNNING_PRESSURE,
2232 block.detail
2233 )));
2234 } else {
2235 task.hold_machine(Some(format!(
2236 "{}{}; no attempt was spent; resume to retry the affected operation",
2237 crate::cache::RESOURCE_HOLD,
2238 block.description()
2239 )));
2240 }
2241 if matches!(block.kind.as_str(), "disk pressure" | "disk admission")
2242 && matches!(block.cause, crate::run::ResourceBlockCause::Other)
2243 {
2244 task.mark_disk_capacity();
2245 task.disk_checked_at = disk_checked_at;
2246 }
2247 if let Some(pass) = state.passes.last() {
2248 task.record_pass_at(
2249 &state.id,
2250 pass.index,
2251 Some(pass.started_at),
2252 attempts_before,
2253 None,
2254 );
2255 }
2256 return;
2257 }
2258 if let Some(hold) = state.land_unrelated.as_ref().filter(|hold| {
2259 state.parked
2260 && state.status == RunStatus::Landing
2261 && state
2262 .pr_pushed_head
2263 .as_ref()
2264 .is_none_or(|h| h == &hold.head)
2265 && task.execution_runs().last() == Some(&state.id)
2266 }) {
2267 let pass = state.passes.last().map_or(0, |p| p.index);
2270 if !task
2271 .passes
2272 .iter()
2273 .any(|p| p.run == state.id && p.pass_index == pass)
2274 {
2275 task.attempts = task.attempts.saturating_sub(1);
2276 }
2277 task.hold_machine(Some(format!(
2278 "[ci-unrelated] CI failure reproduced on base; owner question {}",
2279 hold.question
2280 )));
2281 task.last_error = Some(detail.to_owned());
2282 task.diagnostic = None;
2283 task.record_pass_at(
2284 &state.id,
2285 pass,
2286 state.passes.last().map(|p| p.started_at),
2287 attempts_before,
2288 Some(crate::run::ParkCause::Question),
2289 );
2290 return;
2291 }
2292 let unresolved = task.hold_notice_cause.clone();
2293 let head_e2e_stop = crate::head_e2e_stop::conclusive(state)
2294 .filter(|_| !verdict.parked && !verdict.quota_hit && task.pr_recovery.is_none());
2295 let mut reconsumed_head_e2e = false;
2296 if state.base_sync_blocked() {
2297 task.hold_machine(Some(detail.to_owned()));
2299 task.last_error = Some(detail.to_owned());
2300 } else if !verdict.parked
2301 && task
2302 .pr_recovery
2303 .as_ref()
2304 .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
2305 && matches!(
2306 verdict.status,
2307 RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
2308 )
2309 {
2310 if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
2311 task.succeed(CompletionContext::from_run(
2312 CompletionActor::DaemonSettle,
2313 Some(detail.to_owned()),
2314 task,
2315 state,
2316 ));
2317 } else {
2318 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()));
2319 }
2320 } else if !verdict.parked
2321 && task.pr_recovery.is_some()
2322 && matches!(
2323 verdict.status,
2324 RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
2325 )
2326 && !verdict.quota_hit
2327 {
2328 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.")));
2329 } else if let Some(stop) = head_e2e_stop.clone() {
2330 if crate::head_e2e_stop::reconsumed_without_new_verification(state, &stop) {
2335 reconsumed_head_e2e = true;
2336 let pass = state.passes.last().map_or(0, |p| p.index);
2337 if !task
2338 .passes
2339 .iter()
2340 .any(|p| p.run == state.id && p.pass_index == pass)
2341 {
2342 task.attempts = task.attempts.saturating_sub(1);
2343 }
2344 }
2345 let reason = crate::head_e2e_stop::hold_reason(task, state, &stop, None);
2346 task.hold_head_e2e(stop, reason, detail.to_owned());
2347 } else {
2348 settle_in(task, verdict, detail, max_attempts, p, Some(state));
2349 }
2350 if !verdict.parked
2351 && !verdict.quota_hit
2352 && !reconsumed_head_e2e
2353 && matches!(
2354 verdict.status,
2355 RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
2356 )
2357 {
2358 task.recovery_failed(state);
2359 }
2360 if state.prep_failure.is_some() {
2361 task.hold_notice_cause = unresolved;
2364 task.startup_notice_cause("startup-candidates");
2365 }
2366 if let Some(pass) = state.passes.last() {
2369 let parked = match &pass.end {
2370 Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2371 _ => None,
2372 };
2373 task.record_pass_at(
2374 &state.id,
2375 pass.index,
2376 Some(pass.started_at),
2377 attempts_before,
2378 parked,
2379 );
2380 }
2381 if task.status == TaskStatus::Held {
2382 if state.base_sync_blocked() {
2383 task.base_sync_notice(state);
2384 } else if let Some(stop) = &head_e2e_stop {
2385 task.head_e2e_notice(stop);
2386 } else if state.prep_failure.is_none() {
2387 task.notice_cause(
2388 label(verdict.status),
2389 Some(&state.id),
2390 state.passes.last().map(|p| p.index),
2391 );
2392 }
2393 task.diagnostic = diagnostic(state);
2394 note_open_question(task, &state.id, p);
2395 }
2396}
2397
2398fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2413 let Some(home) = crate::run::try_home() else {
2414 return;
2415 };
2416 let open = Questions::at(home.join("questions")).open_for(run);
2417 let Some(q) = open.first() else {
2418 return;
2419 };
2420 let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2421 decisions.sort_unstable();
2422 task.notice_cause(
2423 &format!("questions:{}", decisions.join(",")),
2424 Some(run),
2425 None,
2426 );
2427 let base = task.hold_reason.clone().unwrap_or_default();
2428 task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2429}
2430
2431fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2442 if let Some(request) = task.sync_only.clone() {
2443 crate::base_sync_only::settle(task, &request, last_run.as_ref(), None);
2444 return;
2445 }
2446 match last_run {
2447 Some(state) => {
2448 let verdict = Verdict {
2449 status: state.status,
2450 left_pr: state.pr.is_some(),
2451 quota_hit: state.quota.iter().any(|loss| {
2452 state
2453 .passes
2454 .last()
2455 .is_none_or(|pass| loss.at >= pass.started_at)
2456 }),
2457 parked: state.parked,
2458 no_viable_candidates: state.viable().is_empty(),
2459 };
2460 let detail = format!(
2461 "{}{}",
2462 phrases(&state.config.graph.language).recovered_running,
2463 describe(&state)
2464 );
2465 settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2466 }
2467 None => {
2468 let why = phrases(language).no_run_to_recover;
2471 task.last_error = Some(why.to_owned());
2472 task.notice_cause("missing-run", None, None);
2475 task.hold_machine(Some(why.to_owned()));
2476 }
2477 }
2478}
2479
2480fn reclaim_orphaned_running(
2502 queue: &Queue,
2503 max_attempts: usize,
2504 live_workers: &std::collections::BTreeSet<String>,
2505) -> Vec<String> {
2506 let mut reclaimed = Vec::new();
2507 for listed in queue.list() {
2508 if listed.status != TaskStatus::Running || live_workers.contains(&listed.id) {
2509 continue;
2510 }
2511 let Ok(_claim) = queue.claim(&listed.id) else {
2512 continue;
2513 };
2514 let Ok(mut task) = queue.get(&listed.id) else {
2518 continue;
2519 };
2520 if task.status != TaskStatus::Running {
2521 continue;
2522 }
2523 let last_run = task
2524 .execution_runs()
2525 .last()
2526 .and_then(|id| RunState::load(id).ok());
2527 if let Some(state) = &last_run
2537 && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2538 {
2539 tracing::warn!("abandon questions for {}: {e:#}", state.id);
2540 }
2541 let language = if last_run.is_none() {
2542 language_of(&task, Path::new("."))
2543 } else {
2544 String::new()
2545 };
2546 reclaim(&mut task, last_run, max_attempts, &language);
2547 if task.status == TaskStatus::Done {
2548 supersede_prior_runs(&task, &crate::run::home());
2549 }
2550 record(queue, &mut task);
2551 reclaimed.push(task.id.clone());
2552 }
2553 reclaimed
2554}
2555
2556fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2588 reclaim_abandoned_runs_with(
2589 home,
2590 now,
2591 crate::proc::pid_status,
2592 crate::proc::process_started_at,
2593 )
2594}
2595
2596fn reclaim_abandoned_runs_with<F, G>(
2602 home: &Path,
2603 now: Timestamp,
2604 query: F,
2605 identity: G,
2606) -> Vec<String>
2607where
2608 F: Fn(u32) -> Option<bool>,
2609 G: Fn(u32) -> Option<String>,
2610{
2611 let mut abandoned = Vec::new();
2612 for entry in std::fs::read_dir(home.join("runs"))
2613 .into_iter()
2614 .flatten()
2615 .flatten()
2616 {
2617 let id = entry.file_name().to_string_lossy().into_owned();
2618 if !crate::run::is_run_id(&id) {
2619 continue;
2620 }
2621 let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2624 continue;
2625 };
2626 let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2634 continue;
2635 };
2636 let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2637 continue;
2638 };
2639 if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2640 continue;
2641 }
2642 let daemon_claims = is_working_on(home, &id, now);
2654 if state.liveness_under_with(home, daemon_claims, &query, &identity)
2655 != crate::run::Liveness::Dead
2656 {
2657 continue;
2658 }
2659 state.abandon("daemon");
2660 if let Err(e) = state.save_under(home) {
2661 tracing::warn!("could not persist abandoned run {id}: {e:#}");
2662 continue;
2663 }
2664 if let Some(notice) = notices::run_ended(&state) {
2667 notices::raise_in(home, notice);
2668 }
2669 if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2677 tracing::warn!("abandon questions for {id}: {e:#}");
2678 }
2679 abandoned.push(id);
2680 }
2681 abandoned
2682}
2683
2684#[derive(Debug, Clone, Serialize, Deserialize)]
2685struct TaskWorker {
2686 opts: Opts,
2687 queue: PathBuf,
2688 task: String,
2689 #[serde(default)]
2690 lane: PermitKind,
2691 #[serde(default)]
2692 standalone: bool,
2693}
2694
2695#[doc(hidden)]
2696pub struct TaskWorkerLease {
2697 pub job: crate::worker::Job,
2698 dir: PathBuf,
2699 lease: Option<crate::worker::Lease>,
2700}
2701
2702impl TaskWorkerLease {
2703 pub fn release_lease(&mut self) {
2704 self.lease = None;
2705 }
2706}
2707
2708impl Drop for TaskWorkerLease {
2709 fn drop(&mut self) {
2710 self.release_lease();
2711 let _ = std::fs::remove_dir_all(&self.dir);
2712 }
2713}
2714
2715#[doc(hidden)]
2717pub fn live_task_fixture(home: &Path, task: &str) -> Result<TaskWorkerLease> {
2718 let request = TaskWorker {
2719 opts: Opts::default(),
2720 queue: home.join("queue"),
2721 task: task.to_owned(),
2722 lane: PermitKind::default(),
2723 standalone: true,
2724 };
2725 let (job, lease) = crate::worker::running_fixture(
2726 home,
2727 &format!("task:{task}"),
2728 serde_json::to_value(request)?,
2729 )?;
2730 Ok(TaskWorkerLease {
2731 dir: home.join("workers").join("jobs").join(&job.id),
2732 job,
2733 lease: Some(lease),
2734 })
2735}
2736
2737fn task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2738 Ok(crate::worker::active(home)?
2739 .into_iter()
2740 .filter(|job| job.kind == "task")
2741 .collect())
2742}
2743
2744fn owned_task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2745 task_jobs(home)?
2746 .into_iter()
2747 .filter_map(
2748 |job| match serde_json::from_value::<TaskWorker>(job.payload.clone()) {
2749 Ok(request) if !request.standalone => Some(Ok(job)),
2750 Ok(_) => None,
2751 Err(error) => Some(Err(error.into())),
2752 },
2753 )
2754 .collect()
2755}
2756
2757#[must_use]
2759pub fn managed(home: &Path) -> bool {
2760 match crate::worker::active(home) {
2761 Err(error) => {
2762 tracing::error!("cannot determine scheduler ownership: {error:#}");
2763 true
2764 }
2765 Ok(jobs) if jobs.iter().any(|j| j.kind == "scheduler") => true,
2766 Ok(_) => {
2767 read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2768 && crate::worker::try_lease(home, "scheduler").map_or(true, |lease| lease.is_none())
2769 }
2770 }
2771}
2772
2773pub async fn spawn_detached(home: &Path, opts: &Opts) -> Result<crate::worker::Job> {
2775 anyhow::ensure!(
2776 crate::worker::control(home, "scheduler")?.is_none() || !managed(home),
2777 "the scheduler is stopping; wait for retirement before starting it again"
2778 );
2779 crate::worker::spawn(
2780 home,
2781 "scheduler",
2782 "scheduler",
2783 serde_json::to_value(opts.absolute()?)?,
2784 )
2785 .await
2786}
2787
2788fn park_request_path(home: &Path, job: &crate::worker::Job) -> PathBuf {
2789 home.join("worker-parks").join(format!("{}.json", job.id))
2790}
2791
2792fn request_task_park(
2793 home: &Path,
2794 job: &crate::worker::Job,
2795 cause: crate::run::ParkCause,
2796) -> Result<()> {
2797 let path = park_request_path(home, job);
2798 std::fs::create_dir_all(path.parent().context("worker park directory")?)?;
2799 std::fs::write(path, serde_json::to_vec(&cause)?)?;
2800 crate::worker::request(home, &job.key, crate::worker::Control::Park)
2801}
2802
2803pub fn request_control(home: &Path, control: crate::worker::Control) -> Result<()> {
2805 if control == crate::worker::Control::Park {
2806 for job in owned_task_jobs(home)? {
2807 request_task_park(home, &job, crate::run::ParkCause::Operator)?;
2808 }
2809 }
2810 crate::worker::request(home, "scheduler", control)
2811}
2812
2813pub(crate) fn scheduler_restart_options(home: &Path) -> Result<Option<Opts>> {
2815 if let Some(job) = crate::worker::active(home)?
2816 .into_iter()
2817 .find(|job| job.kind == "scheduler")
2818 {
2819 return serde_json::from_value(job.payload)
2820 .context("read detached scheduler options")
2821 .map(Some);
2822 }
2823 if read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2824 && crate::worker::try_lease(home, "scheduler")?.is_none()
2825 {
2826 let path = home.join("scheduler-options.json");
2827 let body = std::fs::read(&path).with_context(|| format!("read {}", path.display()))?;
2828 return serde_json::from_slice(&body)
2829 .context("decode detached scheduler options")
2830 .map(Some);
2831 }
2832 Ok(None)
2833}
2834
2835pub async fn restart_detached(home: &Path) -> Result<()> {
2837 let Some(opts) = scheduler_restart_options(home)? else {
2838 return Ok(());
2839 };
2840 request_control(home, crate::worker::Control::Stop)?;
2841 loop {
2842 let reserved = crate::worker::active(home)?
2843 .iter()
2844 .any(|job| job.kind == "scheduler");
2845 if !reserved && crate::worker::try_lease(home, "scheduler")?.is_some() {
2846 break;
2847 }
2848 tokio::time::sleep(Duration::from_millis(100)).await;
2849 }
2850 spawn_detached(home, &opts).await?;
2851 Ok(())
2852}
2853
2854pub async fn run_scheduler_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2856 let opts: Opts = serde_json::from_value(payload)?;
2857 let _ = home;
2858 serve_until(opts, Stop::new()).await
2859}
2860
2861pub async fn run_task_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2863 let request: TaskWorker = serde_json::from_value(payload)?;
2864 let queue = Queue::at(request.queue);
2865 let key = format!("task:{}", request.task);
2866 let job = task_jobs(home)?
2867 .into_iter()
2868 .find(|job| job.key == key)
2869 .context("task worker reservation is missing")?;
2870 let park_path = park_request_path(home, &job);
2871 let _claim = loop {
2874 match queue.claim(&request.task) {
2875 Ok(claim) => break claim,
2876 Err(e) if e.chain().any(|c| c.is::<std::io::Error>()) => {
2879 return Err(e.context("claim the task for its worker"));
2880 }
2881 Err(_) => {
2882 sweep_stale_claims(&queue, STALE_CLAIM);
2883 tokio::time::sleep(Duration::from_millis(50)).await;
2884 }
2885 }
2886 };
2887 let mut task = queue.get(&request.task)?;
2888 if !task.status.runnable()
2889 || (!request.standalone
2890 && request.lane
2891 != permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent))
2892 {
2893 return Ok(());
2894 }
2895 let stop = Stop::new();
2896 let watcher = {
2897 let home = home.to_path_buf();
2898 let stop = stop.clone();
2899 let park_path = park_path.clone();
2900 tokio::spawn(async move {
2901 loop {
2902 if crate::worker::control(&home, &key).ok().flatten().is_some() {
2903 let cause = std::fs::read(&park_path)
2904 .ok()
2905 .and_then(|body| serde_json::from_slice(&body).ok())
2906 .unwrap_or(crate::run::ParkCause::Operator);
2907 stop.park(cause);
2908 return;
2909 }
2910 tokio::time::sleep(Duration::from_millis(200)).await;
2911 }
2912 })
2913 };
2914 let quota = if request.standalone {
2915 run_claimed_until(&request.opts, &queue, &mut task, &stop).await
2916 } else {
2917 let status = Arc::new(Mutex::new(Status::new()));
2918 Box::pin(attempt(
2919 &request.opts,
2920 &queue,
2921 &status,
2922 &stop,
2923 crate::graph::Pause::new(),
2924 &mut task,
2925 ))
2926 .await
2927 };
2928 watcher.abort();
2929 let _ = std::fs::remove_file(park_path);
2930 persist_cooldown(home, "a).await?;
2931 Ok(())
2932}
2933
2934pub async fn spawn_claimed(
2937 home: &Path,
2938 opts: &Opts,
2939 queue: &Queue,
2940 task: &Task,
2941 claim: crate::queue::Claim,
2942) -> Result<crate::worker::Job> {
2943 let request = TaskWorker {
2944 opts: opts.absolute()?,
2945 queue: std::path::absolute(queue.root())?,
2946 task: task.id.clone(),
2947 lane: permit_kind(land_resume_state(task) == LandResume::Ready, task.urgent),
2948 standalone: true,
2949 };
2950 let job = crate::worker::spawn(
2951 home,
2952 "task",
2953 &format!("task:{}", task.id),
2954 serde_json::to_value(request)?,
2955 )
2956 .await?;
2957 drop(claim);
2958 Ok(job)
2959}
2960
2961pub async fn run_detached_claimed(
2964 opts: &Opts,
2965 queue: &Queue,
2966 task: &mut Task,
2967 claim: crate::queue::Claim,
2968) -> Result<()> {
2969 let home = crate::run::home();
2970 let job = spawn_claimed(&home, opts, queue, task, claim).await?;
2971 loop {
2972 crate::worker::active(&home)?;
2975 let current = crate::worker::get(&home, &job.id)?;
2976 if matches!(
2977 current.status,
2978 crate::worker::Status::Finished | crate::worker::Status::Failed
2979 ) {
2980 *task = queue.get(&task.id)?;
2981 anyhow::ensure!(
2982 current.status != crate::worker::Status::Failed,
2983 "task worker failed: {}",
2984 current.result.as_deref().unwrap_or("unknown failure")
2985 );
2986 return Ok(());
2987 }
2988 tokio::time::sleep(Duration::from_millis(200)).await;
2989 }
2990}
2991
2992async fn persist_cooldown(home: &Path, quota: &[QuotaLoss]) -> Result<()> {
2993 if let Some(until) = cooldown_until(quota, Timestamp::now()) {
2994 let _lease = loop {
2995 if let Some(lease) = crate::worker::try_lease(home, "task-quota-cooldown")? {
2996 break lease;
2997 }
2998 tokio::time::sleep(Duration::from_millis(10)).await;
2999 };
3000 if read_cooldown(home)?.is_none_or(|previous| previous < until) {
3001 let path = home.join("task-quota-cooldown.json");
3002 let temporary = path.with_extension("json.tmp");
3003 std::fs::write(&temporary, serde_json::to_vec(&until)?)?;
3004 std::fs::rename(temporary, path)?;
3005 }
3006 }
3007 Ok(())
3008}
3009
3010fn read_cooldown(home: &Path) -> Result<Option<Timestamp>> {
3011 match std::fs::read(home.join("task-quota-cooldown.json")) {
3012 Ok(body) => Ok(Some(serde_json::from_slice(&body)?)),
3013 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
3014 Err(error) => Err(error.into()),
3015 }
3016}
3017
3018pub async fn serve(opts: Opts) -> Result<()> {
3024 tracing::info!(
3025 "automatic update and restart requires magi web; standalone serve does not restart"
3026 );
3027 serve_until(opts, Stop::new()).await
3028}
3029
3030pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
3041 let opts = opts.absolute()?;
3042 let home = crate::run::home();
3043 let _scheduler = crate::worker::try_lease(&home, "scheduler")?
3044 .context("another scheduler already owns this home")?;
3045 if let Some(reading) = read_status(&home)
3046 && legacy_scheduler_running(&reading, Timestamp::now(), std::process::id())
3047 {
3048 bail!("a legacy scheduler is still running; stop it before starting independent dispatch");
3049 }
3050 if !crate::worker::active(&home)?
3051 .iter()
3052 .any(|job| job.kind == "scheduler")
3053 {
3054 crate::worker::clear_control(&home, "scheduler")?;
3055 }
3056 std::fs::write(
3057 home.join("scheduler-options.json"),
3058 serde_json::to_vec(&opts)?,
3059 )?;
3060 let control = {
3061 let home = home.clone();
3062 let stop = stop.clone();
3063 tokio::spawn(async move {
3064 loop {
3065 match crate::worker::control(&home, "scheduler").ok().flatten() {
3066 Some(crate::worker::Control::Park) => {
3067 let _ = request_control(&home, crate::worker::Control::Park);
3068 stop.park(crate::run::ParkCause::Operator);
3069 break;
3070 }
3071 Some(crate::worker::Control::Stop) => {
3072 stop.stop();
3073 break;
3074 }
3075 None => {}
3076 }
3077 tokio::time::sleep(Duration::from_millis(100)).await;
3078 }
3079 })
3080 };
3081 let signal = {
3082 let stop = stop.clone();
3083 tokio::spawn(async move {
3084 if tokio::signal::ctrl_c().await.is_ok() {
3085 stop.stop();
3086 tracing::info!("scheduler shutdown requested; independent workers continue");
3087 }
3088 })
3089 };
3090
3091 let worktrees_root = opts
3092 .worktrees_root
3093 .clone()
3094 .unwrap_or_else(crate::run::default_worktree_root);
3095 let outcome = drive(
3096 &opts,
3097 &Queue::open(),
3098 &status_path(),
3099 &crate::run::home(),
3100 &worktrees_root,
3101 &stop,
3102 )
3103 .await;
3104
3105 signal.abort();
3106 control.abort();
3107 outcome
3108}
3109
3110async fn drive(
3123 opts: &Opts,
3124 queue: &Queue,
3125 status_file: &Path,
3126 home: &Path,
3127 worktrees_root: &Path,
3128 stop: &Stop,
3129) -> Result<()> {
3130 let recovery_cfg = prepare(&opts.repo, opts).ok();
3138 let daemon_cfg = recovery_cfg
3139 .as_ref()
3140 .map(|c| c.daemon.clone())
3141 .unwrap_or_default();
3142 let reconciled = crate::driver::reconcile(home);
3143 if !reconciled.is_empty() {
3144 tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
3145 }
3146 let mut initial_status = Status::new();
3147 let owned = owned_task_jobs(home)?;
3148 initial_status.current = current_work(home, Timestamp::now())
3149 .into_iter()
3150 .filter(|current| {
3151 owned
3152 .iter()
3153 .any(|job| job.key.strip_prefix("task:") == Some(current.task.as_str()))
3154 })
3155 .collect();
3156 initial_status.idle = initial_status.current.is_empty();
3157 initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
3158 recovery_cfg.as_ref(),
3159 daemon_cfg.max_deputies,
3160 ));
3161 let status = Arc::new(Mutex::new(initial_status));
3162 write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
3163 let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
3164
3165 let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
3171
3172 tracing::info!(
3173 "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
3174 queue.root().display(),
3175 opts.poll.as_secs(),
3176 opts.max_attempts,
3177 concurrency,
3178 if daemon_cfg.pause_for_interrupts {
3179 ", interrupts enabled"
3180 } else {
3181 ""
3182 }
3183 );
3184
3185 let outcome = tokio::select! {
3186 outcome = poll(opts, queue, &status, home, worktrees_root, stop, DispatchLimits {
3187 max_concurrent: concurrency,
3188 pause_for_interrupts: daemon_cfg.pause_for_interrupts,
3189 recovery_cfg,
3190 }) => outcome,
3191 () = async {
3192 while !stop.stopped() {
3193 tokio::time::sleep(Duration::from_millis(25)).await;
3194 }
3195 } => {
3196 if stop.parking() {
3197 request_control(home, crate::worker::Control::Park)?;
3198 }
3199 Ok(())
3200 }
3201 };
3202
3203 stop.busy.store(0, Ordering::SeqCst);
3204 beat.abort();
3205 clear_status_at(status_file);
3206 outcome
3207}
3208
3209pub(crate) fn release_watch_settings_from_config(
3212 home: &Path,
3213 repo: &Path,
3214 cfg: &Config,
3215) -> (Vec<PathBuf>, u64) {
3216 let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
3217 .into_iter()
3218 .map(|r| r.path)
3219 .collect();
3220 let mut known: Vec<PathBuf> = Queue::at(home.join("queue"))
3223 .list()
3224 .into_iter()
3225 .map(|t| t.repo)
3226 .collect();
3227 let runs = home.join("runs");
3228 for id in crate::run::list_ids_in(&runs) {
3229 let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
3230 .ok()
3231 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
3232 .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
3233 known.extend(repo);
3234 }
3235 for k in known {
3236 let k = k.canonicalize().unwrap_or(k);
3237 if k.join(".git").exists() && !paths.contains(&k) {
3238 paths.push(k);
3239 }
3240 }
3241 let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
3242 if !paths.contains(&own) {
3243 paths.push(own);
3244 }
3245 (paths, cfg.daemon.release_stall_minutes)
3246}
3247
3248const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
3250
3251async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
3257 loop {
3258 tokio::time::sleep(HEARTBEAT).await;
3259 let snapshot = {
3260 let mut guard = lock(&status);
3261 guard.updated_at = Timestamp::now();
3262 guard.clone()
3263 };
3264 if let Err(e) = write_status_to(&path, &snapshot) {
3265 tracing::warn!("could not refresh the daemon status file: {e:#}");
3268 }
3269 }
3270}
3271
3272#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3275enum LandResume {
3276 NotLanding,
3279 StillWaiting,
3284 Ready,
3288}
3289
3290fn land_resume_state(task: &Task) -> LandResume {
3294 if task.sync_only.is_some() {
3295 return LandResume::NotLanding;
3296 }
3297 let Some(run_id) = task.execution_runs().last() else {
3298 return LandResume::NotLanding;
3299 };
3300 let Ok(state) = RunState::load(run_id) else {
3301 return LandResume::NotLanding;
3302 };
3303 if !state.parked {
3304 return LandResume::NotLanding;
3305 }
3306 if state.status == RunStatus::Landing
3307 && state.land_approval.as_ref().is_some_and(|binding| {
3308 ask::Questions::open()
3309 .get_for_effects(&binding.question)
3310 .is_ok_and(|q| {
3311 q.run == state.id
3312 && q.resolution()
3313 .as_deref()
3314 .is_some_and(crate::merge_decision::stops)
3315 })
3316 })
3317 {
3318 return LandResume::Ready;
3319 }
3320 if !implementers_match(task, &state) {
3321 return LandResume::NotLanding;
3322 }
3323 let node = if state.status == RunStatus::Landing {
3327 land::APPROVAL_NODE
3328 } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
3329 crate::github_text::ASK_NODE
3330 } else {
3331 return LandResume::NotLanding;
3332 };
3333 let store = ask::Questions::open();
3334 let waiting = store
3335 .list_for_effects()
3336 .into_iter()
3337 .filter(|q| &q.run == run_id && q.node == node)
3338 .max_by(|a, b| a.id.cmp(&b.id));
3339 let Some(mut q) = waiting else {
3340 return LandResume::Ready;
3341 };
3342 if !q.status.open() {
3343 if q.resolution().as_deref() == Some(land::REPAIR) {
3346 return if state.liveness(false) == Liveness::Live {
3347 LandResume::StillWaiting
3348 } else {
3349 LandResume::NotLanding
3350 };
3351 }
3352 return LandResume::Ready;
3353 }
3354 let timeout = Duration::from_secs(state.config.graph.answer_timeout);
3361 let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
3362 if !store.held_reply(&q.id) && elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
3363 q.abandon(format!(
3364 "no answer within {}s of asking",
3365 timeout.as_secs().max(1)
3366 ));
3367 if store.put(&mut q).is_ok() {
3370 return LandResume::Ready;
3371 }
3372 }
3373 LandResume::StillWaiting
3374}
3375
3376const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
3384
3385const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
3397
3398#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3411enum Interrupt {
3412 Idle,
3414 Parking {
3426 parked: Vec<String>,
3427 interrupt_task: String,
3428 },
3429 Running {
3437 parked: Vec<String>,
3438 interrupt_task: String,
3439 },
3440 Resuming { parked: Vec<String> },
3447}
3448
3449fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
3470 match state {
3471 Interrupt::Idle => {
3472 if in_flight.len() != 1 {
3484 return Interrupt::Idle;
3485 }
3486 match runnable.iter().find(|t| t.interrupt) {
3487 Some(t) => Interrupt::Parking {
3488 parked: in_flight.to_vec(),
3489 interrupt_task: t.id.clone(),
3490 },
3491 None => Interrupt::Idle,
3492 }
3493 }
3494 Interrupt::Parking {
3495 parked,
3496 interrupt_task,
3497 } => {
3498 if in_flight.iter().any(|id| parked.contains(id)) {
3499 Interrupt::Parking {
3501 parked,
3502 interrupt_task,
3503 }
3504 } else if in_flight.contains(&interrupt_task) {
3505 Interrupt::Running {
3506 parked,
3507 interrupt_task,
3508 }
3509 } else if runnable.iter().any(|t| t.id == interrupt_task) {
3510 Interrupt::Parking {
3514 parked,
3515 interrupt_task,
3516 }
3517 } else {
3518 Interrupt::Resuming { parked }
3523 }
3524 }
3525 Interrupt::Running {
3526 parked,
3527 interrupt_task,
3528 } => {
3529 if in_flight.contains(&interrupt_task) {
3530 Interrupt::Running {
3531 parked,
3532 interrupt_task,
3533 }
3534 } else {
3535 Interrupt::Resuming { parked }
3541 }
3542 }
3543 Interrupt::Resuming { parked } => {
3544 if in_flight.iter().any(|id| parked.contains(id)) {
3545 Interrupt::Idle
3551 } else if runnable.iter().any(|t| parked.contains(&t.id)) {
3552 Interrupt::Resuming { parked }
3553 } else {
3554 Interrupt::Idle
3557 }
3558 }
3559 }
3560}
3561
3562fn advance_interrupt_tick(
3568 enabled: bool,
3569 state: Interrupt,
3570 in_flight: &[String],
3571 runnable: &[Task],
3572) -> Interrupt {
3573 if !enabled {
3574 return Interrupt::Idle;
3575 }
3576 advance_interrupt(state, in_flight, runnable)
3577}
3578
3579fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
3584 match state {
3585 Interrupt::Idle => candidates,
3586 Interrupt::Parking {
3587 parked,
3588 interrupt_task,
3589 } => {
3590 if in_flight.iter().any(|id| parked.contains(id)) {
3591 Vec::new()
3592 } else {
3593 candidates
3594 .into_iter()
3595 .filter(|t| &t.id == interrupt_task)
3596 .collect()
3597 }
3598 }
3599 Interrupt::Running { .. } => Vec::new(),
3600 Interrupt::Resuming { parked } => candidates
3608 .into_iter()
3609 .find(|t| parked.contains(&t.id))
3610 .into_iter()
3611 .collect(),
3612 }
3613}
3614
3615struct DispatchLimits {
3619 max_concurrent: usize,
3622 pause_for_interrupts: bool,
3624 recovery_cfg: Option<Config>,
3625}
3626
3627#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3636enum PermitKind {
3637 None,
3642 Urgent,
3649 #[default]
3652 Ordinary,
3653}
3654
3655fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
3658 if priority {
3659 PermitKind::None
3660 } else if urgent {
3661 PermitKind::Urgent
3662 } else {
3663 PermitKind::Ordinary
3664 }
3665}
3666
3667fn available_slots(requests: &[TaskWorker], limit: usize) -> (usize, usize) {
3668 let (ordinary, urgent) = requests.iter().filter(|request| !request.standalone).fold(
3669 (0usize, 0usize),
3670 |(ordinary, urgent), request| match request.lane {
3671 PermitKind::Ordinary => (ordinary + 1, urgent),
3672 PermitKind::Urgent => (ordinary, urgent + 1),
3673 PermitKind::None => (ordinary, urgent),
3674 },
3675 );
3676 (
3677 limit.saturating_sub(ordinary),
3678 1usize.saturating_sub(urgent),
3679 )
3680}
3681
3682#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
3684enum SkipReason {
3685 ClaimUnavailable,
3686 RereadFailed,
3687 NoLongerRunnable,
3688 WaitingOnLanding,
3689 CoolingDown,
3690 OrdinaryCapacity,
3691 UrgentCapacity,
3692 InterruptGate,
3693}
3694
3695impl SkipReason {
3696 fn key(self) -> &'static str {
3697 match self {
3698 Self::ClaimUnavailable => "claim_unavailable",
3699 Self::RereadFailed => "reread_failed",
3700 Self::NoLongerRunnable => "no_longer_runnable",
3701 Self::WaitingOnLanding => "waiting_on_landing",
3702 Self::CoolingDown => "cooling_down",
3703 Self::OrdinaryCapacity => "ordinary_capacity",
3704 Self::UrgentCapacity => "urgent_capacity",
3705 Self::InterruptGate => "interrupt_gate",
3706 }
3707 }
3708
3709 fn describe(self) -> &'static str {
3710 match self {
3711 Self::ClaimUnavailable => "could not claim it (held elsewhere or claim failed)",
3712 Self::RereadFailed => "could not re-read it",
3713 Self::NoLongerRunnable => "no longer runnable",
3714 Self::WaitingOnLanding => "waiting on landing",
3715 Self::CoolingDown => "quota cooldown",
3716 Self::OrdinaryCapacity => "no free ordinary slot",
3717 Self::UrgentCapacity => "urgent slot busy",
3718 Self::InterruptGate => "withheld by the interrupt sequence",
3719 }
3720 }
3721}
3722
3723#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3725pub struct DispatchReasonCount {
3726 pub reason: String,
3728 pub count: usize,
3730}
3731
3732#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3734pub struct DispatchWait {
3735 pub runnable: usize,
3737 pub reasons: Vec<DispatchReasonCount>,
3739}
3740
3741type DispatchSkips = std::collections::BTreeSet<(String, SkipReason)>;
3742
3743fn aggregate_dispatch_wait(runnable: usize, skips: &DispatchSkips) -> Option<DispatchWait> {
3744 if runnable == 0 {
3745 return None;
3746 }
3747 let mut counts = std::collections::BTreeMap::new();
3748 for (_, reason) in skips {
3749 *counts.entry(*reason).or_insert(0usize) += 1;
3750 }
3751 let mut counts: Vec<_> = counts.into_iter().collect();
3752 counts.sort_by(|(a, n), (b, m)| m.cmp(n).then(a.cmp(b)));
3753 Some(DispatchWait {
3754 runnable,
3755 reasons: counts
3756 .into_iter()
3757 .map(|(reason, count)| DispatchReasonCount {
3758 reason: reason.key().to_owned(),
3759 count,
3760 })
3761 .collect(),
3762 })
3763}
3764
3765fn interrupt_skips(before: &[String], after: &[Task]) -> DispatchSkips {
3766 before
3767 .iter()
3768 .filter(|id| !after.iter().any(|task| &task.id == *id))
3769 .map(|id| (id.clone(), SkipReason::InterruptGate))
3770 .collect()
3771}
3772
3773fn changed_dispatch_skips(previous: &mut DispatchSkips, current: DispatchSkips) -> bool {
3774 if *previous == current {
3775 return false;
3776 }
3777 *previous = current;
3778 true
3779}
3780
3781struct DispatchClaim {
3782 task: Task,
3783 claim: crate::queue::Claim,
3784 permit: Option<tokio::sync::OwnedSemaphorePermit>,
3785}
3786
3787fn claim_dispatch(
3790 queue: &Queue,
3791 candidate: &Task,
3792 cooling_down: bool,
3793 ordinary: &Arc<tokio::sync::Semaphore>,
3794 urgent: &Arc<tokio::sync::Semaphore>,
3795) -> std::result::Result<DispatchClaim, SkipReason> {
3796 let claim = queue
3797 .claim(&candidate.id)
3798 .map_err(|_| SkipReason::ClaimUnavailable)?;
3799 let task = match queue.get(&candidate.id) {
3800 Ok(t) if t.status.runnable() => t,
3801 Ok(_) => return Err(SkipReason::NoLongerRunnable),
3802 Err(e) => {
3803 tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
3804 return Err(SkipReason::RereadFailed);
3805 }
3806 };
3807 if let Some(hold) = crate::head_e2e_stop::dispatch_hold(queue, &task) {
3808 let mut held = task;
3809 hold.apply(&mut held);
3810 record(queue, &mut held);
3811 return Err(SkipReason::NoLongerRunnable);
3812 }
3813 let resume = land_resume_state(&task);
3814 if resume == LandResume::StillWaiting {
3815 return Err(SkipReason::WaitingOnLanding);
3816 }
3817 let priority = resume == LandResume::Ready;
3818 if !priority && cooling_down {
3819 return Err(SkipReason::CoolingDown);
3820 }
3821 let permit = match permit_kind(priority, task.urgent) {
3824 PermitKind::None => None,
3825 PermitKind::Urgent => Some(
3826 Arc::clone(urgent)
3827 .try_acquire_owned()
3828 .map_err(|_| SkipReason::UrgentCapacity)?,
3829 ),
3830 PermitKind::Ordinary => Some(
3831 Arc::clone(ordinary)
3832 .try_acquire_owned()
3833 .map_err(|_| SkipReason::OrdinaryCapacity)?,
3834 ),
3835 };
3836 let stamp = Timestamp::now();
3839 let mut task = task;
3840 task.dispatched_at = Some(stamp);
3841 if let Err(e) = queue.modify(&task.id, |t| {
3842 t.dispatched_at = Some(stamp);
3843 true
3844 }) {
3845 tracing::warn!("could not record dispatch order of {}: {e:#}", task.short());
3846 }
3847 Ok(DispatchClaim {
3848 task,
3849 claim,
3850 permit,
3851 })
3852}
3853
3854#[derive(Serialize, Deserialize)]
3873struct ServiceWorker {
3874 opts: Opts,
3875 queue: PathBuf,
3876 worktrees_root: PathBuf,
3877 operation: String,
3878}
3879
3880fn load_conductor(home: &Path) -> Result<Conductor> {
3881 match std::fs::read(home.join("conductor-state.json")) {
3882 Ok(body) => serde_json::from_slice(&body).context("read conductor state"),
3883 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Conductor::new()),
3884 Err(error) => Err(error.into()),
3885 }
3886}
3887
3888fn conductor_work(queue: &Queue, home: &Path) -> (Vec<Task>, Vec<Task>, Vec<Task>) {
3889 let live: std::collections::BTreeSet<_> = current_work(home, Timestamp::now())
3890 .into_iter()
3891 .map(|c| c.task)
3892 .collect();
3893 let stalled = stalled_tasks(queue, home, Timestamp::now());
3894 let stalled_ids: std::collections::BTreeSet<_> = stalled.iter().map(|t| t.id.clone()).collect();
3895 let finished = finished_tasks(queue)
3896 .into_iter()
3897 .filter(|t| !live.contains(&t.id) && !stalled_ids.contains(&t.id))
3898 .filter(|t| !awaiting_resume_with(t, |id| RunState::load_under(id, home)))
3899 .collect();
3900 let queued = queued_tasks(queue)
3901 .into_iter()
3902 .filter(|t| !live.contains(&t.id))
3903 .collect();
3904 (queued, stalled, finished)
3905}
3906
3907fn retention_service_receipt(
3910 home: &Path,
3911 operation: &str,
3912 phase: &str,
3913 outcome: &str,
3914 detail: &str,
3915 cfg: Option<&Config>,
3916) {
3917 if !matches!(operation, "housekeeping" | "disk-pressure") {
3918 return;
3919 }
3920 let receipt = serde_json::json!({"checked_at": Timestamp::now(),
3921 "version": env!("CARGO_PKG_VERSION"), "pid": std::process::id(),
3922 "operation": operation, "outcome": outcome, "detail": detail,
3923 "auto_fold": cfg.map(|c| c.disk.auto_fold),
3924 "reclaim_bytes": cfg.map(|c| c.disk.worktree_reclaim_bytes)});
3925 if let Err(error) = crate::fold_evidence::atomic_write(
3926 &home.join(format!("source-eviction-{operation}-{phase}.json")),
3927 &serde_json::to_vec(&receipt).expect("service receipt"),
3928 ) {
3929 tracing::warn!("retention service receipt failed: {error:#}");
3930 }
3931}
3932
3933async fn start_service(
3934 home: &Path,
3935 opts: &Opts,
3936 queue: &Queue,
3937 worktrees_root: &Path,
3938 operation: &str,
3939 cfg: Option<&Config>,
3940 busy: bool,
3941) -> Result<()> {
3942 let fetch_cfg = if operation == "fetch" {
3945 match prepare(&opts.repo, opts) {
3946 Ok(cfg) => Some(cfg),
3947 Err(error) => {
3948 tracing::warn!("could not reload periodic fetch configuration: {error:#}");
3949 return Ok(());
3950 }
3951 }
3952 } else {
3953 None
3954 };
3955 let cfg = fetch_cfg.as_ref().or(cfg);
3956 let ticks = home.join("service-ticks");
3957 std::fs::create_dir_all(&ticks)?;
3958 let receipt = ticks.join(format!("daemon-{operation}"));
3959 let last = std::fs::read(&receipt)
3960 .ok()
3961 .and_then(|body| serde_json::from_slice::<Timestamp>(&body).ok());
3962 let interval = match operation {
3963 "disk-pressure" => 30,
3964 "chat-goals" => 60,
3965 "cache" => CACHE_CHECK_INTERVAL_SECS,
3966 "fetch" => cfg.map_or(60, |cfg| cfg.repos.fetch_interval.max(1)),
3967 _ => opts.poll.as_secs().max(1),
3968 };
3969 let now = Timestamp::now();
3970 if !cache_check_due(last, now, interval) {
3971 retention_service_receipt(
3972 home,
3973 operation,
3974 "dispatch",
3975 "skipped",
3976 "cadence not due",
3977 cfg,
3978 );
3979 return Ok(());
3980 }
3981 let key = format!("service:daemon-{operation}");
3982 if crate::worker::active(home)?
3983 .iter()
3984 .any(|job| job.key == key)
3985 {
3986 retention_service_receipt(
3987 home,
3988 operation,
3989 "dispatch",
3990 "skipped",
3991 "service worker already active",
3992 cfg,
3993 );
3994 return Ok(());
3995 }
3996 let eligible = match operation {
3997 "conductor" => {
3998 let (queued, stalled, finished) = conductor_work(queue, home);
3999 !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
4000 && load_conductor(home)?.worth_a_look(queue, &stalled, &finished)
4001 }
4002 "maintenance" => {
4003 queue.list().iter().any(|task| {
4004 crate::triage::disk_wait_eligible(task)
4005 && task
4006 .disk_checked_at
4007 .is_none_or(|at| now.as_second() - at.as_second() >= 60)
4008 }) || Questions::at(home.join("questions"))
4009 .list_for_effects()
4010 .iter()
4011 .any(|q| {
4012 q.chosen_action().is_some_and(|action| action.maintenance())
4013 && !home
4014 .join("choice-actions")
4015 .join(format!("{}.json", q.id))
4016 .exists()
4017 })
4018 }
4019 "housekeeping" => !busy && runnable(queue).is_empty(),
4020 "cache" => {
4021 !busy
4022 && !runnable(queue).is_empty()
4023 && cfg.is_some_and(|cfg| cfg.disk.cache_limit_bytes > 0)
4024 }
4025 "disk-pressure" => busy,
4026 "fetch" => {
4027 cfg.is_some_and(|cfg| cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty())
4028 }
4029 "chat-goals" => crate::talk::Talks::at(home.join("talks"))
4030 .list()
4031 .iter()
4032 .any(|talk| {
4033 talk.status.open()
4034 && talk.pending.is_empty()
4035 && talk.pending_attachments.is_empty()
4036 && talk.goals.iter().any(|goal| goal.active())
4037 }),
4038 _ => false,
4039 };
4040 if !eligible {
4041 retention_service_receipt(
4042 home,
4043 operation,
4044 "dispatch",
4045 "skipped",
4046 if operation == "housekeeping" {
4047 "active work or runnable task queue"
4048 } else {
4049 "no active work; idle housekeeping owns scan"
4050 },
4051 cfg,
4052 );
4053 return Ok(());
4054 }
4055 retention_service_receipt(
4056 home,
4057 operation,
4058 "dispatch",
4059 "launching",
4060 "eligible and cadence due",
4061 cfg,
4062 );
4063 let request = ServiceWorker {
4064 opts: opts.absolute()?,
4065 queue: std::path::absolute(queue.root())?,
4066 worktrees_root: std::path::absolute(worktrees_root)?,
4067 operation: operation.to_owned(),
4068 };
4069 if let Err(error) =
4070 crate::worker::spawn(home, "daemon-service", &key, serde_json::to_value(request)?).await
4071 {
4072 retention_service_receipt(
4073 home,
4074 operation,
4075 "dispatch",
4076 "error",
4077 &format!("worker launch: {error:#}"),
4078 cfg,
4079 );
4080 tracing::warn!(operation, "could not launch daemon service: {error:#}");
4081 }
4082 std::fs::write(receipt, serde_json::to_vec(&now)?)?;
4083 Ok(())
4084}
4085
4086pub async fn run_service_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
4089 let request: ServiceWorker = serde_json::from_value(payload)?;
4090 let opts = &request.opts;
4091 let queue = Queue::at(request.queue);
4092 let questions = Questions::at(home.join("questions"));
4093 match request.operation.as_str() {
4094 "chat-goals" => {
4095 let talks = crate::talk::Talks::at(home.join("talks"));
4096 crate::chat_goal_runtime::sweep(&talks, false).await;
4097 }
4098 "maintenance" => {
4099 apply_maintenance_choices(&queue, &questions, home).await;
4100 triage::monitor_disk_waits(
4101 &queue,
4102 &questions,
4103 opts.config.as_deref(),
4104 Timestamp::now(),
4105 );
4106 }
4107 "conductor" => {
4108 let path = home.join("conductor-state.json");
4109 let mut conductor = load_conductor(home)?;
4110 let (queued, stalled, finished) = conductor_work(&queue, home);
4111 if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
4112 && conductor.worth_a_look(&queue, &stalled, &finished)
4113 {
4114 let cfg = prepare(&opts.repo, opts)?;
4115 conductor
4116 .maybe_run(
4117 &cfg,
4118 &opts.repo,
4119 &queue,
4120 &questions,
4121 home,
4122 &queued,
4123 &stalled,
4124 &finished,
4125 opts.max_attempts,
4126 )
4127 .await;
4128 let temporary = path.with_extension("json.tmp");
4129 std::fs::write(&temporary, serde_json::to_vec(&conductor)?)?;
4130 std::fs::rename(temporary, path)?;
4131 }
4132 }
4133 "fetch" => {
4134 let cfg = prepare(&opts.repo, opts)?;
4135 if cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty() {
4136 let outcome = clean::fetch_origins(&cfg.repos.roots, FETCH_TIMEOUT, || false).await;
4137 tracing::debug!("fetch origins: {outcome:?}");
4138 }
4139 }
4140 "cache" => {
4141 if task_jobs(home)?.is_empty() {
4142 let mut checked = None;
4143 maybe_prune_cache_between_runs(
4144 &opts.repo,
4145 opts,
4146 home,
4147 &Stop::new(),
4148 &mut checked,
4149 Timestamp::now(),
4150 )
4151 .await;
4152 }
4153 }
4154 "disk-pressure" => {
4155 if let Ok(cfg) = prepare(&opts.repo, opts) {
4156 retention_service_receipt(
4157 home,
4158 "disk-pressure",
4159 "worker",
4160 "running",
4161 "retention sweep",
4162 Some(&cfg),
4163 );
4164 crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
4165 if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
4166 tracing::warn!("disk pressure cache cleanup failed: {e:#}");
4167 }
4168 if let Err(e) = crate::build_target::prune_registered(home, &cfg.disk) {
4169 tracing::warn!("disk pressure isolated build cleanup failed: {e:#}");
4170 }
4171 for current in current_work(home, Timestamp::now()) {
4172 if let Ok(state) = RunState::load_under(¤t.run, home)
4173 && let Some(reason) = disk_gate(&state.repo, &state.config)
4174 {
4175 for job in owned_task_jobs(home)?.into_iter().filter(|job| {
4176 job.key.strip_prefix("task:") == Some(current.task.as_str())
4177 }) {
4178 request_task_park(
4179 home,
4180 &job,
4181 crate::run::ParkCause::Interrupt {
4182 reason: reason.clone(),
4183 },
4184 )?;
4185 }
4186 notices::raise_in(
4187 home,
4188 Notice::warn(
4189 "disk:pressure",
4190 "Disk pressure persists after cleanup; active workers were asked to checkpoint and park. New starts and resumes wait for free space.",
4191 ),
4192 );
4193 }
4194 }
4195 } else {
4196 retention_service_receipt(
4197 home,
4198 "disk-pressure",
4199 "worker",
4200 "error",
4201 "configuration could not be loaded",
4202 None,
4203 );
4204 }
4205 }
4206 "housekeeping" => {
4207 if task_jobs(home)?.is_empty() {
4208 match prepare(&opts.repo, opts) {
4209 Ok(cfg) => {
4210 retention_service_receipt(
4211 home,
4212 "housekeeping",
4213 "worker",
4214 "running",
4215 "retention sweep",
4216 Some(&cfg),
4217 );
4218 crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
4219 }
4220 Err(error) => retention_service_receipt(
4221 home,
4222 "housekeeping",
4223 "worker",
4224 "error",
4225 &format!("configuration: {error:#}"),
4226 None,
4227 ),
4228 }
4229 janitor(&opts.repo, opts, home, &request.worktrees_root).await;
4230 resweep_superseded_attempts(&queue, home);
4231 triage_held(&queue, home, opts).await;
4232 } else {
4233 retention_service_receipt(
4234 home,
4235 "housekeeping",
4236 "worker",
4237 "skipped",
4238 "task worker became active",
4239 None,
4240 );
4241 }
4242 }
4243 operation => bail!("unknown daemon service {operation}"),
4244 }
4245 Ok(())
4246}
4247
4248fn task_worker_spawn_error(home: &Path, request: &TaskWorker, error: anyhow::Error) -> Result<()> {
4252 let key = format!("task:{}", request.task);
4253 let payload = serde_json::to_value(request)?;
4254 if crate::worker::active(home)?
4255 .iter()
4256 .any(|job| job.key == key && job.kind == "task" && job.payload != payload)
4257 {
4258 tracing::warn!(
4259 "task {} acquired a competing worker reservation: {error:#}",
4260 crate::run::short_of(&request.task)
4261 );
4262 return Ok(());
4263 }
4264 tracing::error!("task worker startup stopped dispatch: {error:#}");
4265 notices::raise_in(
4266 home,
4267 Notice::error(
4268 "loop:worker-startup",
4269 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),
4272 ).link(Link::Task { id: request.task.clone() }),
4273 );
4274 Err(error).with_context(|| {
4275 format!(
4276 "cannot start task {} worker; dispatcher stopped; any unacknowledged reservation remains occupied",
4277 crate::run::short_of(&request.task)
4278 )
4279 })
4280}
4281
4282async fn poll(
4283 opts: &Opts,
4284 queue: &Queue,
4285 status: &Arc<Mutex<Status>>,
4286 home: &Path,
4287 worktrees_root: &Path,
4288 stop: &Stop,
4289 limits: DispatchLimits,
4290) -> Result<()> {
4291 let mut attempted = Vec::new();
4292 let mut settling_once_services = false;
4293 let interrupt_path = home.join("scheduler-interrupt.json");
4294 let mut interrupt = match std::fs::read(&interrupt_path) {
4295 Ok(body) => serde_json::from_slice(&body).context("read scheduler interrupt state")?,
4296 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Interrupt::Idle,
4297 Err(error) => return Err(error.into()),
4298 };
4299 let mut previous = std::collections::BTreeSet::<String>::new();
4300 let mut previous_skips = DispatchSkips::new();
4301 while !stop.stopped() {
4302 let jobs: Vec<_> = crate::worker::active(home)?
4303 .into_iter()
4304 .filter(|job| job.kind == "task")
4305 .collect();
4306 let requests: Vec<_> = jobs
4307 .iter()
4308 .map(|job| {
4309 serde_json::from_value::<TaskWorker>(job.payload.clone())
4310 .with_context(|| format!("read live task worker {}", job.id))
4311 })
4312 .collect::<Result<_>>()?;
4313 let live: std::collections::BTreeSet<_> = requests.iter().map(|r| r.task.clone()).collect();
4314 let owned: std::collections::BTreeSet<_> = requests
4315 .iter()
4316 .filter(|r| !r.standalone)
4317 .map(|r| r.task.clone())
4318 .collect();
4319 let current: Vec<_> = requests
4320 .iter()
4321 .zip(&jobs)
4322 .filter(|(request, _)| !request.standalone)
4323 .map(|(request, job)| Current {
4324 worker: Some(job.id.clone()),
4325 task: request.task.clone(),
4326 run: queue
4327 .get(&request.task)
4328 .ok()
4329 .and_then(|task| task.execution_runs().last().cloned())
4330 .unwrap_or_default(),
4331 })
4332 .collect();
4333 {
4334 let mut snapshot = lock(status);
4335 snapshot.polls += 1;
4336 snapshot.completed += previous.difference(&owned).count();
4337 snapshot.current = current;
4338 snapshot.idle = owned.is_empty();
4339 snapshot.dispatch_wait = None;
4340 }
4341 previous = owned.clone();
4342 stop.busy.store(owned.len(), Ordering::SeqCst);
4343
4344 let (ordinary, urgent) = available_slots(&requests, limits.max_concurrent);
4347 let sem = Arc::new(tokio::sync::Semaphore::new(ordinary));
4348 let urgent_sem = Arc::new(tokio::sync::Semaphore::new(urgent));
4349 let mut permits = Vec::new();
4350 sweep_stale_claims(queue, STALE_CLAIM);
4351 reclaim_orphaned_running(queue, opts.max_attempts, &live);
4352 reclaim_abandoned_runs(home, Timestamp::now());
4353 let questions = Questions::at(home.join("questions"));
4354
4355 crate::task_chat::sweep(
4358 queue,
4359 &crate::talk::Talks::at(home.join("talks")),
4360 &questions,
4361 home,
4362 );
4363 if let Err(error) = crate::task_inquiry::Outbox::at(home)
4364 .sweep(queue, &crate::talk::Talks::at(home.join("talks")))
4365 {
4366 tracing::warn!("task inquiry delivery remains pending: {error:#}");
4367 }
4368 repair_choice_offers(&questions);
4369 resolve_blockers(queue, &questions);
4370 apply_task_choice_actions(queue, &questions, home);
4371 triage::apply_answers(queue, &questions);
4372 reconcile_task_questions(queue, &questions);
4373 let talks = crate::talk::Talks::at(home.join("talks"));
4374 crate::chat_notify::sweep(queue, &talks, home);
4375 crate::notice_delivery::sweep(queue, &talks, home, &opts.repo);
4376 crate::chat_watch::sweep(home, &talks);
4377 if let Err(error) = crate::chat_control::reconcile_decisions(queue, home) {
4378 tracing::warn!("decision receipt reconciliation remains pending: {error:#}");
4379 }
4380 let mut turns = tokio::task::JoinSet::new();
4381 crate::chat_notify::start_turns(&talks, stop.parking(), &mut turns);
4382 while turns.join_next().await.is_some() {}
4384
4385 crate::consult::start_services(
4386 home,
4387 &opts.repo,
4388 limits.recovery_cfg.as_ref(),
4389 opts.config.as_deref(),
4390 )
4391 .await?;
4392 for operation in [
4393 "conductor",
4394 "maintenance",
4395 "housekeeping",
4396 "disk-pressure",
4397 "cache",
4398 "fetch",
4399 "chat-goals",
4400 ] {
4401 if settling_once_services {
4405 break;
4406 }
4407 if operation == "chat-goals" && stop.parking() {
4408 continue;
4409 }
4410 start_service(
4411 home,
4412 opts,
4413 queue,
4414 worktrees_root,
4415 operation,
4416 limits.recovery_cfg.as_ref(),
4417 !live.is_empty(),
4418 )
4419 .await?;
4420 }
4421 let latest = crate::worker::active(home)?;
4422 if latest.iter().any(|job| job.key == "service:daemon-cache")
4423 || latest
4424 .iter()
4425 .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4426 {
4427 stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4428 continue;
4429 }
4430 let candidates: Vec<Task> = runnable(queue)
4431 .into_iter()
4432 .filter(|task| !live.contains(&task.id))
4433 .filter(|task| !opts.once || !attempted.contains(&task.id))
4434 .collect();
4435 let in_flight: Vec<_> = owned.iter().cloned().collect();
4436 let prior_interrupt = std::mem::discriminant(&interrupt);
4437 interrupt = advance_interrupt_tick(
4438 limits.pause_for_interrupts,
4439 interrupt,
4440 &in_flight,
4441 &candidates,
4442 );
4443 if prior_interrupt != std::mem::discriminant(&interrupt) {
4446 let temporary = interrupt_path.with_extension("json.tmp");
4447 std::fs::write(&temporary, serde_json::to_vec(&interrupt)?)?;
4448 std::fs::rename(temporary, &interrupt_path)?;
4449 }
4450 if let Interrupt::Parking {
4451 parked,
4452 interrupt_task,
4453 } = &interrupt
4454 {
4455 for job in jobs.iter().filter(|job| {
4456 parked
4457 .iter()
4458 .any(|id| job.key.strip_prefix("task:") == Some(id.as_str()))
4459 }) {
4460 if crate::worker::control(home, &job.key)?.is_none() {
4461 request_task_park(
4462 home,
4463 job,
4464 crate::run::ParkCause::Interrupt {
4465 reason: format!(
4466 "task {} asked to run first",
4467 crate::run::short_of(interrupt_task)
4468 ),
4469 },
4470 )?;
4471 }
4472 }
4473 }
4474 let candidate_ids: Vec<_> = candidates.iter().map(|task| task.id.clone()).collect();
4475 let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
4476 let mut skips = interrupt_skips(&candidate_ids, &candidates);
4477 let cooling = read_cooldown(home)?.is_some_and(|until| Timestamp::now() < until);
4478 let mut started = false;
4479 let mut resync = false;
4480 for candidate in candidates {
4481 if stop.stopped() {
4482 break;
4483 }
4484 let DispatchClaim {
4485 task,
4486 claim,
4487 permit,
4488 } = match claim_dispatch(queue, &candidate, cooling, &sem, &urgent_sem) {
4489 Ok(claim) => claim,
4490 Err(reason) => {
4491 skips.insert((candidate.id, reason));
4492 continue;
4493 }
4494 };
4495 if crate::worker::active(home)?
4496 .iter()
4497 .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4498 {
4499 drop(claim);
4500 resync = true;
4501 break;
4502 }
4503 let lane = permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent);
4504 let request = TaskWorker {
4505 opts: opts.absolute()?,
4506 queue: std::path::absolute(queue.root())?,
4507 task: task.id.clone(),
4508 lane,
4509 standalone: false,
4510 };
4511 if let Err(error) = crate::worker::spawn(
4514 home,
4515 "task",
4516 &format!("task:{}", task.id),
4517 serde_json::to_value(&request)?,
4518 )
4519 .await
4520 {
4521 task_worker_spawn_error(home, &request, error)?;
4522 drop(claim);
4523 resync = true;
4524 break;
4525 }
4526 drop(claim);
4527 permits.extend(permit);
4528 attempted.push(task.id);
4529 started = true;
4530 }
4531 if !resync && !stop.stopped() {
4532 if !started {
4533 lock(status).dispatch_wait = aggregate_dispatch_wait(candidate_ids.len(), &skips);
4534 }
4535 if changed_dispatch_skips(&mut previous_skips, skips) {
4536 if previous_skips.is_empty() {
4537 tracing::info!("dispatch skips cleared");
4538 }
4539 for (task, reason) in &previous_skips {
4540 tracing::info!(
4541 task,
4542 reason = reason.key(),
4543 "task {} skipped: {}",
4544 crate::run::short_of(task),
4545 reason.describe()
4546 );
4547 }
4548 }
4549 }
4550 if started || resync {
4551 continue;
4552 }
4553 if owned.is_empty() && opts.once {
4554 settling_once_services = true;
4555 if crate::worker::active(home)?.iter().any(|job| {
4559 job.kind == "daemon-service"
4560 && matches!(
4561 job.key.as_str(),
4562 "service:daemon-housekeeping"
4563 | "service:daemon-conductor"
4564 | "service:daemon-maintenance"
4565 )
4566 }) {
4567 stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4568 continue;
4569 }
4570 break;
4571 }
4572 stop.idle(if live.is_empty() {
4573 opts.poll
4574 } else {
4575 RECHECK_WHILE_BUSY.min(opts.poll)
4576 })
4577 .await;
4578 }
4579 stop.busy.store(0, Ordering::SeqCst);
4582 lock(status).dispatch_wait = None;
4583 Ok(())
4584}
4585
4586async fn resume_owner_lock(home: &Path, id: &str) -> Result<crate::pr_head::OwnerLock> {
4590 let busy = |error: &anyhow::Error| {
4591 error.downcast_ref::<std::io::Error>().is_some_and(|error| {
4592 error.kind() == std::io::ErrorKind::WouldBlock
4593 || cfg!(windows) && error.raw_os_error() == Some(33)
4594 })
4595 };
4596 match crate::pr_head::owner_lock(home, id) {
4597 Ok(lock) => return Ok(lock),
4598 Err(error) if busy(&error) => {}
4599 Err(error) => return Err(error),
4600 }
4601 let wait = RunState::load_under(id, home)?
4602 .config
4603 .graph
4604 .timeout_resource_wait;
4605 crate::pr_head::owner_lock_wait(home, id, Duration::from_secs(wait)).await
4606}
4607
4608async fn public_resume_owner(
4612 home: &Path,
4613 runs: &[String],
4614 repo: &Path,
4615) -> Result<Option<RunState>> {
4616 let mut owner = None;
4617 for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
4618 let _lock = resume_owner_lock(home, id).await?;
4619 let state = RunState::load_under(id, home)?;
4620 if state.released()
4621 || state.retired_to.is_some()
4622 || state.pr_taken_over_by.is_some()
4623 || !crate::handover::landing_checkpoint(&state)
4624 {
4625 continue;
4626 }
4627 anyhow::ensure!(
4628 crate::git::toplevel(&state.repo).await?.canonicalize()?
4629 == crate::git::toplevel(repo).await?.canonicalize()?,
4630 "public owner repository differs; inspect run lineage"
4631 );
4632 anyhow::ensure!(
4633 owner.is_none(),
4634 "multiple retained public owners; inspect run lineage"
4635 );
4636 if let Some(reason) = crate::handover::resume_refusal_under(&state, Some(home)) {
4637 anyhow::bail!(reason.diagnostic(&state));
4638 }
4639 let claimed = is_working_on_other(home, id, Timestamp::now())?;
4640 anyhow::ensure!(
4641 state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
4642 "public owner's driver is live or unknown; wait before retrying"
4643 );
4644 owner = Some(state);
4645 }
4646 Ok(owner)
4647}
4648
4649async fn attempt(
4655 opts: &Opts,
4656 queue: &Queue,
4657 status: &Arc<Mutex<Status>>,
4658 stop: &Stop,
4659 interrupt_pause: crate::graph::Pause,
4660 task: &mut Task,
4661) -> Vec<QuotaLoss> {
4662 if let Some(request) = task.sync_only.clone() {
4663 Box::pin(attempt_sync_only(
4664 queue,
4665 status,
4666 stop,
4667 interrupt_pause,
4668 task,
4669 request,
4670 ))
4671 .await;
4672 return Vec::new();
4673 }
4674 let repo = repo_for(task, &opts.repo);
4675 tracing::info!(
4676 "task {} — {} (repo {})",
4677 task.short(),
4678 task.title,
4679 repo.display()
4680 );
4681
4682 let public_owner = match public_resume_owner(&crate::run::home(), &task.runs, &repo).await {
4683 Ok(owner) => owner,
4684 Err(e) => {
4685 task.hold_machine(Some(format!(
4686 "Cannot verify existing public owner: {e:#}; no attempt started."
4687 )));
4688 record(queue, task);
4689 return Vec::new();
4690 }
4691 };
4692 let resume_runs = public_owner
4693 .as_ref()
4694 .map(|s| vec![s.id.clone()])
4695 .unwrap_or_else(|| task.execution_runs().to_vec());
4696
4697 if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
4701 && previous
4702 .merge_decision
4703 .as_ref()
4704 .is_some_and(|decision| !decision.closed)
4705 && previous.status != RunStatus::Landing
4706 && !crate::merge_decision::resumable_hold(&previous)
4707 {
4708 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)));
4709 record(queue, task);
4710 return Vec::new();
4711 }
4712 let stop_owner = resume_runs
4713 .last()
4714 .and_then(|id| RunState::load(id).ok())
4715 .filter(|state| {
4716 crate::merge_decision::resumable_hold(state)
4717 || state.status == RunStatus::Landing
4718 && state.land_approval.as_ref().is_some_and(|binding| {
4719 Questions::open()
4720 .get_for_effects(&binding.question)
4721 .is_ok_and(|q| {
4722 q.run == state.id
4723 && q.resolution()
4724 .as_deref()
4725 .is_some_and(crate::merge_decision::stops)
4726 })
4727 })
4728 });
4729 if let Some(owner) = stop_owner {
4730 let mut runner = match Runner::resume(&owner.id) {
4731 Ok(runner) => runner,
4732 Err(e) => {
4733 task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
4734 record(queue, task);
4735 return Vec::new();
4736 }
4737 };
4738 runner.on_pause(stop.pause());
4739 runner.watch_interrupt(interrupt_pause);
4740 let quota_before = runner.state.quota.clone();
4741 let before_start = task.clone();
4742 task.start(owner.id.clone());
4743 if let Err(error) = queue.put(task) {
4744 *task = before_start;
4745 let error = runner.fail_startup("task-start", error);
4746 if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
4747 task.record_startup_failure(failure.clone());
4748 }
4749 task.hold_manual(Some(format!(
4750 "Could not persist task start; no agents dispatched: {error:#}"
4751 )));
4752 record(queue, task);
4753 return Vec::new();
4754 }
4755 lock(status).current.push(Current {
4756 worker: None,
4757 task: task.id.clone(),
4758 run: owner.id,
4759 });
4760 runner.state.carry_dispatched_resumes(task);
4761 runner.state.next_pass_task_entry = true;
4762 let result = runner.execute().await;
4763 return finish_attempt(
4764 opts.max_attempts,
4765 queue,
4766 task,
4767 &runner.state,
4768 "a_before,
4769 result,
4770 );
4771 }
4772
4773 if let Some(owner) = &public_owner
4774 && (task.fresh_start || !may_resume_run(owner, task))
4775 {
4776 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)));
4777 record(queue, task);
4778 return Vec::new();
4779 }
4780
4781 if let Some(state) = task
4782 .execution_runs()
4783 .last()
4784 .and_then(|id| RunState::load(id).ok())
4785 && let Some(reason) = crate::repair_budget::conflict_failure(task, &state)
4786 {
4787 task.hold_machine(Some(reason));
4788 record(queue, task);
4789 return Vec::new();
4790 }
4791
4792 if let Some(held) = crate::base_sync_recovery::held_run(queue, task)
4793 && !task.fresh_start
4794 && task.pr_recovery.is_none()
4795 {
4796 let sequencer_resume = crate::repair_budget::legacy::resumable_sequencer_stop(&held)
4799 && task.review_branch.is_none()
4800 && task.assignment_accepts(&held)
4801 && compatible_run_instruction(&held, task)
4802 && task
4803 .resume_override
4804 .as_ref()
4805 .is_some_and(|pin| pin.pinned_run.as_ref() == Some(&held.id));
4806 let authorized = if sequencer_resume || crate::repair_budget::conflict_pending(task, &held)
4809 {
4810 true
4811 } else if task.resumption.is_some() && compatible_run_instruction(&held, task) {
4812 let home = queue.root().parent().expect("queue has a home");
4813 match Runner::authorize_base_recovery_from_resumption(home, &held.id, &task.id).await {
4814 Ok(()) => true,
4815 Err(error) => {
4816 tracing::debug!(run = %held.id, %error, "base recovery resumption refused");
4817 false
4818 }
4819 }
4820 } else {
4821 false
4822 };
4823 if !authorized {
4824 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())));
4825 task.base_sync_notice(&held);
4827 task.resume_override = None;
4828 record(queue, task);
4829 return Vec::new();
4830 }
4831 }
4832 let head_e2e_approval = match crate::head_e2e_stop::check_attempt(queue, task) {
4833 Some(crate::head_e2e_stop::AttemptGate::Hold(hold)) => {
4834 hold.apply(task);
4835 record(queue, task);
4836 return Vec::new();
4837 }
4838 Some(crate::head_e2e_stop::AttemptGate::ConsumeOwnerApproval {
4839 run,
4840 stop_id,
4841 generation,
4842 approval_at,
4843 }) => Some((run, stop_id, generation, approval_at)),
4844 None => None,
4845 };
4846 let unfinished = (!task.fresh_start)
4847 .then(|| unfinished_run(&resume_runs, task.short()))
4848 .flatten()
4849 .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
4850 let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
4851 if task.repair_grants.last().is_some_and(|receipt| {
4852 task.execution_runs().last() == Some(&receipt.request.run)
4853 && task.operator_decided_at == receipt.decision
4854 && previous
4855 .as_ref()
4856 .is_none_or(|run| run.id != receipt.request.run)
4857 }) {
4858 task.hold_unrequested_retry(Some(
4859 "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(),
4860 ));
4861 record(queue, task);
4862 return Vec::new();
4863 }
4864 if let Some(id) = &task.disk_resume_run
4865 && unfinished.as_ref() != Some(id)
4866 {
4867 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()));
4868 record(queue, task);
4869 return Vec::new();
4870 }
4871
4872 if !task.fresh_start
4873 && task.pr_recovery.is_none()
4874 && task.review_branch.is_none()
4875 && task.resume_override.is_none()
4876 && previous
4877 .as_ref()
4878 .is_some_and(|run| run.retired_to.is_some())
4879 && unfinished.is_none()
4880 {
4881 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()));
4882 record(queue, task);
4883 return Vec::new();
4884 }
4885
4886 let saved_recovery = previous.as_ref().filter(|run| {
4887 task.replacement.is_none()
4888 && task.pr_recovery.as_ref().is_some_and(|selected| {
4889 selected
4890 .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
4891 .is_ok()
4892 && selected_starter(selected, Some(run), unfinished.as_deref())
4893 == Starter::Resume(run.id.clone())
4894 })
4895 });
4896
4897 let explicit = match &task.overrides {
4901 Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
4902 Some(_) => opts.config.as_deref(),
4903 None => opts.config.as_deref(),
4904 };
4905 let (mut config, layers) = if let Some(run) = saved_recovery {
4906 let mut saved = run.clone();
4909 if let Err(e) = saved.configure_recovery_resume() {
4910 task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
4911 record(queue, task);
4912 return Vec::new();
4913 }
4914 (saved.config, Vec::new())
4915 } else {
4916 let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
4917 Ok(loaded) => loaded,
4918 Err(e) => {
4919 let reason = format!("[config] {e:#}");
4920 record_config_failure(task, &e);
4921 task.last_error = Some(reason.clone());
4922 task.hold_machine(Some(reason));
4923 record(queue, task);
4924 return Vec::new();
4925 }
4926 };
4927 if let Err(e) = apply_options(&mut config, opts, task) {
4928 task.hold_manual(Some(format!(
4929 "[config] {e:#}; correct the merge override before releasing the task"
4930 )));
4931 record(queue, task);
4932 return Vec::new();
4933 }
4934 if let Some(selected) = &task.pr_recovery
4935 && let Err(e) = selected.configure(&mut config)
4936 {
4937 task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
4938 record(queue, task);
4939 return Vec::new();
4940 }
4941 (config, layers)
4942 };
4943 let config_evidence = crate::pr_recovery::ConfigEvidence {
4944 layers,
4945 overrides: task.overrides.clone(),
4946 daemon_merge: task
4947 .overrides
4948 .as_ref()
4949 .is_none_or(|o| o.inherit_daemon_options)
4950 .then(|| opts.merge.clone())
4951 .flatten(),
4952 };
4953 apply_task_implementers(&mut config, task);
4954 if let Some(replacement) = &task.replacement {
4955 let safe = RunState::load(&replacement.run).is_ok_and(|old| {
4956 old.liveness(false) == Liveness::Dead
4957 && old.merge_decision.as_ref().is_some_and(|d| {
4958 d.closed
4959 && d.question == replacement.question
4960 && d.replacement_run.as_ref().is_none_or(|run| {
4961 task.execution_runs().last() == Some(run)
4962 && RunState::load(run).is_ok_and(|current| {
4963 current.replaces.as_ref().is_some_and(|pin| {
4964 pin.question == replacement.question
4965 && pin.agent == replacement.agent
4966 })
4967 })
4968 })
4969 })
4970 });
4971 if !safe {
4972 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()));
4973 record(queue, task);
4974 return Vec::new();
4975 }
4976 match config.agent(&replacement.agent) {
4977 Ok(agent) if crate::agent::installed(agent) => {}
4978 _ => {
4979 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)));
4980 record(queue, task);
4981 return Vec::new();
4982 }
4983 }
4984 config.graph.implementers = 1;
4985 config.graph.land_approval = true;
4986 config.merge.mode = MergeMode::Pr;
4987 config.graph.selected_implementer = Some(replacement.agent.clone());
4988 }
4989 let p = phrases(&config.graph.language);
4990 let start_failed = p.could_not_start;
4991 if let Ok(base) =
4996 crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
4997 .await
4998 && let Ok(head) =
4999 crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
5000 {
5001 let mut inputs = crate::queue::recovery_inputs(&task.sources);
5002 if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
5003 let source = crate::git::rev_parse(&repo, branch)
5004 .await
5005 .unwrap_or_default();
5006 inputs.push_str(&format!(";review:{branch}:{source}"));
5007 }
5008 if let Some(reason) = task
5009 .recovery_exhausted(
5010 &head,
5011 &inputs,
5012 task.attempt_limit
5013 .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
5014 )
5015 .filter(|_| {
5016 !task.repair_grants.last().is_some_and(|receipt| {
5017 RunState::load(&receipt.request.run)
5018 .is_ok_and(|run| crate::repair_budget::pending(task, &run))
5019 })
5020 })
5021 {
5022 task.hold_recovery_budget(
5023 reason,
5024 crate::queue::RecoveryAdmission { base: head, inputs },
5025 );
5026 record(queue, task);
5027 return Vec::new();
5028 }
5029 task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
5030 }
5031
5032 let consume_review = !previous
5053 .as_ref()
5054 .is_some_and(|state| crate::repair_budget::pending(task, state));
5055 let review_branch = consume_review
5056 .then(|| review_branch_for(task, previous.as_ref()))
5057 .flatten();
5058 let branch_exists = match review_branch {
5059 Some(branch) => crate::git::branch_exists(&repo, branch)
5060 .await
5061 .unwrap_or(false),
5062 None => false,
5063 };
5064 let proposed = review_retry_starter(
5068 task,
5069 previous.as_ref(),
5070 review_branch,
5071 branch_exists,
5072 unfinished.as_deref(),
5073 );
5074 let retry_selected = task.replacement.is_some()
5075 && task.resumption.is_some()
5076 && !task.fresh_start
5077 && previous.as_ref().is_some_and(|run| {
5078 run.replaces.is_some()
5079 && ((run.status == RunStatus::Failed && run.viable().is_empty())
5080 || (run.status == RunStatus::Blocked && run.tally.is_none()))
5081 });
5082 let stop_pin = task
5083 .resume_override
5084 .as_ref()
5085 .filter(|pin| {
5086 Questions::open()
5087 .get_for_effects(&pin.question_id)
5088 .is_ok_and(|q| {
5089 q.node == land::APPROVAL_NODE
5090 && q.resolution()
5091 .as_deref()
5092 .is_some_and(crate::merge_decision::stops)
5093 })
5094 })
5095 .and_then(|pin| pin.pinned_run.clone());
5096 let granted_run = task.repair_grants.last().and_then(|receipt| {
5097 let state = RunState::load(&receipt.request.run).ok()?;
5098 crate::repair_budget::pending(task, &state).then(|| receipt.request.run.clone())
5099 });
5100 let starter = if let Some(run) = granted_run {
5101 Starter::Resume(run)
5102 } else if let Some(owner) = &public_owner {
5103 Starter::Resume(owner.id.clone())
5104 } else if let Some(run) = stop_pin {
5105 Starter::Resume(run)
5108 } else if retry_selected {
5109 Starter::Resume(previous.as_ref().unwrap().id.clone())
5110 } else if let Some(selected) = &task.pr_recovery {
5111 if selected
5112 .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
5113 .is_ok()
5114 {
5115 selected_starter(selected, previous.as_ref(), unfinished.as_deref())
5116 } else {
5117 Starter::Review(selected.branch.clone())
5118 }
5119 } else {
5120 starter_with_implementers(task, previous.as_ref(), proposed)
5121 };
5122 let disk_reason = match &starter {
5125 Starter::Resume(id) => previous.as_ref().filter(|run| &run.id == id).map_or_else(
5126 || {
5127 RunState::load(id)
5128 .ok()
5129 .and_then(|run| disk_gate(&run.repo, &run.config))
5130 },
5131 |run| disk_gate(&run.repo, &run.config),
5132 ),
5133 _ => disk_gate(&repo, &config),
5134 };
5135 if let Some(reason) = disk_reason {
5136 task.notice_cause("disk-space", None, None);
5137 task.last_error = Some(reason.clone());
5138 let disk_checked_at = task.disk_checked_at;
5139 task.hold_machine(Some(reason.clone()));
5140 if matches!(starter, Starter::Resume(_)) {
5141 task.mark_disk_capacity();
5142 } else {
5143 task.mark_startup_disk_capacity();
5144 }
5145 task.disk_checked_at = disk_checked_at;
5146 record(queue, task);
5147 tracing::warn!("holding {} for want of disk space: {reason}", task.short());
5148 notices::raise(
5149 Notice::warn(
5150 &format!("disk:{}", repo.display()),
5151 format!("Task {} is waiting for disk space. It will resume automatically when disk and output admission checks succeed.", task.id),
5152 )
5153 .link(Link::Task {
5154 id: task.id.clone(),
5155 }),
5156 );
5157 return Vec::new();
5158 }
5159 let review_branch = if consume_review {
5160 let valid = review_branch.is_some();
5161 task.review_instruction = None;
5162 task.review_branch.take().filter(|_| valid)
5163 } else {
5164 None
5165 };
5166 if let Some(pin) = &task.resume_override
5169 && let Some(run) = &pin.pinned_run
5170 && starter != Starter::Resume(run.clone())
5171 {
5172 let run = run.clone();
5173 task.notice_cause("resume-owner", Some(&run), None);
5174 task.hold_machine(Some(format!(
5175 "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
5176 task.id
5177 )));
5178 record(queue, task);
5179 return Vec::new();
5180 }
5181 if let Some(run) = &task.disk_resume_run
5185 && starter != Starter::Resume(run.clone())
5186 {
5187 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()));
5188 record(queue, task);
5189 return Vec::new();
5190 }
5191 if task.replacement.is_some()
5192 && previous.as_ref().is_some_and(|run| run.replaces.is_some())
5193 && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
5194 {
5195 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()));
5196 record(queue, task);
5197 return Vec::new();
5198 }
5199 if let Some((ref run, ..)) = head_e2e_approval
5200 && starter != Starter::Resume(run.clone())
5201 {
5202 task.hold_machine(Some(format!(
5203 "Conclusive head_e2e stop on run {run} cannot resume safely with current task settings; inspect `magi show {run}` before retrying. No replacement competition was started."
5204 )));
5205 record(queue, task);
5206 return Vec::new();
5207 }
5208 if let Some(reason) = retained_attempt_hold(
5209 task,
5210 &starter,
5211 config.disk.retained_attempt_limit,
5212 RunState::load,
5213 ) {
5214 if let Starter::Review(branch) = &starter {
5217 task.review_branch = Some(branch.clone());
5218 }
5219 task.hold_unrequested_retry(Some(reason));
5220 record(queue, task);
5221 return Vec::new();
5222 }
5223 let attachments = match task_attachments(queue, task) {
5228 Ok(a) => a,
5229 Err(e) => {
5230 task.attempts += 1;
5231 task.fail_startup_target(
5232 "startup-attachments",
5233 e.name.clone(),
5234 format!("{start_failed}{e:#}"),
5235 opts.max_attempts,
5236 );
5237 record(queue, task);
5238 return Vec::new();
5239 }
5240 };
5241 let startup_pause = stop.pause();
5242 let startup_interrupt = interrupt_pause.clone();
5243 let wait = crate::repo_lock::WaitPolicy::new(
5244 Duration::from_secs(config.graph.timeout_resource_wait),
5245 move || startup_pause.parked() || startup_interrupt.parked(),
5246 );
5247 let started = wait.scope(Box::pin(async { match &starter {
5250 Starter::Review(_) if task.pr_recovery.is_some() => {
5251 let selected = task.pr_recovery.clone().expect("selected recovery");
5252 match selected.check_task_assignment(&task.id, &task.instruction, task.reassignments.len()) {
5253 Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
5254 .await
5255 .map(|mut r| {
5256 r.state.attachments = attachments.clone();
5257 r
5258 }),
5259 Err(e) => Err(e),
5260 }
5261 }
5262 Starter::Review(branch) => {
5263 tracing::info!(
5264 "task {} reopens `{branch}` as a review-only pass",
5265 task.short()
5266 );
5267 let takeover = crate::handover::Takeover {
5270 earlier: task.earlier_attempts().to_vec(),
5271 home: crate::run::home(),
5272 choice: take_divergence_answer(branch, &config.merge.remote, task),
5273 task_instruction: Some(instruction_for(task)),
5274 };
5275 Runner::review_taking_over(
5276 &repo,
5277 branch,
5278 config,
5279 Some(takeover),
5280 crate::run::Origin::queue(&task.id),
5281 )
5282 .await
5283 }
5284 Starter::Resume(id) => {
5285 tracing::info!("resuming run {id} rather than competing again");
5286 Runner::resume(id).and_then(|mut r| {
5287 if retry_selected {
5288 for candidate in &mut r.state.candidates {
5291 candidate.failed = None;
5292 candidate.empty = false;
5293 candidate.commits = 0;
5294 }
5295 r.state.status = RunStatus::Implementing;
5296 r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
5297 }
5298 if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
5299 r.state.sources = task.sources.clone();
5300 }
5301 if r.state.prep_failure.is_some() {
5302 let approval = task
5303 .resumption
5304 .as_ref()
5305 .context("preparation retry requires an explicit task release")?;
5306 r.retry_preparation(approval.at)?;
5307 }
5308 if let Some(instruction) =
5309 prepare_instruction(&starter, Some(&r.state.instruction), task)
5310 {
5311 r.state.instruction = instruction;
5312 }
5313 r.state.attachments = attachments.clone();
5314 if task.replacement.is_some() {
5315 r.state.config.merge.mode = MergeMode::Pr;
5316 r.state.config.graph.land_approval = true;
5317 }
5318 if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
5322 .overrides
5323 .as_ref()
5324 .and_then(|o| o.merge.as_deref())
5325 .and_then(|m| merge_mode(m).ok())
5326 {
5327 r.state.config.merge.mode = mode;
5328 }
5329 Ok(r)
5330 })
5331 }
5332 Starter::Start => {
5333 if let Some(branch) = &review_branch {
5334 tracing::warn!(
5335 "conductor chose review for task {} but branch `{branch}` no longer \
5336 exists; requeuing as a fresh competition instead",
5337 task.short()
5338 );
5339 }
5340 let instruction = prepare_instruction(&starter, None, task)
5341 .unwrap_or_else(|| task.instruction.clone());
5342 Runner::start_naming(
5343 &repo,
5344 instruction,
5345 &task.title,
5346 config,
5347 crate::run::Origin::queue(&task.id),
5348 )
5349 .await
5350 .map(|mut r| {
5351 r.state.attachments = attachments.clone();
5352 r.state.sources = task.sources.clone();
5353 r
5354 })
5355 }
5356 }})).await;
5357 if let Err(error) = &started
5358 && let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>()
5359 {
5360 task.record_startup_failure(failure.clone());
5361 }
5362 let mut runner = match started {
5363 Ok(r) => r,
5364 Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
5365 let detail = format!("{e:#}");
5366 task.last_error = Some(detail.clone());
5367 if e.is::<crate::build_target::AdmissionDiskWait>()
5368 && let Starter::Review(branch) = &starter
5369 && review_branch.is_some()
5370 {
5371 task.review_branch = Some(branch.clone());
5372 task.review_instruction = Some(task.instruction.clone());
5373 }
5374 if stop.parking() || interrupt_pause.parked() {
5375 let attempts = task.attempts;
5376 task.park(e.to_string());
5377 task.attempts = attempts;
5379 } else if e.is::<crate::build_target::AdmissionDiskWait>() {
5380 let disk_checked_at = task.disk_checked_at;
5381 task.hold_machine(Some(detail));
5382 task.mark_startup_disk_capacity();
5383 task.disk_checked_at = disk_checked_at;
5384 } else {
5385 task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
5386 }
5387 record(queue, task);
5388 return Vec::new();
5389 }
5390 Err(e) if task.pr_recovery.is_some() => {
5394 task.startup_notice_cause("startup-public-head");
5395 task.attempts += 1;
5396 task.last_error = Some(format!("{start_failed}{e:#}"));
5397 task.hold_unrequested_retry(Some(format!(
5398 "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."
5399 )));
5400 record(queue, task);
5401 return Vec::new();
5402 }
5403 Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
5404 let detail = match e.downcast_ref::<crate::handover::Refused>() {
5405 Some(r) => (p.handover_refused)(r),
5406 None => format!("{e:#}"),
5407 };
5408 task.startup_notice_cause("startup-handover");
5409 let reason = format!("{start_failed}{detail}");
5410 task.last_error = Some(reason.clone());
5411 let branch = match &starter {
5414 Starter::Review(branch) => Some(branch.clone()),
5415 _ => None,
5416 };
5417 task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
5421 record(queue, task);
5422 tracing::warn!(
5423 "holding {} for a branch it cannot take over: {e:#}",
5424 task.short()
5425 );
5426 return Vec::new();
5427 }
5428 Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
5433 let d = e
5434 .downcast_ref::<crate::reconcile::Diverged>()
5435 .expect("checked by the guard");
5436 let mut q = ask::Question::new(
5437 task.id.clone(),
5438 crate::reconcile::NODE.to_owned(),
5439 crate::reconcile::SEAT.to_owned(),
5440 d.summary(),
5441 d.detail(),
5442 d.choices(),
5443 );
5444 match Questions::open().put(&mut q) {
5445 Ok(()) => {
5446 task.last_error = Some(format!("{e:#}"));
5447 task.review_branch = Some(d.branch.clone());
5450 task.review_instruction = Some(task.instruction.clone());
5451 task.block(vec![q.id.clone()], Some(d.summary()));
5452 }
5453 Err(put) => {
5454 tracing::warn!("could not file the divergence question: {put:#}");
5455 task.attempts += 1;
5456 task.fail_startup(
5457 "startup-question-store",
5458 format!("{start_failed}{e:#}"),
5459 opts.max_attempts,
5460 );
5461 }
5462 }
5463 record(queue, task);
5464 return Vec::new();
5465 }
5466 Err(e) => {
5467 if e.downcast_ref::<crate::reconcile::Stale>().is_some()
5473 && let Starter::Review(branch) = &starter
5474 {
5475 task.review_branch = Some(branch.clone());
5476 task.review_instruction = Some(task.instruction.clone());
5477 task.last_error = Some(format!("{start_failed}{e:#}"));
5478 task.status = crate::queue::TaskStatus::Failed;
5479 record(queue, task);
5480 return Vec::new();
5481 }
5482 task.attempts += 1;
5483 task.last_error = Some(format!("{start_failed}{e:#}"));
5484 task.startup_notice_cause("startup-source");
5485 task.hold_unrequested_retry(Some(format!(
5486 "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
5487 )));
5488 record(queue, task);
5489 return Vec::new();
5490 }
5491 };
5492 if !matches!(starter, Starter::Resume(_))
5493 && let Some((mode, source)) = task.build_cache_override(&runner.state.config)
5494 {
5495 runner
5496 .state
5497 .event("build-cache", format!("{mode} selected by {source}"));
5498 }
5499 if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
5500 runner.state.recovery_config = Some(config_evidence);
5501 }
5502 if let Some(replacement) = &task.replacement {
5503 if matches!(starter, Starter::Start) {
5504 runner.state.instruction.push_str(&format!(
5505 "\n\n# Replacement review context\n{}",
5506 replacement.context
5507 ));
5508 }
5509 runner.state.replaces = Some(replacement.clone());
5510 runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
5511 if let Ok(mut old) = RunState::load(&replacement.run)
5512 && let Some(d) = &mut old.merge_decision
5513 {
5514 d.replacement_run = Some(runner.state.id.clone());
5515 old.event(
5516 "replacement",
5517 format!(
5518 "replacement run {} owns the next attempt; old PR remains closed",
5519 runner.state.id
5520 ),
5521 );
5522 if let Err(e) = old.save() {
5523 let error = runner.fail_startup("replacement-history", e);
5524 if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5525 task.record_startup_failure(failure.clone());
5526 }
5527 task.hold_manual(Some(format!(
5528 "Could not link replacement history: {error:#}; no agents dispatched"
5529 )));
5530 record(queue, task);
5531 return Vec::new();
5532 }
5533 }
5534 }
5535 runner.state.task_instruction = Some(task.instruction.clone());
5536 runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
5539 if runner.state.origin_chat.is_none() {
5540 runner.state.origin_chat = task.chat_talk().map(str::to_owned);
5541 }
5542 runner.on_pause(stop.pause());
5544 runner.watch_interrupt(interrupt_pause);
5548
5549 let run = runner.state.id.clone();
5552 let before_start = task.clone();
5553 task.start(run.clone());
5554 if let Err(error) = queue.put(task) {
5555 *task = before_start;
5556 let error = runner.fail_startup("task-start", error);
5557 if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5558 task.record_startup_failure(failure.clone());
5559 }
5560 task.hold_manual(Some(format!(
5561 "Could not persist task start; no agents dispatched: {error:#}"
5562 )));
5563 record(queue, task);
5564 return Vec::new();
5565 }
5566 if task.status != TaskStatus::Running {
5567 return Vec::new();
5569 }
5570 lock(status).current.push(Current {
5571 worker: None,
5572 task: task.id.clone(),
5573 run,
5574 });
5575
5576 let quota_before = runner.state.quota.clone();
5579 runner.state.carry_dispatched_resumes(task);
5580 runner.state.entry_resumption_generation =
5581 Some(task.resumption.as_ref().map_or(0, |r| r.generation));
5582 if let Some((run, stop_id, generation, approval_at)) = head_e2e_approval
5583 && runner.state.id == run
5584 {
5585 crate::head_e2e_stop::record_consumed_approval(
5586 &mut runner.state,
5587 &task.id,
5588 &stop_id,
5589 generation,
5590 approval_at,
5591 );
5592 }
5593 runner.state.next_pass_task_entry = true;
5594 let result = runner.execute().await;
5595 finish_attempt(
5596 opts.max_attempts,
5597 queue,
5598 task,
5599 &runner.state,
5600 "a_before,
5601 result,
5602 )
5603}
5604
5605async fn attempt_sync_only(
5606 queue: &Queue,
5607 status: &Arc<Mutex<Status>>,
5608 stop: &Stop,
5609 interrupt: crate::graph::Pause,
5610 task: &mut Task,
5611 request: crate::base_sync_only::Request,
5612) {
5613 let result = async {
5614 anyhow::ensure!(
5615 task.status == TaskStatus::Queued
5616 && task.execution_runs().last() == Some(&request.run)
5617 && task.resume_override.as_ref().is_some_and(
5618 |pin| pin.at == request.at && pin.pinned_run.as_ref() == Some(&request.run)
5619 ),
5620 "sync-base-only request no longer owns the exact queued run"
5621 );
5622 let mut runner = Runner::resume(&request.run)?;
5623 anyhow::ensure!(
5624 public_resume_owner(&crate::run::home(), &task.runs, &runner.state.repo)
5625 .await?
5626 .is_none(),
5627 "the task still has a public execution owner"
5628 );
5629 anyhow::ensure!(
5630 !stop.parking() && !interrupt.parked(),
5631 "paused before base synchronization"
5632 );
5633 let original = task.clone();
5634 task.start(request.run.clone());
5635 task.attempts = original.attempts;
5636 if let Err(error) = queue.put(task) {
5637 *task = original;
5638 return Err(error);
5639 }
5640 if task.status != TaskStatus::Running || task.sync_only.as_ref() != Some(&request) {
5641 return Ok(());
5642 }
5643 lock(status).current.push(Current {
5644 worker: None,
5645 task: task.id.clone(),
5646 run: request.run.clone(),
5647 });
5648 runner.on_pause(stop.pause());
5649 runner.watch_interrupt(interrupt);
5650 runner.execute_sync_only(request.clone()).await
5651 }
5652 .await;
5653 if task.sync_only.as_ref() == Some(&request) {
5654 let saved = RunState::load(&request.run).ok();
5655 let detail = result.err().map(|error| {
5656 format!("Base synchronization only: {error:#}; verification was not allowed")
5657 });
5658 crate::base_sync_only::settle(task, &request, saved.as_ref(), detail);
5659 record(queue, task);
5660 }
5661}
5662
5663pub fn finish_attempt(
5668 max_attempts: usize,
5669 queue: &Queue,
5670 task: &mut Task,
5671 state: &RunState,
5672 quota_before: &[QuotaLoss],
5673 result: Result<()>,
5674) -> Vec<QuotaLoss> {
5675 let detail = match result {
5676 Ok(()) => describe(state),
5677 Err(e) => format!("{e:#}"),
5678 };
5679 let fresh = losses_this_attempt(quota_before, &state.quota);
5680 let verdict = Verdict {
5681 status: state.status,
5682 left_pr: state.pr.is_some(),
5685 quota_hit: !fresh.is_empty(),
5691 parked: state.parked,
5695 no_viable_candidates: state.viable().is_empty(),
5698 };
5699 if let Some(replacement) = &state.replaces
5700 && let Some(pr) = &state.pr
5701 && let Ok(mut old) = RunState::load(&replacement.run)
5702 && let Some(d) = &mut old.merge_decision
5703 {
5704 d.replacement_pr = Some(pr.url.clone());
5705 let _ = old.save();
5706 }
5707 settle_and_diagnose(task, verdict, &detail, max_attempts, state);
5708 if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
5709 task.hold_unrequested_retry(Some(format!(
5710 "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.",
5711 task.short()
5712 )));
5713 }
5714 if task.status == TaskStatus::Done {
5715 supersede_prior_runs(task, &crate::run::home());
5716 }
5717 record(queue, task);
5718 tracing::info!(
5719 "task {} is {} after run {} ({})",
5720 task.short(),
5721 task.status.as_str(),
5722 state.short(),
5723 label(state.status)
5724 );
5725 fresh
5726}
5727
5728pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
5732 if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
5735 && !awaiting_resume_with(task, RunState::load)
5736 && withheld_text_wait(task).is_none()
5740 && !(task.fresh_start && task.replacement.is_some())
5741 {
5742 let why = task.last_error.clone().map_or_else(
5743 || "the run did not finish".to_owned(),
5744 |e| format!("the run did not finish: {e}"),
5745 );
5746 task.hold_unrequested_retry(Some(format!(
5747 "{why}. It was started by hand, so it is not retried \
5748 automatically; `magi task release` retries it."
5749 )));
5750 record(queue, task);
5751 }
5752}
5753
5754#[must_use]
5758pub fn loop_would_resume(run: &str) -> bool {
5759 unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
5760}
5761
5762#[must_use]
5772pub fn foreign_loop(
5773 reading: Option<&Reading>,
5774 now: Timestamp,
5775 own_pid: u32,
5776) -> Option<Option<u32>> {
5777 let reading = reading.filter(|r| r.running(now))?;
5778 match reading.pid {
5779 Some(pid) if pid == own_pid => None,
5780 pid => Some(pid),
5781 }
5782}
5783
5784fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
5785 reading.worker_protocol != Some(1)
5786 && (foreign_loop(Some(reading), now, own_pid).is_some()
5787 || reading
5788 .pid
5789 .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
5790}
5791
5792pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
5803 run_claimed_until(opts, queue, task, &Stop::new()).await;
5804}
5805
5806async fn run_claimed_until(
5807 opts: &Opts,
5808 queue: &Queue,
5809 task: &mut Task,
5810 stop: &Stop,
5811) -> Vec<QuotaLoss> {
5812 let status = Arc::new(Mutex::new(Status::new()));
5813 let mut quota = Box::pin(attempt(
5816 opts,
5817 queue,
5818 &status,
5819 stop,
5820 crate::graph::Pause::new(),
5821 task,
5822 ))
5823 .await;
5824 let mut resumes = 0;
5833 while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
5834 let Some(timeout) = withheld_text_wait(task) else {
5835 break;
5836 };
5837 eprintln!(
5838 "waiting for the owner's answer on a withheld pull request text \
5839 (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
5840 );
5841 let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
5844 let ready = loop {
5845 match land_resume_state(task) {
5846 LandResume::StillWaiting
5847 if !stop.parking() && std::time::Instant::now() < limit =>
5848 {
5849 tokio::time::sleep(WITHHELD_POLL).await;
5850 }
5851 LandResume::Ready => break true,
5852 _ => break false,
5853 }
5854 };
5855 if !ready || stop.parking() {
5856 break;
5857 }
5858 resumes += 1;
5859 quota.extend(
5860 Box::pin(attempt(
5861 opts,
5862 queue,
5863 &status,
5864 stop,
5865 crate::graph::Pause::new(),
5866 task,
5867 ))
5868 .await,
5869 );
5870 }
5871 hold_if_runnable(queue, task);
5872 quota
5873}
5874
5875const MAX_WITHHELD_RESUMES: u32 = 3;
5878
5879const WITHHELD_POLL: Duration = Duration::from_secs(15);
5881
5882fn withheld_text_wait(task: &Task) -> Option<u64> {
5885 let id = task.execution_runs().last()?;
5886 let s = RunState::load(id).ok()?;
5887 (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
5888 .then_some(s.config.graph.answer_timeout)
5889}
5890
5891fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
5901 after
5902 .iter()
5903 .filter(|q| !before.contains(q))
5904 .cloned()
5905 .collect()
5906}
5907
5908fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
5911 let quota: Vec<_> = quota
5912 .iter()
5913 .filter(|q| q.cause == crate::agent::QuotaCause::UsageLimit)
5914 .collect();
5915 if quota.is_empty() {
5916 return None;
5917 }
5918 let with_hint = quota.iter().find(|q| q.reset.is_some());
5919 let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
5920 let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
5921 let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
5922 Some(
5923 now.checked_add(jiff::SignedDuration::from_secs(secs))
5924 .unwrap_or(Timestamp::MAX),
5925 )
5926}
5927
5928fn implementers_match(task: &Task, state: &RunState) -> bool {
5930 task.replacement.as_ref().map_or_else(
5931 || {
5932 task.implementers()
5933 .is_none_or(|n| n == state.config.graph.implementers)
5934 },
5935 |replacement| {
5936 state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
5937 && state.config.graph.implementers == 1
5938 },
5939 )
5940}
5941
5942fn starter_with_implementers(
5944 task: &Task,
5945 previous: Option<&RunState>,
5946 proposed: Starter,
5947) -> Starter {
5948 if previous.is_some_and(|s| !implementers_match(task, s)) {
5949 task.review_of
5950 .as_ref()
5951 .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
5952 } else {
5953 proposed
5954 }
5955}
5956
5957fn apply_task_implementers(config: &mut Config, task: &Task) {
5959 if let Some(n) = task.implementers() {
5960 config.graph.implementers = n;
5961 }
5962}
5963
5964#[cfg(test)]
5969fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
5970 let explicit = match &task.overrides {
5971 Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
5972 _ => opts.config.as_deref(),
5973 };
5974 let (mut config, _) = Config::discover(repo, explicit)?;
5975 apply_options(&mut config, opts, task)?;
5976 Ok(config)
5977}
5978
5979fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
5980 if task
5981 .overrides
5982 .as_ref()
5983 .is_none_or(|o| o.inherit_daemon_options)
5984 && let Some(mode) = opts.merge.as_deref()
5985 {
5986 config.merge.mode = merge_mode(mode)?;
5987 }
5988 if let Some(o) = &task.overrides {
5989 o.apply(config);
5990 }
5991 if let Some((mode, _)) = task.build_cache_override(config) {
5992 config.verify.build_cache = mode;
5993 }
5994 Ok(())
5995}
5996
5997fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
5999 let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
6000 if let Some(mode) = &opts.merge {
6001 config.merge.mode = merge_mode(mode)?;
6002 }
6003 Ok(config)
6004}
6005
6006async fn maybe_prune_cache_between_runs(
6011 repo: &Path,
6012 opts: &Opts,
6013 home: &Path,
6014 stop: &Stop,
6015 last_checked: &mut Option<Timestamp>,
6016 now: Timestamp,
6017) {
6018 if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
6019 return;
6020 }
6021 *last_checked = Some(now);
6022 let cfg = match prepare(repo, opts) {
6023 Ok(cfg) => cfg,
6024 Err(e) => {
6025 tracing::warn!("cache check: no config: {e:#}");
6026 return;
6027 }
6028 };
6029 match clean::prune_cache_if_over_limit(&cfg, home) {
6030 Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
6031 "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
6032 pruned.files,
6033 pruned.freed
6034 ),
6035 Ok(_) => {}
6036 Err(e) => {
6037 tracing::warn!("housekeep: prune cache: {e:#}");
6038 notices::raise_in(
6039 home,
6040 Notice::warn(
6041 "housekeep:cache",
6042 format!(
6043 "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
6044 e.to_string()
6045 .lines()
6046 .next()
6047 .unwrap_or("unknown cleanup error")
6048 ),
6049 ),
6050 );
6051 }
6052 }
6053}
6054
6055fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
6059 last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
6060}
6061
6062async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
6081 let cfg = match prepare(repo, opts) {
6082 Ok(cfg) => cfg,
6083 Err(e) => {
6084 tracing::warn!("housekeep: no config: {e:#}");
6085 return;
6086 }
6087 };
6088 let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
6097 let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
6098 if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
6103 let mut extra = Vec::new();
6104 if out.unreadable > 0 {
6105 extra.push(format!("{} unreadable", out.unreadable));
6106 }
6107 if out.orphaned_worktrees > 0 {
6108 extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
6109 }
6110 let detail = if extra.is_empty() {
6111 String::new()
6112 } else {
6113 format!(" ({})", extra.join(", "))
6114 };
6115 tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
6116 }
6117 if out.external_merges_recorded > 0 {
6118 tracing::info!(
6119 "housekeep: recorded {} run(s) as merged externally",
6120 out.external_merges_recorded
6121 );
6122 }
6123 if out.stale_pr_states_repaired > 0 {
6124 tracing::info!(
6125 "housekeep: rewrote {} run record(s) whose pull request had already settled",
6126 out.stale_pr_states_repaired
6127 );
6128 }
6129 if out.cache_files > 0 {
6130 tracing::info!(
6131 "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
6132 out.cache_files,
6133 out.cache_freed
6134 );
6135 }
6136 if out.questions_abandoned > 0 {
6137 tracing::info!(
6138 "housekeep: abandoned {} question(s) left open by a finished run",
6139 out.questions_abandoned
6140 );
6141 }
6142}
6143
6144async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
6153 let questions = Questions::at(home.join("questions"));
6154 let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
6155 if report.is_empty() {
6156 return;
6157 }
6158 if !report.quarantined.is_empty() {
6159 tracing::info!(
6160 "triage: held {} blocked task(s) whose blocked-on task or \
6161 question no longer exists: {}",
6162 report.quarantined.len(),
6163 report.quarantined.join(", ")
6164 );
6165 }
6166 if !report.resumed.is_empty() {
6167 tracing::info!(
6168 "triage: resumed {} held task(s) whose machine hold had resolved: {}",
6169 report.resumed.len(),
6170 report.resumed.join(", ")
6171 );
6172 }
6173 if !report.asked.is_empty() {
6174 tracing::info!(
6175 "triage: asked about {} held task(s): {}",
6176 report.asked.len(),
6177 report.asked.join(", ")
6178 );
6179 }
6180 if !report.answered.is_empty() {
6181 tracing::info!(
6182 "triage: applied {} operator answer(s): {}",
6183 report.answered.len(),
6184 report.answered.join(", ")
6185 );
6186 }
6187}
6188
6189pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
6196 disk_gate_at(repo, config, crate::run::home)
6197}
6198
6199pub(crate) fn disk_gate_at(
6200 repo: &Path,
6201 config: &Config,
6202 home: impl FnOnce() -> PathBuf,
6203) -> Option<String> {
6204 let measure = if crate::build_target::isolated(config) {
6205 crate::disk::managed_free_bytes
6206 } else {
6207 crate::disk::free_bytes
6208 };
6209 disk_gate_with(repo, config, home, measure)
6210}
6211
6212fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
6216 repo: &Path,
6217 config: &Config,
6218 home: impl FnOnce() -> PathBuf,
6219 free_bytes: F,
6220) -> Option<String> {
6221 let min = config.disk.min_free_bytes;
6222 if min == 0 {
6223 return None;
6224 }
6225 let output = match config.verify.build_cache {
6226 BuildCache::Shared => config.cache_dir(),
6227 BuildCache::Isolated => Some(home()),
6228 };
6229 let default_worktree_root;
6230 let worktree_root = match config.graph.worktree_root.as_deref() {
6231 Some(root) => root,
6232 None => {
6233 default_worktree_root = crate::run::default_worktree_root();
6234 &default_worktree_root
6235 }
6236 };
6237 for path in [Some(repo), output.as_deref(), Some(worktree_root)]
6238 .into_iter()
6239 .flatten()
6240 {
6241 let probe = if path == repo {
6242 path
6243 } else {
6244 path.ancestors().find(|p| p.exists()).unwrap_or(path)
6245 };
6246 let reason = match free_bytes(probe) {
6247 Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
6248 Err(e) => Some(crate::disk::unmeasured_in(
6249 probe,
6250 &e,
6251 &config.graph.language,
6252 )),
6253 };
6254 if reason.is_some() {
6255 return reason;
6256 }
6257 }
6258 None
6259}
6260
6261const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
6268
6269const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
6273
6274fn quota_wait(
6283 reset_at: Option<Timestamp>,
6284 now: Timestamp,
6285 fallback: Duration,
6286 cap: Duration,
6287) -> Duration {
6288 match reset_at {
6289 Some(at) if at > now => {
6290 let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
6291 Duration::from_secs(secs).min(cap)
6292 }
6293 _ => fallback,
6294 }
6295}
6296
6297fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
6311 parse_reset_hint_zoned(text, now)
6312 .or_else(|| parse_reset_hint_dated(text))
6313 .or_else(|| parse_reset_hint_relative(text, recorded))
6314}
6315
6316fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
6320 let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
6321 let mut rest = rest.trim();
6322 if rest.is_empty() {
6323 return None;
6324 }
6325 let mut total: i64 = 0;
6326 let mut matched = false;
6327 for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
6328 if let Some((digits, tail)) = rest.split_once(unit)
6329 && !digits.is_empty()
6330 && digits.bytes().all(|b| b.is_ascii_digit())
6331 {
6332 total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
6333 rest = tail;
6334 matched = true;
6335 }
6336 }
6337 if !rest.is_empty() || !matched {
6338 return None;
6339 }
6340 recorded
6341 .checked_add(jiff::SignedDuration::from_secs(total))
6342 .ok()
6343}
6344
6345fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
6349 let clock = clock.trim().to_lowercase();
6350 let (digits, pm) = clock
6351 .strip_suffix("am")
6352 .map(|d| (d, false))
6353 .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
6354 let (h, m) = digits.trim().split_once(':')?;
6355 let mut hour: i8 = h.trim().parse().ok()?;
6356 let minute: i8 = m.trim().parse().ok()?;
6357 if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
6358 return None;
6359 }
6360 if pm && hour != 12 {
6361 hour += 12;
6362 } else if !pm && hour == 12 {
6363 hour = 0;
6364 }
6365 Some((hour, minute))
6366}
6367
6368fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
6373 let open = text.find('(')?;
6374 let close = text.rfind(')')?;
6375 if close <= open {
6376 return None;
6377 }
6378 let zone = text[open + 1..close].trim();
6379 let (hour, minute) = parse_12h_clock(&text[..open])?;
6380 let tz = jiff::tz::TimeZone::get(zone).ok()?;
6381 let candidate = now
6382 .to_zoned(tz)
6383 .with()
6384 .hour(hour)
6385 .minute(minute)
6386 .second(0)
6387 .millisecond(0)
6388 .microsecond(0)
6389 .nanosecond(0)
6390 .build()
6391 .ok()?;
6392 let mut at = candidate.timestamp();
6393 if at <= now {
6394 at += jiff::SignedDuration::from_hours(24);
6395 }
6396 Some(at)
6397}
6398
6399fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
6408 let words: Vec<&str> = text.split_whitespace().collect();
6409 if words.len() < 5 {
6410 return None;
6411 }
6412 (0..=words.len() - 5)
6413 .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
6414}
6415
6416fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
6422 if trailing.is_some_and(|next| next.starts_with('(')) {
6423 return None;
6424 }
6425 let month = month_number(window[0])?;
6426 let day_token = window[1].strip_suffix(',')?.to_lowercase();
6427 let day_digits = ["st", "nd", "rd", "th"]
6428 .iter()
6429 .find_map(|suffix| day_token.strip_suffix(*suffix))?;
6430 let day: i8 = day_digits.parse().ok()?;
6431 let year_token = window[2];
6432 if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
6433 return None;
6434 }
6435 let year: i16 = year_token.parse().ok()?;
6436 let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
6440 let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
6441 let date = jiff::civil::Date::new(year, month, day).ok()?;
6442 let candidate = date
6443 .at(hour, minute, 0, 0)
6444 .to_zoned(jiff::tz::TimeZone::UTC)
6445 .ok()?;
6446 Some(candidate.timestamp())
6447}
6448
6449fn month_number(name: &str) -> Option<i8> {
6452 const NAMES: [&str; 12] = [
6453 "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
6454 ];
6455 let lower = name.to_lowercase();
6456 NAMES
6457 .iter()
6458 .position(|n| *n == lower.as_str())
6459 .map(|i| i as i8 + 1)
6460}
6461
6462#[cfg(test)]
6464fn exhausted_review_budget(state: &RunState) -> bool {
6465 !crate::handover::can_resume(state)
6468 && state.status == RunStatus::Blocked
6469 && !state.released()
6470 && state.retired_to.is_none()
6471}
6472
6473fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
6510 unfinished_run_with(runs, short, RunState::load)
6511}
6512
6513pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
6516where
6517 F: FnMut(&str) -> Result<RunState>,
6518{
6519 let mut id = runs.last()?.clone();
6520 let mut visited = std::collections::BTreeSet::new();
6521 let mut repo = None;
6522 loop {
6523 if !runs.contains(&id) || !visited.insert(id.clone()) {
6524 tracing::warn!("invalid or cyclic recovery authority for task {short}");
6525 return None;
6526 }
6527 let state = match load(&id) {
6528 Ok(state) if state.id == id => state,
6529 Ok(_) => return None,
6530 Err(e) => {
6531 tracing::warn!("could not read run {id} for task {short}: {e:#}");
6532 return None;
6533 }
6534 };
6535 if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
6536 return None;
6537 }
6538 repo = Some(state.repo.clone());
6539 if let Some(authority) = state.retired_to {
6540 id = authority;
6541 continue;
6542 }
6543 return (crate::handover::can_resume(&state)
6544 && state.liveness(false) != crate::run::Liveness::Live)
6545 .then_some(id);
6546 }
6547}
6548
6549fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
6557where
6558 F: FnOnce(&str) -> Result<RunState>,
6559{
6560 if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
6562 || task.fresh_start
6563 || task.review_branch.is_some()
6564 {
6565 return false;
6566 }
6567 let Some(id) = task.execution_runs().last() else {
6568 return false;
6569 };
6570 load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
6571}
6572
6573#[derive(Debug, Clone, PartialEq, Eq)]
6576enum Starter {
6577 Review(String),
6580 Resume(String),
6582 Start,
6584}
6585
6586fn retained_attempt_hold(
6591 task: &Task,
6592 starter: &Starter,
6593 limit: usize,
6594 mut load: impl FnMut(&str) -> Result<RunState>,
6595) -> Option<String> {
6596 if limit == 0 || matches!(starter, Starter::Resume(_)) {
6597 return None;
6598 }
6599 let mut retained = 0;
6600 for id in task
6601 .runs
6602 .iter()
6603 .chain(task.startup_failures.iter().map(|failure| &failure.run))
6604 .collect::<std::collections::BTreeSet<_>>()
6605 {
6606 let state = match load(id) {
6607 Ok(state) if state.id == *id => state,
6608 _ => {
6609 return Some(format!(
6610 "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
6611 ));
6612 }
6613 };
6614 if state.retired_to.is_some() || state.released() {
6615 continue;
6616 }
6617 retained += 1;
6620 }
6621 (retained >= limit).then(|| format!(
6622 "[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."
6623 ))
6624}
6625
6626fn selected_starter(
6628 selected: &crate::pr_recovery::Selection,
6629 previous: Option<&RunState>,
6630 unfinished: Option<&str>,
6631) -> Starter {
6632 if let Some(id) = unfinished
6633 && previous.is_some_and(|r| {
6634 r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
6635 })
6636 {
6637 Starter::Resume(id.to_owned())
6638 } else {
6639 Starter::Review(selected.branch.clone())
6640 }
6641}
6642
6643fn take_divergence_answer(
6647 branch: &str,
6648 remote: &str,
6649 task: &mut Task,
6650) -> Option<crate::reconcile::Choice> {
6651 let summary = crate::reconcile::summary_for(branch, remote);
6652 let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
6653 (a.question == summary)
6654 .then(|| crate::reconcile::Choice::from_answer(&a.answer))
6655 .flatten()
6656 .map(|c| (i, c))
6657 })?;
6658 task.answers.remove(idx);
6659 Some(choice)
6660}
6661
6662fn choose_starter(
6674 review_branch: Option<&str>,
6675 branch_exists: bool,
6676 unfinished: Option<&str>,
6677) -> Starter {
6678 match review_branch {
6679 Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
6680 Some(_) => Starter::Start,
6681 None => match unfinished {
6682 Some(id) => Starter::Resume(id.to_owned()),
6683 None => Starter::Start,
6684 },
6685 }
6686}
6687
6688fn review_retry_starter(
6692 task: &Task,
6693 previous: Option<&RunState>,
6694 branch: Option<&str>,
6695 exists: bool,
6696 unfinished: Option<&str>,
6697) -> Starter {
6698 if let Some(run) = previous
6699 && unfinished == Some(run.id.as_str())
6700 && run.reviewed_commits.is_some()
6701 && branch.is_some_and(|branch| {
6702 exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
6703 })
6704 && may_resume_run(run, task)
6705 {
6706 return Starter::Resume(run.id.clone());
6707 }
6708 match (branch, unfinished, &task.review_of) {
6709 (None, None, Some(branch)) => Starter::Review(branch.clone()),
6710 _ => choose_starter(branch, exists, unfinished),
6711 }
6712}
6713
6714fn review_branch_for<'a>(task: &'a Task, previous: Option<&RunState>) -> Option<&'a str> {
6716 task.review_branch
6717 .as_deref()
6718 .filter(|&branch| match &task.review_instruction {
6719 Some(authored) => *authored == task.instruction,
6720 None => previous.map_or_else(
6723 || task.review_of.as_deref() == Some(branch),
6724 |run| compatible_run_instruction(run, task),
6725 ),
6726 })
6727}
6728
6729fn may_resume_run(run: &RunState, task: &Task) -> bool {
6732 if !task.assignment_accepts(run) {
6733 return false;
6734 }
6735 task.resume_override
6736 .as_ref()
6737 .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
6738 || compatible_run_instruction(run, task)
6739}
6740
6741pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
6743 if let Some(authored) = &run.task_instruction {
6744 return compatible_instruction(authored, task);
6745 }
6746 if compatible_instruction(&run.instruction, task) {
6747 return true;
6748 }
6749 if run.reviewed_commits.is_some() {
6752 if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
6753 return strip_answers_block(authored, task).trim() == task.instruction.trim();
6754 }
6755 if let Some(branch) = &task.review_of {
6756 let canonical = format!(
6757 "Review the branch `{branch}` (review-only: no implementation, no judging)."
6758 );
6759 let generated = format!(
6760 "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"
6761 );
6762 return task.instruction == canonical && run.instruction.starts_with(&generated);
6763 }
6764 }
6765 false
6766}
6767
6768pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
6770 strip_answers_block(old, task) == task.instruction
6771}
6772
6773fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
6776 if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
6777 return fallback.to_path_buf();
6778 }
6779 task.repo.clone()
6780}
6781
6782const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
6786
6787fn answers_block(task: &Task, count: usize) -> String {
6789 let mut s = ANSWERS_HEADER.to_owned();
6790 for a in &task.answers[..count] {
6791 s.push_str(&format!("- {}: {}\n", a.question, a.answer));
6792 }
6793 s
6794}
6795
6796fn resumption_block(r: &crate::queue::Resumption) -> String {
6799 format!(
6800 "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
6801 Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
6802 r.generation, r.at, r.instruction, r.answers_through,
6803 )
6804}
6805
6806fn append_answers(base: &str, task: &Task) -> String {
6808 let mut s = base.to_owned();
6809 if !task.answers.is_empty() {
6810 s.push_str(&answers_block(task, task.answers.len()));
6811 }
6812 if let Some(r) = &task.resumption {
6813 s.push_str(&resumption_block(r));
6814 }
6815 s
6816}
6817
6818fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
6822 let mut instruction = instruction;
6823 for approval in task
6824 .resumption
6825 .iter()
6826 .chain(task.resumption_history.iter().rev())
6827 {
6828 if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
6829 instruction = base;
6830 break;
6831 }
6832 }
6833 for count in (1..=task.answers.len()).rev() {
6834 let block = answers_block(task, count);
6835 if let Some(base) = instruction.strip_suffix(&block) {
6836 return base;
6837 }
6838 }
6839 instruction
6840}
6841
6842fn instruction_for(task: &Task) -> String {
6850 append_answers(&task.instruction, task)
6851}
6852
6853fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
6865 append_answers(strip_answers_block(old_instruction, task), task)
6866}
6867
6868fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
6870 let failure = error.downcast_ref::<crate::config::ConfigFailure>();
6871 task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
6872 if let Some(cause) = task.hold_notice_cause.as_mut() {
6873 cause.target = failure.map(|f| f.target.clone());
6874 }
6875}
6876
6877#[derive(Debug, thiserror::Error)]
6878#[error("attachment `{name}` is recorded on the task but {path} is missing")]
6879struct MissingAttachment {
6880 name: String,
6881 path: PathBuf,
6882}
6883
6884fn task_attachments(
6886 queue: &Queue,
6887 task: &Task,
6888) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
6889 let paths = queue.attachment_paths(task);
6890 for (name, path) in task.attachments.iter().zip(&paths) {
6891 if !path.is_file() {
6892 return Err(MissingAttachment {
6893 name: name.clone(),
6894 path: path.clone(),
6895 });
6896 }
6897 }
6898 Ok(paths)
6899}
6900
6901fn prepare_instruction(
6912 starter: &Starter,
6913 old_instruction: Option<&str>,
6914 task: &Task,
6915) -> Option<String> {
6916 match starter {
6917 Starter::Start => Some(instruction_for(task)),
6918 Starter::Resume(_) => Some(resumed_instruction(
6919 old_instruction.expect("a resumed run always has a prior instruction"),
6920 task,
6921 )),
6922 Starter::Review(_) => None,
6923 }
6924}
6925
6926fn record(queue: &Queue, task: &mut Task) {
6930 if let Err(e) = queue.put(task) {
6931 tracing::error!("could not record task {}: {e:#}", task.short());
6932 let notice = Notice::error(
6933 "loop:record",
6934 format!(
6935 "Task {} state could not be saved: {}. Check the disk.",
6936 task.id,
6937 e.to_string().lines().next().unwrap_or("unknown save error")
6938 ),
6939 )
6940 .link(Link::Task {
6941 id: task.id.clone(),
6942 });
6943 match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
6945 Some(home) => notices::raise_in(home, notice),
6946 None => notices::raise(notice),
6947 }
6948 }
6949}
6950
6951fn runnable(queue: &Queue) -> Vec<Task> {
6957 let mut tasks: Vec<Task> = queue
6958 .list()
6959 .into_iter()
6960 .filter(|t| t.status.runnable())
6961 .collect();
6962 tasks.sort_unstable_by(crate::queue::dispatch_order);
6963 tasks
6964}
6965
6966fn describe(state: &RunState) -> String {
6980 let p = phrases(&state.config.graph.language);
6981 let mut detail = if state.status == RunStatus::Stalled {
6982 let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
6983 seats.sort_unstable();
6984 seats.dedup();
6985 if seats.is_empty() {
6986 p.quorum_lost.to_owned()
6987 } else {
6988 format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
6989 }
6990 } else {
6991 format!("{}{}", p.run_ended, state.status.display_label())
6992 };
6993 if let Some(cause) = state.verification_blocking_cause() {
6994 detail.push_str(&format!(" ({cause})"));
6995 } else if let Some(last) = state.events.last() {
6996 let unanswered = state
7000 .reviews
7001 .last()
7002 .filter(|r| {
7003 state.status == RunStatus::Blocked
7004 && last.node == "review"
7005 && r.incomplete()
7006 && r.blocking == 0
7007 && r.round == state.config.graph.review_rounds
7008 && r.e2e.iter().all(crate::run::CommandOutcome::ok)
7009 })
7010 .map(|r| (r.expected - r.answered, r.round));
7011 match unanswered {
7012 Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
7013 detail.push_str(&format!(
7014 " ({}: {})",
7015 last.node,
7016 (p.reviewers_never_answered)(missing, rounds)
7017 ));
7018 }
7019 _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
7020 }
7021 }
7022 detail.push_str(&format!(" [run {}]", state.id));
7023 detail
7024}
7025
7026const DIAGNOSTIC_MAX: usize = 4_000;
7032
7033const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
7038
7039pub(crate) fn diagnostic_for(state: &RunState) -> Option<String> {
7053 diagnostic(state)
7054}
7055
7056fn diagnostic(state: &RunState) -> Option<String> {
7057 let mut parts: Vec<String> = Vec::new();
7058
7059 if let Some(e2e) = &state.head_e2e
7060 && !e2e.passed
7061 {
7062 for o in e2e
7063 .outcomes
7064 .iter()
7065 .filter(|o| !o.ok() && !o.resource_blocked)
7066 {
7067 parts.push(format!(
7068 "head_e2e `{}` failed on {} ({}):\n{}",
7069 o.command,
7070 e2e.head.chars().take(7).collect::<String>(),
7071 notices::exit_status(o.code),
7072 crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
7073 ));
7074 }
7075 }
7076
7077 for o in state.gate.iter().filter(|o| !o.ok()) {
7079 parts.push(format!(
7080 "gate `{}` failed ({}):\n{}",
7081 o.command,
7082 notices::exit_status(o.code),
7083 crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
7084 ));
7085 }
7086
7087 if let Some(last) = state
7090 .events
7091 .iter()
7092 .rev()
7093 .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
7094 {
7095 parts.push(last.message.clone());
7096 }
7097
7098 if state.viable().is_empty() {
7105 for c in &state.candidates {
7106 if c.has_valid_verified_noop()
7107 && let Some(evidence) = c.verified_noop_display()
7108 {
7109 parts.push(format!(
7110 "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
7111 c.label
7112 ));
7113 } else if !c.summary.trim().is_empty() {
7114 if let Some(why) = &c.failed {
7115 parts.push(format!(
7116 "candidate {} ({why}): {}",
7117 c.label,
7118 c.summary.trim()
7119 ));
7120 } else {
7121 parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
7122 }
7123 } else if let Some(why) = &c.failed {
7124 parts.push(format!("candidate {}: {why}", c.label));
7125 }
7126 }
7127 }
7128
7129 if parts.is_empty() {
7130 return None;
7131 }
7132 Some(crate::run::tail(
7137 &parts.join("\n\n"),
7138 DIAGNOSTIC_MAX.saturating_sub(100),
7139 ))
7140}
7141
7142fn label(status: RunStatus) -> &'static str {
7150 status.as_str()
7151}
7152
7153pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
7155 match mode {
7156 "none" => Ok(MergeMode::None),
7157 "local" => Ok(MergeMode::Local),
7158 "pr" => Ok(MergeMode::Pr),
7159 other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
7160 }
7161}
7162
7163fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
7168 mutex
7169 .lock()
7170 .unwrap_or_else(std::sync::PoisonError::into_inner)
7171}
7172
7173#[cfg(test)]
7174mod tests {
7175 use super::*;
7176 use crate::queue::{Source, TaskStatus};
7177 use crate::run::{Candidate, CommandOutcome};
7178 use pretty_assertions::assert_eq;
7179
7180 fn task() -> Task {
7181 Task::new(
7182 "add retries".to_owned(),
7183 "add retries".to_owned(),
7184 PathBuf::from("/repo"),
7185 Source::Human,
7186 )
7187 }
7188
7189 #[test]
7190 fn dispatch_wait_aggregates_unique_skips_in_stable_count_order() {
7191 let skips = DispatchSkips::from([
7192 ("a".into(), SkipReason::CoolingDown),
7193 ("b".into(), SkipReason::WaitingOnLanding),
7194 ("c".into(), SkipReason::WaitingOnLanding),
7195 ("d".into(), SkipReason::OrdinaryCapacity),
7196 ]);
7197 let wait = aggregate_dispatch_wait(4, &skips).unwrap();
7198 assert_eq!(wait.runnable, 4);
7199 assert_eq!(
7200 wait.reasons
7201 .iter()
7202 .map(|r| (r.reason.as_str(), r.count))
7203 .collect::<Vec<_>>(),
7204 [
7205 ("waiting_on_landing", 2),
7206 ("cooling_down", 1),
7207 ("ordinary_capacity", 1)
7208 ]
7209 );
7210 assert_eq!(aggregate_dispatch_wait(0, &DispatchSkips::new()), None);
7211 assert!(
7212 aggregate_dispatch_wait(2, &DispatchSkips::new())
7213 .unwrap()
7214 .reasons
7215 .is_empty()
7216 );
7217 }
7218
7219 #[test]
7220 fn dispatch_wait_tracks_interrupt_withholding_and_set_changes() {
7221 let before = vec!["a".into(), "b".into(), "c".into()];
7222 let allowed = vec![task_with_id("b")];
7223 let skips = interrupt_skips(&before, &allowed);
7224 assert_eq!(
7225 skips,
7226 DispatchSkips::from([
7227 ("a".into(), SkipReason::InterruptGate),
7228 ("c".into(), SkipReason::InterruptGate),
7229 ])
7230 );
7231 let mut previous = DispatchSkips::new();
7232 assert!(!changed_dispatch_skips(&mut previous, DispatchSkips::new()));
7233 assert!(changed_dispatch_skips(&mut previous, skips.clone()));
7234 assert!(!changed_dispatch_skips(&mut previous, skips));
7235 assert!(changed_dispatch_skips(
7236 &mut previous,
7237 DispatchSkips::from([("a".into(), SkipReason::CoolingDown),])
7238 ));
7239 assert!(changed_dispatch_skips(&mut previous, DispatchSkips::new()));
7240 }
7241
7242 #[test]
7243 fn dispatch_wait_status_reads_legacy_and_future_reason_keys() {
7244 let mut value = serde_json::to_value(Status::new()).unwrap();
7245 value.as_object_mut().unwrap().remove("dispatch_wait");
7246 assert!(
7247 serde_json::from_value::<Status>(value.clone())
7248 .unwrap()
7249 .dispatch_wait
7250 .is_none()
7251 );
7252 assert!(
7253 serde_json::from_value::<Reading>(value.clone())
7254 .unwrap()
7255 .dispatch_wait
7256 .is_none()
7257 );
7258 value["dispatch_wait"] = serde_json::json!({
7259 "runnable": 3, "reasons": [{"reason": "future_reason", "count": 3}]
7260 });
7261 let reading = serde_json::from_value::<Reading>(value).unwrap();
7262 assert_eq!(
7263 reading.dispatch_wait.unwrap().reasons[0].reason,
7264 "future_reason"
7265 );
7266 }
7267
7268 fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
7269 let job = crate::worker::Job {
7270 id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
7271 sequence: 1,
7272 kind: "task".into(),
7273 key: format!("task:{}", request.task),
7274 payload: serde_json::to_value(request).unwrap(),
7275 generation: "a".repeat(64),
7276 version: None,
7277 status: crate::worker::Status::Starting,
7278 result: None,
7279 pid: None,
7280 created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
7281 finished_at: None,
7282 };
7283 let dir = home.join("workers/jobs").join(&job.id);
7284 std::fs::create_dir_all(&dir).unwrap();
7285 std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
7286 job
7287 }
7288
7289 #[test]
7290 fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
7291 let home = tempfile::tempdir().unwrap();
7292 let request = TaskWorker {
7293 opts: Opts::default(),
7294 queue: home.path().join("queue"),
7295 task: "startup".into(),
7296 lane: PermitKind::Ordinary,
7297 standalone: false,
7298 };
7299 let job = starting_task_reservation(home.path(), &request);
7300 let error = task_worker_spawn_error(
7301 home.path(),
7302 &request,
7303 anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
7304 )
7305 .expect_err("our own reservation must not turn a failed spawn into a resync");
7306 let active = crate::worker::active(home.path()).unwrap();
7307 assert_eq!(active.len(), 1);
7308 assert_eq!(active[0].id, job.id);
7309 assert_eq!(active[0].status, crate::worker::Status::Starting);
7310 assert!(
7311 crate::worker::control(home.path(), &job.key)
7312 .unwrap()
7313 .is_none()
7314 );
7315 let notices = notices::Notices::at(home.path().join("notifications")).list();
7316 assert_eq!(notices.len(), 1);
7317 assert_eq!(notices[0].key, "loop:worker-startup");
7318 assert!(!notices[0].message.contains("private-error-detail"));
7319 assert!(notices[0].message.contains(&request.task));
7320 assert!(
7321 notices[0]
7322 .message
7323 .contains("could not be started or acknowledged")
7324 );
7325 assert!(notices[0].message.contains("worker.log"));
7326 assert_eq!(
7327 notices[0].link,
7328 Some(Link::Task {
7329 id: request.task.clone()
7330 })
7331 );
7332 assert!(format!("{error:#}").contains("private-error-detail"));
7333 }
7334
7335 #[test]
7336 fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
7337 let home = tempfile::tempdir().unwrap();
7338 let mut request = TaskWorker {
7339 opts: Opts::default(),
7340 queue: home.path().join("queue"),
7341 task: "handoff".into(),
7342 lane: PermitKind::Ordinary,
7343 standalone: true,
7344 };
7345 let job = starting_task_reservation(home.path(), &request);
7346 request.standalone = false;
7347 task_worker_spawn_error(
7348 home.path(),
7349 &request,
7350 anyhow::anyhow!("operation key is already reserved for a different request"),
7351 )
7352 .expect("a different standalone request is the handoff race, not our startup failure");
7353 let active = crate::worker::active(home.path()).unwrap();
7354 assert_eq!(active.len(), 1);
7355 assert_eq!(active[0].id, job.id);
7356 assert_eq!(active[0].payload, job.payload);
7357 assert!(
7358 notices::Notices::at(home.path().join("notifications"))
7359 .list()
7360 .is_empty()
7361 );
7362 }
7363
7364 #[test]
7365 fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
7366 let home = tempfile::tempdir().unwrap();
7367 let queue = Queue::at(home.path().join("queue"));
7368 let mut task = task();
7369 task.runs = vec!["previous".into()];
7370 queue.put(&mut task).unwrap();
7371 let request = TaskWorker {
7372 opts: Opts::default(),
7373 queue: home.path().join("queue"),
7374 task: task.id.clone(),
7375 lane: PermitKind::Ordinary,
7376 standalone: false,
7377 };
7378 let job = starting_task_reservation(home.path(), &request);
7379 let claims = current_work(home.path(), Timestamp::now());
7380 assert_eq!(claims.len(), 1);
7381 assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
7382 assert_eq!(claims[0].run, "previous");
7383 assert!(other_claims_run(&claims, "previous", None));
7384 assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
7387 assert!(is_working_on(home.path(), "previous", Timestamp::now()));
7388 }
7389
7390 #[test]
7391 fn admission_excludes_only_the_callers_exact_reservation() {
7392 let own = Current {
7393 worker: Some("own".into()),
7394 task: "same-task".into(),
7395 run: "previous".into(),
7396 };
7397 assert!(!other_claims_run(
7398 std::slice::from_ref(&own),
7399 "previous",
7400 Some("own")
7401 ));
7402 assert!(other_claims_run(
7403 std::slice::from_ref(&own),
7404 "previous",
7405 None
7406 ));
7407 for worker in [None, Some("other".into())] {
7408 let other = Current {
7409 worker,
7410 ..own.clone()
7411 };
7412 assert!(other_claims_run(
7413 &[own.clone(), other],
7414 "previous",
7415 Some("own")
7416 ));
7417 }
7418 let legacy: Current =
7419 serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
7420 assert!(other_claims_run(&[legacy], "previous", Some("own")));
7421 }
7422
7423 #[test]
7424 fn os_leased_task_worker_survives_wall_clock_advance() {
7425 let home = tempfile::tempdir().unwrap();
7426 let queue = Queue::at(home.path().join("queue"));
7427 let mut task = task();
7428 let run = "20260903-100000-abcd";
7429 task.start(run.into());
7430 queue.put(&mut task).unwrap();
7431 let mut worker = live_task_fixture(home.path(), &task.id).unwrap();
7432 let future = Timestamp::now() + jiff::SignedDuration::from_secs(3600);
7433 assert!(
7434 current_work(home.path(), future)
7435 .iter()
7436 .any(
7437 |claim| claim.worker.as_deref() == Some(worker.job.id.as_str())
7438 && claim.run == run
7439 )
7440 );
7441 worker.release_lease();
7442 assert!(worker.dir.join("job.json").is_file());
7443 assert!(!is_working_on(home.path(), run, future));
7444 let dir = worker.dir.clone();
7445 drop(worker);
7446 assert!(!dir.exists());
7447 }
7448
7449 #[test]
7450 fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
7451 let mut task = task();
7452 let mut run = run_state(RunStatus::Reviewing);
7453 run.task_instruction = Some(task.instruction.clone());
7454 run.reviewed_commits = Some(vec!["committed-fix".into()]);
7455 let branch = "magi/test/B";
7456 run.candidates.push(crate::run::Candidate {
7457 branch: branch.into(),
7458 ..candidate('B', "preserved work", false, None)
7459 });
7460 task.runs = vec![run.id.clone()];
7461 let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
7462 assert_eq!(
7463 review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
7464 Starter::Resume(run.id.clone())
7465 );
7466 assert!(matches!(
7467 review_retry_starter(
7468 &task,
7469 Some(&run),
7470 Some("different"),
7471 true,
7472 unfinished.as_deref()
7473 ),
7474 Starter::Review(_)
7475 ));
7476 assert_eq!(
7477 review_retry_starter(
7478 &task,
7479 Some(&run),
7480 Some(branch),
7481 false,
7482 unfinished.as_deref()
7483 ),
7484 Starter::Start
7485 );
7486 task.instruction.push_str(" changed criteria");
7487 assert!(matches!(
7488 review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
7489 Starter::Review(_)
7490 ));
7491 assert!(matches!(
7492 review_retry_starter(&task, Some(&run), Some(branch), true, None),
7493 Starter::Review(_)
7494 ));
7495 }
7496
7497 #[test]
7498 fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
7499 let dir = tempfile::tempdir().unwrap();
7500 let queue = Queue::at(dir.path().join("queue"));
7501 let mut task = task();
7502 task.status = TaskStatus::Running;
7503 task.attempts = 1;
7504 queue.put(&mut task).unwrap();
7505 let live = std::collections::BTreeSet::from([task.id.clone()]);
7506 assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
7507 drop(queue.claim(&task.id).unwrap());
7508 let saved = queue.get(&task.id).unwrap();
7509 assert_eq!(saved.status, TaskStatus::Running);
7510 assert_eq!(saved.attempts, 1);
7511 assert!(saved.last_error.is_none());
7512 }
7513
7514 #[test]
7515 fn standalone_workers_do_not_consume_scheduler_lanes() {
7516 let request = |task: &str, lane, standalone| TaskWorker {
7517 opts: Opts::default(),
7518 queue: PathBuf::from("/queue"),
7519 task: task.to_owned(),
7520 lane,
7521 standalone,
7522 };
7523 let mut jobs = vec![
7524 request("ordinary", PermitKind::Ordinary, false),
7525 request("standalone-urgent", PermitKind::Urgent, true),
7526 request("standalone-ordinary", PermitKind::Ordinary, true),
7527 request("decision", PermitKind::None, false),
7528 ];
7529 assert_eq!(available_slots(&jobs, 2), (1, 1));
7530 jobs.push(request("urgent", PermitKind::Urgent, false));
7531 assert_eq!(available_slots(&jobs, 2), (1, 0));
7532 assert_eq!(available_slots(&jobs, 0), (0, 0));
7533 }
7534
7535 #[test]
7536 fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
7537 let now = Timestamp::now();
7538 let mut reading = Reading {
7539 pid: Some(std::process::id()),
7540 updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
7541 ..Reading::default()
7542 };
7543 assert!(!reading.running(now));
7544 assert!(legacy_scheduler_running(&reading, now, 0));
7545 reading.worker_protocol = Some(1);
7546 assert!(!legacy_scheduler_running(&reading, now, 0));
7547 }
7548
7549 #[test]
7550 fn selected_public_head_overrides_historical_resume_and_pin() {
7551 let mut t = task();
7552 let mut old = run_state(RunStatus::Blocked);
7553 let selection = crate::pr_recovery::Selection {
7554 url: "url".into(),
7555 branch: format!("magi/task-{}", t.id),
7556 head: "a".repeat(40),
7557 source_head: None,
7558 source_run: None,
7559 source_proof: None,
7560 disposition: Some(crate::pr_recovery::Disposition::Review),
7561 instruction: t.instruction.clone(),
7562 approved_at: Timestamp::now(),
7563 };
7564 t.resume_override = Some(crate::queue::OperatorResume {
7565 pinned_run: Some(old.id.clone()),
7566 question_id: "choice".into(),
7567 at: Timestamp::now(),
7568 conductor_rehold: None,
7569 forced: false,
7570 });
7571 assert_eq!(
7572 selected_starter(&selection, Some(&old), Some(&old.id)),
7573 Starter::Review(selection.branch.clone())
7574 );
7575 old.pr_recovery = Some(selection.clone());
7576 assert_eq!(
7577 selected_starter(&selection, Some(&old), Some(&old.id)),
7578 Starter::Review(selection.branch.clone())
7579 );
7580 old.reviewed_commits = Some(vec!["implementation".into()]);
7581 assert_eq!(
7582 selected_starter(&selection, Some(&old), Some(&old.id)),
7583 Starter::Resume(old.id.clone())
7584 );
7585 let mut changed = selection.clone();
7586 changed.head = "b".repeat(40);
7587 assert_eq!(
7588 selected_starter(&changed, Some(&old), Some(&old.id)),
7589 Starter::Review(changed.branch)
7590 );
7591 }
7592
7593 #[test]
7594 fn candidate_transplant_failure_is_one_actionable_hold() {
7595 let dir = tempfile::tempdir().unwrap();
7596 let q = Queue::at(dir.path().join("queue"));
7597 let mut t = task();
7598 let mut state = run_state(RunStatus::Blocked);
7599 state.event("prep", "cannot apply referenced commit: conflict");
7600 state.prep_failure = Some("conflict".into());
7601 t.start(state.id.clone());
7602 finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
7603 assert_eq!(t.attempts, 1);
7604 assert_eq!(t.status, TaskStatus::Held);
7605 assert!(t.operator_held());
7606 assert!(!t.status.runnable());
7607 assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
7608 let first = t.chat_notice_key().unwrap();
7609 t.chat_notices.push(first.clone());
7610 t.release_operator("test", None);
7611 state.id = "another-unprepared-run".into();
7612 t.start(state.id.clone());
7613 finish_attempt(
7614 3,
7615 &q,
7616 &mut t,
7617 &state,
7618 &[],
7619 Err(anyhow::anyhow!("still conflicts")),
7620 );
7621 assert_eq!(
7622 t.chat_notice_key().as_ref(),
7623 Some(&first),
7624 "no work happened"
7625 );
7626 t.release_operator("test", None);
7627 state.prep_failure = None;
7628 state.status = RunStatus::Failed;
7629 state.begin_pass();
7630 t.start(state.id.clone());
7631 finish_attempt(
7632 1,
7633 &q,
7634 &mut t,
7635 &state,
7636 &[],
7637 Err(anyhow::anyhow!("new gate failure")),
7638 );
7639 let failure = t.chat_notice_key().unwrap();
7640 assert_ne!(failure, first, "approved recovery reached a real failure");
7641 t.release_operator("test", None);
7642 state.begin_pass();
7643 t.start(state.id.clone());
7644 finish_attempt(
7645 1,
7646 &q,
7647 &mut t,
7648 &state,
7649 &[],
7650 Err(anyhow::anyhow!("new failure on resume")),
7651 );
7652 assert_ne!(
7653 t.chat_notice_key().as_ref(),
7654 Some(&failure),
7655 "a new settled pass"
7656 );
7657 }
7658
7659 #[test]
7660 fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
7661 for source in ["cli", "web"] {
7662 let mut t = task();
7663 let mut run = run_state(RunStatus::Blocked);
7664 run.instruction = "Run A original criteria".into();
7665 run.task_instruction = Some(run.instruction.clone());
7666 t.start(run.id.clone());
7667 t.release_operator("choice", Some("resume-question"));
7668 t.resume_override = Some(crate::queue::OperatorResume {
7669 question_id: "resume-question".into(),
7670 at: Timestamp::now(),
7671 conductor_rehold: None,
7672 forced: true,
7673 pinned_run: Some(run.id.clone()),
7674 });
7675 t.hold_machine(Some("not enough free space to start a run".into()));
7676 let mut unchanged = t.clone();
7677 unchanged
7678 .edit("title changed".into(), unchanged.instruction.clone())
7679 .unwrap();
7680 unchanged.release_operator(source, None);
7681 assert_eq!(
7682 unchanged
7683 .resume_override
7684 .as_ref()
7685 .unwrap()
7686 .pinned_run
7687 .as_deref(),
7688 Some(run.id.as_str())
7689 );
7690 assert!(!compatible_run_instruction(&run, &unchanged));
7691 assert!(may_resume_run(&run, &unchanged));
7692
7693 t.edit(
7694 "approved recovery".into(),
7695 "Reuse measured PR head B; fix Clippy; review".into(),
7696 )
7697 .unwrap();
7698 assert!(t.resume_override.is_none());
7699 t.release_operator(source, None);
7700 let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
7701 assert!(reloaded.resume_override.is_none());
7702 assert!(!may_resume_run(&run, &reloaded));
7703 let unfinished =
7704 unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
7705 .filter(|_| may_resume_run(&run, &reloaded));
7706 assert_eq!(
7707 choose_starter(None, false, unfinished.as_deref()),
7708 Starter::Start
7709 );
7710 assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
7711 assert_eq!(
7712 reloaded.resumption_history[0].question_id.as_deref(),
7713 Some("resume-question")
7714 );
7715
7716 unchanged.instruction = "Reuse measured PR head B".into();
7719 unchanged.hold_machine(Some("disk hold".into()));
7720 unchanged.release_operator(source, None);
7721 assert!(unchanged.resume_override.is_none());
7722 assert!(!may_resume_run(&run, &unchanged));
7723 }
7724 }
7725
7726 #[test]
7727 fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
7728 let mut t = task();
7729 let mut run = run_state(RunStatus::Blocked);
7730 t.review_of = Some("approved-head".into());
7731 t.instruction =
7732 "Review the branch `approved-head` (review-only: no implementation, no judging)."
7733 .into();
7734 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();
7735 run.reviewed_commits = Some(vec!["Commit log".into()]);
7736 t.start(run.id.clone());
7737 t.hold_machine(Some("interrupted review".into()));
7738 t.release_operator("cli", None);
7739 assert!(
7740 compatible_run_instruction(&run, &t),
7741 "legacy explicit review remains resumable"
7742 );
7743 let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
7744 .filter(|_| compatible_run_instruction(&run, &t));
7745 assert_eq!(
7746 choose_starter(None, false, unfinished.as_deref()),
7747 Starter::Resume(run.id.clone())
7748 );
7749 run.task_instruction = Some(t.instruction.clone());
7750 assert!(compatible_run_instruction(&run, &t));
7751 let reloaded: RunState =
7752 serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
7753 assert!(compatible_run_instruction(&reloaded, &t));
7754 t.edit(
7755 "new approved head".into(),
7756 "Reuse measured PR head B".into(),
7757 )
7758 .unwrap();
7759 assert!(!compatible_run_instruction(&run, &t));
7760
7761 t.review_of = None;
7763 t.instruction = "Fix Clippy on approved head".into();
7764 run.task_instruction = None;
7765 run.instruction = format!(
7766 "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
7767 t.instruction
7768 );
7769 assert!(compatible_run_instruction(&run, &t));
7770 t.instruction.push('\n');
7771 assert!(
7772 compatible_run_instruction(&run, &t),
7773 "legacy generated review trimmed the original criteria"
7774 );
7775 t.hold_for_handover(Some("approved-head".into()), "refused".into());
7776 assert_eq!(review_branch_for(&t, Some(&run)), Some("approved-head"));
7777 t.edit("new plan".into(), "Reuse measured PR head B".into())
7778 .unwrap();
7779 assert!(review_branch_for(&t, Some(&run)).is_none());
7780 assert!(!compatible_run_instruction(&run, &t));
7781 t.review_branch = Some("approved-head".into());
7782 t.review_instruction = None;
7783 assert!(
7784 review_branch_for(&t, Some(&run)).is_none(),
7785 "legacy retained candidate cannot replace a revised approved head"
7786 );
7787 }
7788
7789 #[test]
7790 fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
7791 let home = crate::run::test_home();
7792 crate::run::pin_test_home();
7793 let dir = tempfile::tempdir().unwrap();
7794 let queue = Queue::at(dir.path().join("queue"));
7795 for resume in [true, false] {
7796 let state = run_state(RunStatus::Blocked);
7797 let mut t = task();
7798 t.start(state.id.clone());
7799 let action = if resume {
7800 ask::ChoiceAction::Resume {
7801 run: state.id.clone(),
7802 }
7803 } else {
7804 ask::ChoiceAction::Requeue
7805 };
7806 let mut q = action_question(&state.id, action);
7807 q.status = ask::QuestionStatus::Open;
7808 q.answer = None;
7809 q.answered_at = None;
7810 t.fail("run stopped with a question", 3);
7811 hold_if_runnable(&queue, &mut t);
7812 assert!(t.operator_decided_at.is_none());
7813 assert!(t.operator_held());
7814 q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
7815 let expected = if resume {
7816 ActionDecision::Resume(state.id.clone())
7817 } else {
7818 ActionDecision::Requeue
7819 };
7820 assert_eq!(
7821 decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
7822 expected
7823 );
7824 t.hold_manual(Some("later explicit hold".into()));
7825 assert_eq!(
7826 decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
7827 ActionDecision::Stale
7828 );
7829 }
7830 }
7831
7832 #[test]
7833 fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
7834 let mut t = task();
7835 t.answers.push(crate::queue::AnsweredQuestion {
7836 question: "Inspect the remote?".into(),
7837 answer: "Inspect then wait".into(),
7838 });
7839 let old = instruction_for(&t);
7840 assert!(compatible_instruction(&old, &t));
7841 t.instruction = "Reuse approved PR head and review".into();
7842 t.release_operator("cli", None);
7843 assert!(!compatible_instruction(&old, &t));
7844 let approved = instruction_for(&t);
7845 assert!(approved.contains("waiting premises are superseded"));
7846 assert!(compatible_instruction(&approved, &t));
7847 assert_eq!(resumed_instruction(&approved, &t), approved);
7848 t.release_operator("web", None);
7849 assert!(compatible_instruction(&approved, &t));
7850 assert_eq!(t.resumption_history.len(), 1);
7851 t.start("run".into());
7852 assert!(instruction_for(&t).contains("Explicit operator resumption"));
7853 }
7854
7855 #[test]
7859 fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
7860 let mut state = RunState::new(
7861 PathBuf::from("/repo"),
7862 "main".into(),
7863 "base".into(),
7864 "task".into(),
7865 Config::default(),
7866 );
7867 state.status = RunStatus::Landing;
7868 state.parked = true;
7869 state.pr_pushed_head = Some("head".into());
7870 state.land_unrelated = Some(
7871 serde_json::from_value(serde_json::json!({
7872 "head": "head", "question": "ci-question",
7873 "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
7874 }))
7875 .unwrap(),
7876 );
7877 let mut t = task();
7878 t.start(state.id.clone());
7879 let verdict = Verdict {
7880 status: RunStatus::Landing,
7881 left_pr: true,
7882 quota_hit: false,
7883 parked: true,
7884 no_viable_candidates: false,
7885 };
7886 settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
7887 assert_eq!(t.attempts, 0);
7888 assert_eq!(t.status, TaskStatus::Held);
7889 assert!(!t.operator_held());
7890 assert!(
7891 t.hold_reason
7892 .as_deref()
7893 .unwrap()
7894 .starts_with("[ci-unrelated]")
7895 );
7896 t.attempts = 1;
7898 settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
7899 assert_eq!(t.attempts, 1);
7900 assert_eq!(t.passes.len(), 1);
7901 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
7902 state.pr_pushed_head = Some("new-head".into());
7903 state.parked = false;
7904 state.status = RunStatus::Blocked;
7905 let stale = Verdict {
7906 status: RunStatus::Blocked,
7907 parked: false,
7908 ..verdict
7909 };
7910 settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
7911 assert_eq!(t.attempts, 1);
7912 state.begin_pass();
7914 state.begin_pass();
7915 state.status = RunStatus::Landing;
7916 state.parked = true;
7917 state.pr_pushed_head = Some("head".into());
7918 settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
7919 assert_eq!(t.attempts, 0);
7920 assert_eq!(t.passes.len(), 2);
7921 }
7922
7923 #[test]
7924 fn orphan_recovery_does_not_refund_a_previous_pass_loss() {
7925 let mut state = run_state(RunStatus::Failed);
7926 state
7927 .quota
7928 .push(loss("advisor-1", "2026-10-22T14:38:00Z", None));
7929 state.begin_pass();
7930 let mut t = task();
7931 t.start(state.id.clone());
7932 reclaim(&mut t, Some(state), 2, "en");
7933 assert_eq!(t.attempts, 1);
7934 }
7935
7936 #[test]
7937 fn an_all_seats_unauthenticated_node_refunds_and_holds_without_retry() {
7938 let mut state = run_state(RunStatus::Blocked);
7939 let losses: Vec<_> = ["alpha", "beta"]
7940 .into_iter()
7941 .enumerate()
7942 .map(|(i, agent)| {
7943 QuotaLoss::from_report(
7944 format!("advisor-{i}"),
7945 "advise",
7946 Some(&crate::agent::Quota {
7947 cause: crate::agent::QuotaCause::Authentication,
7948 agent: agent.to_owned(),
7949 reset: None,
7950 }),
7951 )
7952 })
7953 .collect();
7954 crate::graph::block_machine_outage(&mut state, "advise", &losses);
7955 state.quota = losses;
7956 let mut t = task();
7957 t.start(state.id.clone());
7958 let verdict = Verdict {
7959 status: state.status,
7960 left_pr: false,
7961 quota_hit: true,
7962 parked: false,
7963 no_viable_candidates: true,
7964 };
7965 settle_and_diagnose(&mut t, verdict, "authentication unavailable", 2, &state);
7966 assert_eq!(t.attempts, 0);
7967 assert_eq!(t.status, TaskStatus::Held);
7968 assert!(!t.operator_held());
7969 let reason = t.hold_reason.as_deref().unwrap();
7970 assert!(reason.starts_with("[authentication]"));
7971 assert!(
7972 reason.contains("alpha")
7973 && reason.contains("beta")
7974 && reason.contains("re-authenticate")
7975 );
7976 assert!(cooldown_until(&state.quota, Timestamp::now()).is_none());
7977 let mut orphan = task();
7979 orphan.start(state.id.clone());
7980 reclaim(&mut orphan, Some(state), 2, "en");
7981 assert_eq!(orphan.attempts, 0);
7982 assert_eq!(orphan.status, TaskStatus::Held);
7983 }
7984
7985 #[test]
7986 fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
7987 let mut state = RunState::new(
7988 PathBuf::from("/repo"),
7989 "main".to_owned(),
7990 "abc1234".to_owned(),
7991 "task".to_owned(),
7992 Config::default(),
7993 );
7994 state.status = RunStatus::Blocked;
7995 state.resource_block = Some(crate::run::ResourceBlock {
7996 cause: crate::run::ResourceBlockCause::Other,
7997 node: "graft".to_owned(),
7998 kind: "shared build cache".to_owned(),
7999 detail: "timed out".to_owned(),
8000 at: jiff::Timestamp::now(),
8001 });
8002 let mut t = task();
8003 t.start("20260902-000000-aaaa".to_owned());
8004 assert_eq!(t.attempts, 1);
8005 let verdict = Verdict {
8006 status: RunStatus::Blocked,
8007 left_pr: false,
8008 quota_hit: false,
8009 parked: false,
8010 no_viable_candidates: false,
8011 };
8012 settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
8013 assert_eq!(t.status, TaskStatus::Held);
8014 assert_eq!(t.attempts, 0, "the attempt is refunded");
8015 assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
8016 assert!(
8017 !t.operator_held(),
8018 "a machine hold, released without a human"
8019 );
8020
8021 let mut selected = task();
8022 selected.start("20260902-000000-cccc".into());
8023 selected.replacement = Some(crate::merge_decision::Replacement {
8024 question: "fixture".into(),
8025 run: "earlier".into(),
8026 pr: "https://example.invalid/pr/1".into(),
8027 agent: "selected".into(),
8028 context: "fixture".into(),
8029 });
8030 state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
8031 settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
8032 assert_eq!(selected.attempts, 0);
8033 assert!(
8034 !selected.operator_held(),
8035 "a selected agent also retains a machine resource hold"
8036 );
8037 assert!(
8038 selected
8039 .hold_reason
8040 .as_deref()
8041 .unwrap()
8042 .starts_with("[resource] ")
8043 );
8044
8045 let mut p = task();
8047 p.start("20260902-000000-bbbb".to_owned());
8048 settle_and_diagnose(
8049 &mut p,
8050 Verdict {
8051 parked: true,
8052 ..verdict
8053 },
8054 "parked",
8055 2,
8056 &state,
8057 );
8058 assert_eq!(p.status, TaskStatus::Parked);
8059 assert_eq!(
8060 p.attempts, 0,
8061 "parking refunds once rather than also settling the resource hold"
8062 );
8063 }
8064
8065 #[test]
8066 fn record_failure_notice_links_the_task() {
8067 let dir = tempfile::tempdir().unwrap();
8068 std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
8071 let queue = Queue::at(dir.path().join("queue"));
8072 let mut t = interrupt_task("rec-fail-1");
8073 record(&queue, &mut t);
8074
8075 let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
8076 assert_eq!(found.len(), 1);
8077 assert_eq!(found[0].key, "loop:record");
8078 assert_eq!(
8079 found[0].link,
8080 Some(Link::Task {
8081 id: "rec-fail-1".to_owned()
8082 })
8083 );
8084 }
8085
8086 fn interrupt_task(id: &str) -> Task {
8089 let mut t = task();
8090 t.id = id.to_owned();
8091 t.interrupt = true;
8092 t
8093 }
8094
8095 fn task_with_id(id: &str) -> Task {
8097 let mut t = task();
8098 t.id = id.to_owned();
8099 t
8100 }
8101
8102 fn urgent_task(id: &str) -> Task {
8104 let mut t = task();
8105 t.id = id.to_owned();
8106 t.urgent = true;
8107 t
8108 }
8109
8110 #[test]
8111 fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
8112 let dir = tempfile::tempdir().unwrap();
8113 let queue = Queue::at(dir.path().join("queue"));
8114 let mut parked = task_with_id("parked");
8115 parked.start("run".into());
8116 parked.park("upgrade");
8117 parked.record_pass_at(
8118 "run",
8119 0,
8120 Some(Timestamp::now()),
8121 1,
8122 Some(crate::run::ParkCause::Upgrade {
8123 from: "old".into(),
8124 to: None,
8125 }),
8126 );
8127 let mut fresh = task_with_id("fresh");
8128 fresh.priority = 100;
8129 let mut urgent_task = urgent_task("urgent");
8130 for t in [&mut parked, &mut fresh, &mut urgent_task] {
8131 queue.put(t).unwrap();
8132 }
8133 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
8134 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
8135 let candidates = runnable(&queue);
8136 assert_eq!(candidates[0].id, parked.id);
8137 let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
8138 assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_err());
8139 assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_ok());
8140 drop(first);
8141 let claimed_elsewhere = queue.claim(&parked.id).unwrap();
8142 let next = runnable(&queue)
8143 .into_iter()
8144 .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent).ok())
8145 .unwrap();
8146 assert_eq!(next.task.id, fresh.id);
8147 assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
8148 drop(claimed_elsewhere);
8149 drop(next);
8150 assert!(matches!(
8151 claim_dispatch(&queue, &parked, true, &ordinary, &urgent),
8152 Err(SkipReason::CoolingDown)
8153 ));
8154 }
8155
8156 #[test]
8157 fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
8158 let dir = tempfile::tempdir().unwrap();
8159 let queue = Queue::at(dir.path().join("queue"));
8160 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
8161 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
8162 let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
8163 let mut first = task();
8164 queue.put(&mut first).unwrap();
8165 let stale_plain = queue.get(&first.id).unwrap();
8166 first.set_urgent(true).unwrap();
8167 queue.put(&mut first).unwrap();
8168 let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
8169 let mut second = urgent_task("second");
8170 queue.put(&mut second).unwrap();
8171 assert!(matches!(
8172 claim_dispatch(&queue, &second, false, &ordinary, &urgent),
8173 Err(SkipReason::UrgentCapacity)
8174 ));
8175 drop(queue.claim(&second.id).unwrap());
8176 assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
8177 drop(dispatched);
8178 let stale_urgent = queue.get(&first.id).unwrap();
8179 first.set_urgent(false).unwrap();
8180 queue.put(&mut first).unwrap();
8181 assert!(matches!(
8182 claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent),
8183 Err(SkipReason::OrdinaryCapacity)
8184 ));
8185 assert_eq!(urgent.available_permits(), 1);
8186 drop(queue.claim(&first.id).unwrap());
8187 drop(occupied);
8188 }
8189
8190 #[test]
8191 fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
8192 let dir = tempfile::tempdir().unwrap();
8193 let queue = Queue::at(dir.path().join("queue"));
8194 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
8195 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
8196 let mut t = task();
8197 queue.put(&mut t).unwrap();
8198 for enabled in [true, false] {
8199 let stale = queue.get(&t.id).unwrap();
8200 t.set_urgent(enabled).unwrap();
8201 queue.put(&mut t).unwrap();
8202 assert_ne!(stale.urgent, enabled);
8203 let DispatchClaim {
8204 task: fresh,
8205 claim,
8206 permit,
8207 } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
8208 assert_eq!(fresh.urgent, enabled);
8209 assert_eq!(ordinary.available_permits(), usize::from(enabled));
8210 assert_eq!(urgent.available_permits(), usize::from(!enabled));
8211 assert!(queue.claim(&t.id).is_err());
8212 assert_eq!(fresh.attempts, stale.attempts);
8213 drop((claim, permit));
8214 assert_eq!(ordinary.available_permits(), 1);
8215 assert_eq!(urgent.available_permits(), 1);
8216 }
8217 t.set_urgent(true).unwrap();
8218 queue.put(&mut t).unwrap();
8219 let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
8220 assert!(matches!(
8221 claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8222 Err(SkipReason::UrgentCapacity)
8223 ));
8224 assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
8225 drop(queue.claim(&t.id).unwrap());
8226 assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
8227 drop(occupied);
8228 assert!(matches!(
8229 claim_dispatch(&queue, &t, true, &ordinary, &urgent),
8230 Err(SkipReason::CoolingDown)
8231 ));
8232 drop(queue.claim(&t.id).unwrap());
8233 let held = queue.claim(&t.id).unwrap();
8234 assert!(matches!(
8235 claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8236 Err(SkipReason::ClaimUnavailable)
8237 ));
8238 drop(held);
8239 t.status = TaskStatus::Held;
8240 queue.put(&mut t).unwrap();
8241 assert!(matches!(
8242 claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8243 Err(SkipReason::NoLongerRunnable)
8244 ));
8245 drop(queue.claim(&t.id).unwrap());
8246 std::fs::remove_file(queue.path_of(&t.id)).unwrap();
8247 assert!(matches!(
8248 claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8249 Err(SkipReason::RereadFailed)
8250 ));
8251 drop(queue.claim(&t.id).unwrap());
8252 assert_eq!(urgent.available_permits(), 1);
8253 }
8254
8255 #[test]
8260 fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
8261 assert_eq!(permit_kind(true, false), PermitKind::None);
8262 assert_eq!(permit_kind(true, true), PermitKind::None);
8263 }
8264
8265 #[test]
8270 fn permit_kind_separates_urgent_from_ordinary() {
8271 assert_eq!(permit_kind(false, true), PermitKind::Urgent);
8272 assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
8273 }
8274
8275 #[test]
8282 fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
8283 let cfg = Config::default();
8284 let repo = Path::new("/any/repo/path");
8285
8286 let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(1024))
8287 .expect("must hold below the threshold");
8288 assert!(reason.contains("1024"), "{reason}");
8289 assert!(
8290 reason.contains(&cfg.disk.min_free_bytes.to_string()),
8291 "{reason}"
8292 );
8293
8294 assert_eq!(
8295 disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(cfg.disk.min_free_bytes)),
8296 None,
8297 "exactly at the floor is open"
8298 );
8299 assert_eq!(
8300 disk_gate_with(
8301 repo,
8302 &cfg,
8303 PathBuf::new,
8304 |_| Ok(cfg.disk.min_free_bytes + 1)
8305 ),
8306 None,
8307 "comfortably above the floor is open"
8308 );
8309 }
8310
8311 #[test]
8312 fn disk_gate_with_checks_cache_and_worktree_volumes_and_measurement_errors() {
8313 let dir = tempfile::tempdir().unwrap();
8314 let repo = dir.path().join("repo");
8315 let cache = dir.path().join("cache");
8316 let worktrees = dir.path().join("worktrees");
8317 for path in [&repo, &cache, &worktrees] {
8318 std::fs::create_dir(path).unwrap();
8319 }
8320 let mut cfg = Config::default();
8321 cfg.graph.worktree_root = Some(worktrees.clone());
8322 cfg.verify.gate = vec![format!(
8323 "CARGO_TARGET_DIR='{}' cargo build",
8324 cache.display()
8325 )];
8326 for blocked in [&cache, &worktrees] {
8327 for unmeasured in [false, true] {
8328 assert!(
8329 disk_gate_with(&repo, &cfg, PathBuf::new, |path| {
8330 if path == blocked {
8331 if unmeasured {
8332 Err(anyhow::anyhow!("measurement failed"))
8333 } else {
8334 Ok(0)
8335 }
8336 } else {
8337 Ok(u64::MAX)
8338 }
8339 })
8340 .is_some(),
8341 "a blocked secondary output volume must close admission"
8342 );
8343 }
8344 }
8345 assert!(disk_gate_with(&repo, &cfg, PathBuf::new, |_| Ok(u64::MAX)).is_none());
8346 }
8347
8348 #[test]
8349 fn isolated_admission_measures_the_run_home_instead_of_the_shared_cache() {
8350 let dir = tempfile::tempdir().unwrap();
8351 let repo = dir.path().join("repo");
8352 let cache = dir.path().join("cache");
8353 let home_parent = dir.path().join("run-volume");
8354 let home = home_parent.join("new-home");
8355 for path in [&repo, &cache, &home_parent] {
8356 std::fs::create_dir(path).unwrap();
8357 }
8358 let mut cfg = Config::default();
8359 cfg.graph.worktree_root = Some(repo.clone());
8360 cfg.verify.gate = vec![format!(
8361 "CARGO_TARGET_DIR='{}' cargo build",
8362 cache.display()
8363 )];
8364 cfg.verify.build_cache = BuildCache::Isolated;
8365 let denied = |blocked: &Path| {
8366 disk_gate_with(
8367 &repo,
8368 &cfg,
8369 || home.clone(),
8370 |path| Ok(if path == blocked { 0 } else { u64::MAX }),
8371 )
8372 .is_some()
8373 };
8374 assert!(!denied(&cache));
8375 assert!(denied(&home_parent));
8376 }
8377
8378 #[test]
8379 fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
8380 let mut cfg = Config::default();
8381 cfg.disk.min_free_bytes = 0;
8382 let repo = Path::new("/any/repo/path");
8383 assert_eq!(
8384 disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(0)),
8385 None,
8386 "a zero floor never measures at all"
8387 );
8388 }
8389
8390 #[test]
8391 fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
8392 let cfg = Config::default();
8393 let repo = Path::new("/any/repo/path");
8394 let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| {
8395 Err(anyhow::anyhow!("no df on this box"))
8396 })
8397 .expect("a measurement failure must close the gate, not open it");
8398 assert!(reason.contains("could not measure"), "{reason}");
8399 }
8400
8401 #[test]
8402 fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
8403 let ordinary = task();
8404 let next = advance_interrupt(
8405 Interrupt::Idle,
8406 std::slice::from_ref(&ordinary.id),
8407 std::slice::from_ref(&ordinary),
8408 );
8409 assert_eq!(next, Interrupt::Idle);
8410 }
8411
8412 #[test]
8413 fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
8414 let marked = interrupt_task("marked");
8417 let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
8418 assert_eq!(next, Interrupt::Idle);
8419 }
8420
8421 #[test]
8422 fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
8423 let marked = interrupt_task("marked");
8424 let next = advance_interrupt(
8425 Interrupt::Idle,
8426 &["running".to_owned()],
8427 std::slice::from_ref(&marked),
8428 );
8429 assert_eq!(
8430 next,
8431 Interrupt::Parking {
8432 parked: vec!["running".to_owned()],
8433 interrupt_task: "marked".to_owned(),
8434 }
8435 );
8436 }
8437
8438 #[test]
8447 fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
8448 let marked = interrupt_task("marked");
8449
8450 let two = advance_interrupt(
8451 Interrupt::Idle,
8452 &["a".to_owned(), "b".to_owned()],
8453 std::slice::from_ref(&marked),
8454 );
8455 assert_eq!(two, Interrupt::Idle);
8456
8457 let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
8458 assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
8459 }
8460
8461 #[test]
8462 fn parking_holds_until_every_parked_id_has_actually_left_flight() {
8463 let state = Interrupt::Parking {
8464 parked: vec!["running".to_owned()],
8465 interrupt_task: "marked".to_owned(),
8466 };
8467 let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
8469 assert_eq!(still_going, state);
8470
8471 let stopped_but_not_yet_dispatched =
8475 advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
8476 assert_eq!(stopped_but_not_yet_dispatched, state);
8477
8478 let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
8480 assert_eq!(
8481 dispatched,
8482 Interrupt::Running {
8483 parked: vec!["running".to_owned()],
8484 interrupt_task: "marked".to_owned(),
8485 }
8486 );
8487 }
8488
8489 #[test]
8490 fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
8491 let state = Interrupt::Running {
8492 parked: vec!["running".to_owned()],
8493 interrupt_task: "marked".to_owned(),
8494 };
8495 let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
8496 assert_eq!(still_running, state);
8497
8498 let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
8505 assert_eq!(
8506 ended,
8507 Interrupt::Resuming {
8508 parked: vec!["running".to_owned()]
8509 }
8510 );
8511 }
8512
8513 #[test]
8514 fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
8515 let state = Interrupt::Resuming {
8516 parked: vec!["running".to_owned()],
8517 };
8518 let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
8519 assert_eq!(still_waiting, state);
8520
8521 let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
8522 assert_eq!(dispatched, Interrupt::Idle);
8523 }
8524
8525 #[test]
8531 fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
8532 {
8533 let state = Interrupt::Parking {
8534 parked: vec!["running".to_owned()],
8535 interrupt_task: "marked".to_owned(),
8536 };
8537 let next = advance_interrupt(state, &[], &[]);
8540 assert_eq!(
8541 next,
8542 Interrupt::Resuming {
8543 parked: vec!["running".to_owned()]
8544 },
8545 "abandoning the interrupt must not abandon the resume it owes"
8546 );
8547 }
8548
8549 #[test]
8552 fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
8553 let state = Interrupt::Resuming {
8554 parked: vec!["running".to_owned()],
8555 };
8556 let next = advance_interrupt(state, &[], &[]);
8557 assert_eq!(
8558 next,
8559 Interrupt::Idle,
8560 "nothing is left to wait for; the loop must not stay wedged"
8561 );
8562 }
8563
8564 #[test]
8565 fn disabled_by_config_the_sequence_can_never_leave_idle() {
8566 let marked = interrupt_task("marked");
8567 let next = advance_interrupt_tick(
8568 false,
8569 Interrupt::Idle,
8570 &["running".to_owned()],
8571 std::slice::from_ref(&marked),
8572 );
8573 assert_eq!(
8574 next,
8575 Interrupt::Idle,
8576 "an unmarked, unconfigured daemon must behave exactly as before"
8577 );
8578 }
8579
8580 #[test]
8581 fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
8582 let state = Interrupt::Parking {
8583 parked: vec!["running".to_owned()],
8584 interrupt_task: "marked".to_owned(),
8585 };
8586 let candidates = vec![interrupt_task("marked"), task()];
8587 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
8588 assert!(
8589 allowed.is_empty(),
8590 "nothing may dispatch - not even the interrupt task itself - \
8591 until the parked run has actually stopped"
8592 );
8593 }
8594
8595 #[test]
8609 fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
8610 for state in [
8611 Interrupt::Parking {
8612 parked: vec!["running".to_owned()],
8613 interrupt_task: "marked".to_owned(),
8614 },
8615 Interrupt::Running {
8616 parked: vec!["running".to_owned()],
8617 interrupt_task: "marked".to_owned(),
8618 },
8619 Interrupt::Resuming {
8620 parked: vec!["running".to_owned()],
8621 },
8622 ] {
8623 let candidates = vec![
8624 interrupt_task("marked"),
8625 urgent_task("hot"),
8626 task_with_id("ordinary"),
8627 ];
8628 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
8629 assert!(
8630 !allowed.iter().any(|t| t.id == "hot"),
8631 "an urgent candidate must wait out the same gate as anything \
8632 else while the run it would run alongside has not actually \
8633 left flight, for state {state:?}: {allowed:?}"
8634 );
8635 }
8636 }
8637
8638 #[test]
8644 fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
8645 let state = Interrupt::Resuming {
8646 parked: vec!["hot".to_owned()],
8647 };
8648 let candidates = vec![urgent_task("hot"), task()];
8649 let allowed = interrupt_gate(&state, &[], candidates);
8650 assert_eq!(
8651 allowed.iter().filter(|t| t.id == "hot").count(),
8652 1,
8653 "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
8654 );
8655 }
8656
8657 #[test]
8658 fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
8659 let state = Interrupt::Parking {
8660 parked: vec!["running".to_owned()],
8661 interrupt_task: "marked".to_owned(),
8662 };
8663 let other = task();
8664 let candidates = vec![interrupt_task("marked"), other.clone()];
8665 let allowed = interrupt_gate(&state, &[], candidates);
8666 assert_eq!(allowed.len(), 1);
8667 assert_eq!(allowed[0].id, "marked");
8668 }
8669
8670 #[test]
8671 fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
8672 let state = Interrupt::Running {
8673 parked: vec!["running".to_owned()],
8674 interrupt_task: "marked".to_owned(),
8675 };
8676 let candidates = vec![task(), task()];
8677 let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
8678 assert!(allowed.is_empty());
8679 }
8680
8681 #[test]
8688 fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
8689 let state = Interrupt::Resuming {
8690 parked: vec!["a".to_owned(), "c".to_owned()],
8691 };
8692 let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
8693 let allowed = interrupt_gate(&state, &[], candidates);
8694 assert_eq!(
8695 allowed.len(),
8696 1,
8697 "at most one candidate may be offered while resuming: {allowed:?}"
8698 );
8699 assert_eq!(allowed[0].id, "a");
8700 }
8701
8702 #[test]
8703 fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
8704 let state = Interrupt::Resuming {
8705 parked: vec!["a".to_owned()],
8706 };
8707 let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
8708 assert!(allowed.is_empty());
8709 }
8710
8711 #[test]
8717 fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
8718 let running = task(); let marked = interrupt_task("marked");
8720
8721 let mut state = Interrupt::Idle;
8722 let in_flight = vec![running.id.clone()];
8724 state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
8725 let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
8726 assert!(gated.is_empty(), "still waiting on `running` to park");
8727
8728 state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
8730 let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
8731 assert_eq!(
8732 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8733 vec!["marked"],
8734 "only the interrupt task may be offered to the dispatcher now"
8735 );
8736
8737 state = advance_interrupt_tick(
8739 true,
8740 state,
8741 &["marked".to_owned()],
8742 std::slice::from_ref(&running),
8743 );
8744 let gated = interrupt_gate(
8745 &state,
8746 &["marked".to_owned()],
8747 vec![marked.clone(), running.clone()],
8748 );
8749 assert!(
8750 gated.is_empty(),
8751 "the parked run must not be offered back while the interrupt \
8752 task is still running"
8753 );
8754
8755 let other = task_with_id("other");
8759 state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
8760 assert_eq!(
8761 state,
8762 Interrupt::Resuming {
8763 parked: vec![running.id.clone()]
8764 }
8765 );
8766 let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
8767 assert_eq!(
8768 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8769 vec![running.id.as_str()],
8770 "exactly the parked run resumes - not the unrelated task, even \
8771 though it was offered first"
8772 );
8773
8774 state = advance_interrupt_tick(
8778 true,
8779 state,
8780 std::slice::from_ref(&running.id),
8781 std::slice::from_ref(&other),
8782 );
8783 assert_eq!(state, Interrupt::Idle);
8784 let gated = interrupt_gate(
8785 &state,
8786 std::slice::from_ref(&running.id),
8787 vec![other.clone()],
8788 );
8789 assert_eq!(
8790 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8791 vec![other.id.as_str()],
8792 "ordinary dispatch is unrestricted again"
8793 );
8794 }
8795
8796 #[test]
8797 fn every_run_status_settles_the_task_it_came_from() {
8798 let table = [
8800 (RunStatus::Merged, TaskStatus::Done, 1),
8801 (RunStatus::Ready, TaskStatus::Done, 1),
8802 (RunStatus::Stalled, TaskStatus::Failed, 0),
8803 (RunStatus::Blocked, TaskStatus::Failed, 1),
8804 (RunStatus::Failed, TaskStatus::Failed, 1),
8805 (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
8806 (RunStatus::Prep, TaskStatus::Failed, 1),
8807 (RunStatus::Implementing, TaskStatus::Failed, 1),
8808 (RunStatus::Judging, TaskStatus::Failed, 1),
8809 (RunStatus::Deliberating, TaskStatus::Failed, 1),
8810 (RunStatus::Voting, TaskStatus::Failed, 1),
8811 (RunStatus::Reviewing, TaskStatus::Failed, 1),
8812 (RunStatus::Gating, TaskStatus::Failed, 1),
8813 ];
8814 for (run, want, attempts) in table {
8815 let mut t = task();
8816 t.start("20260902-000000-aaaa".to_owned());
8817 settle(
8818 &mut t,
8819 Verdict {
8820 status: run,
8821 left_pr: false,
8822 parked: false,
8823 quota_hit: matches!(run, RunStatus::Stalled),
8824 no_viable_candidates: false,
8825 },
8826 "why",
8827 2,
8828 );
8829 assert_eq!(t.status, want, "task status after {}", label(run));
8830 assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
8831 }
8832 }
8833
8834 #[test]
8835 fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
8836 let mut stalled = task();
8837 stalled.start("20260902-000000-aaaa".to_owned());
8838 settle(
8839 &mut stalled,
8840 Verdict {
8841 status: RunStatus::Stalled,
8842 left_pr: false,
8843 parked: false,
8844 quota_hit: true,
8845 no_viable_candidates: false,
8846 },
8847 "quota",
8848 1,
8849 );
8850 assert_eq!(stalled.attempts, 0);
8851 assert!(
8852 stalled.status.runnable(),
8853 "a machine problem must leave the task in line"
8854 );
8855
8856 let mut blocked = task();
8857 blocked.start("20260902-000000-aaaa".to_owned());
8858 settle(
8859 &mut blocked,
8860 Verdict {
8861 status: RunStatus::Blocked,
8862 left_pr: false,
8863 parked: false,
8864 quota_hit: false,
8865 no_viable_candidates: false,
8866 },
8867 "findings open",
8868 1,
8869 );
8870 assert_eq!(blocked.attempts, 1);
8871 assert_eq!(
8872 blocked.status,
8873 TaskStatus::Held,
8874 "the last attempt hands the task to a human"
8875 );
8876 }
8877
8878 #[test]
8879 fn a_run_that_opened_a_pull_request_is_never_re_competed() {
8880 let mut delivered = task();
8883 delivered.start("20260903-080619-01c2".to_owned());
8884 settle(
8885 &mut delivered,
8886 Verdict {
8887 status: RunStatus::Blocked,
8888 left_pr: true,
8889 parked: false,
8890 quota_hit: false,
8891 no_viable_candidates: false,
8892 },
8893 "no check status",
8894 4,
8895 );
8896 assert_eq!(
8897 delivered.status,
8898 TaskStatus::Held,
8899 "a pull request waiting on CI or a person is not a retryable failure"
8900 );
8901 assert!(
8902 !delivered.status.runnable(),
8903 "the loop must not pick this task up again"
8904 );
8905 assert_eq!(
8906 delivered.last_error.as_deref(),
8907 Some("no check status"),
8908 "the operator needs to be told what the gate was waiting for"
8909 );
8910
8911 let mut empty_handed = task();
8914 empty_handed.start("20260903-080619-01c2".to_owned());
8915 settle(
8916 &mut empty_handed,
8917 Verdict {
8918 status: RunStatus::Blocked,
8919 left_pr: false,
8920 parked: false,
8921 quota_hit: false,
8922 no_viable_candidates: false,
8923 },
8924 "findings open",
8925 4,
8926 );
8927 assert_eq!(empty_handed.status, TaskStatus::Failed);
8928 assert!(empty_handed.status.runnable());
8929 }
8930
8931 #[test]
8932 fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
8933 let mut noop = task();
8939 noop.start("20260912-131304-391f".to_owned());
8940 settle(
8941 &mut noop,
8942 Verdict {
8943 status: RunStatus::VerifiedNoop,
8944 left_pr: false,
8945 parked: false,
8946 quota_hit: false,
8947 no_viable_candidates: true,
8948 },
8949 "candidate A: already fixed by b32cfc4, on main",
8950 4,
8951 );
8952 assert_eq!(
8953 noop.status,
8954 TaskStatus::Held,
8955 "an unverified claim is a request for a human, not a failure"
8956 );
8957 assert!(
8958 !noop.status.runnable(),
8959 "the loop must not requeue this on the same unverified claim"
8960 );
8961 assert_eq!(noop.attempts, 1);
8966 }
8967
8968 #[test]
8969 fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
8970 let mut parked = task();
8975 parked.start("20260903-183634-2d98".to_owned());
8976 settle(
8977 &mut parked,
8978 Verdict {
8979 status: RunStatus::Implementing,
8980 left_pr: false,
8981 quota_hit: false,
8982 parked: true,
8983 no_viable_candidates: false,
8984 },
8985 "parked after `implementing`",
8986 2,
8987 );
8988 assert_eq!(parked.attempts, 0, "a park is refunded");
8989 assert!(
8990 parked.status.runnable(),
8991 "and the task stays in line so the next loop resumes its run"
8992 );
8993 assert_eq!(parked.status, TaskStatus::Parked);
8994 assert_eq!(
8995 parked.park_reason.as_deref(),
8996 Some("parked after `implementing`"),
8997 "the card says where it stopped"
8998 );
8999 assert_eq!(parked.last_error, None, "nothing failed");
9000
9001 let mut broken = task();
9005 broken.start("20260903-183634-2d98".to_owned());
9006 settle(
9007 &mut broken,
9008 Verdict {
9009 status: RunStatus::Implementing,
9010 left_pr: false,
9011 quota_hit: false,
9012 parked: false,
9013 no_viable_candidates: false,
9014 },
9015 "returned mid-flight",
9016 2,
9017 );
9018 assert_eq!(broken.attempts, 1);
9019 }
9020
9021 #[test]
9022 fn only_a_rate_limit_buys_the_task_its_attempt_back() {
9023 let mut flaky = task();
9028 flaky.start("20260903-123023-e633".to_owned());
9029 settle(
9030 &mut flaky,
9031 Verdict {
9032 status: RunStatus::Stalled,
9033 left_pr: false,
9034 parked: false,
9035 quota_hit: false,
9036 no_viable_candidates: false,
9037 },
9038 "verdict rests on 1 of 3 judges",
9039 2,
9040 );
9041 assert_eq!(
9042 flaky.attempts, 1,
9043 "flakiness spends an attempt, so `max_attempts` still bounds it"
9044 );
9045 assert!(flaky.status.runnable(), "and it is still worth retrying");
9046
9047 let mut limited = task();
9049 limited.start("20260903-123023-e633".to_owned());
9050 settle(
9051 &mut limited,
9052 Verdict {
9053 status: RunStatus::Stalled,
9054 left_pr: false,
9055 parked: false,
9056 quota_hit: true,
9057 no_viable_candidates: false,
9058 },
9059 "judge-2, judge-3 out of quota",
9060 2,
9061 );
9062 assert_eq!(limited.attempts, 0, "a quota window is refunded");
9063 assert!(limited.status.runnable());
9064
9065 let mut worn = task();
9068 for _ in 0..2 {
9069 worn.release();
9070 }
9071 worn.start("20260903-123023-e633".to_owned());
9072 worn.attempts = 2;
9073 settle(
9074 &mut worn,
9075 Verdict {
9076 status: RunStatus::Stalled,
9077 left_pr: false,
9078 parked: false,
9079 quota_hit: false,
9080 no_viable_candidates: false,
9081 },
9082 "no quorum again",
9083 2,
9084 );
9085 assert_eq!(worn.status, TaskStatus::Held);
9086 assert!(!worn.status.runnable());
9087 }
9088
9089 #[test]
9090 fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
9091 let mut wiped_out = task();
9098 wiped_out.start("20260907-025000-a1b2".to_owned());
9099 settle(
9100 &mut wiped_out,
9101 Verdict {
9102 status: RunStatus::Failed,
9103 left_pr: false,
9104 parked: false,
9105 quota_hit: true,
9106 no_viable_candidates: true,
9107 },
9108 "no candidate produced a change; nothing to judge",
9109 2,
9110 );
9111 assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
9112 assert!(
9113 wiped_out.status.runnable(),
9114 "a machine problem must leave the task in line"
9115 );
9116
9117 let mut partial_progress = task();
9123 partial_progress.start("20260907-025500-c3d4".to_owned());
9124 settle(
9125 &mut partial_progress,
9126 Verdict {
9127 status: RunStatus::Failed,
9128 left_pr: false,
9129 parked: false,
9130 quota_hit: true,
9131 no_viable_candidates: false,
9132 },
9133 "gate failed on the winning candidate",
9134 2,
9135 );
9136 assert_eq!(
9137 partial_progress.attempts, 1,
9138 "a candidate that actually produced a change spends the attempt \
9139 even though some other seat hit its quota"
9140 );
9141 assert!(partial_progress.status.runnable());
9142 }
9143
9144 #[test]
9145 fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
9146 let mut t = task();
9152 t.start("20260907-025000-a1b2".to_owned());
9153 let mut state = run_state(RunStatus::Failed);
9154 state.quota.push(QuotaLoss {
9155 cause: crate::agent::QuotaCause::UsageLimit,
9156 agent: String::new(),
9157 seat: "cand-a".to_owned(),
9158 node: "implement".to_owned(),
9159 at: Timestamp::now(),
9160 reset: None,
9161 });
9162 assert!(
9163 state.viable().is_empty(),
9164 "no candidate was added, so nothing is viable"
9165 );
9166 reclaim(&mut t, Some(state), 2, "en");
9167 assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
9168 assert!(t.status.runnable());
9169 }
9170
9171 #[test]
9172 fn a_held_task_is_never_offered_to_the_loop() {
9173 let dir = tempfile::tempdir().unwrap();
9174 let queue = Queue::at(dir.path().to_path_buf());
9175 for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
9176 let mut t = task();
9177 t.id = format!("2026090{n}-000000-000{n}");
9178 t.priority = priority;
9179 queue.put(&mut t).unwrap();
9180 }
9181 let mut held = task();
9182 held.id = "20260909-000000-9999".to_owned();
9183 held.priority = 99;
9184 held.hold_machine(None);
9185 queue.put(&mut held).unwrap();
9186
9187 let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
9188 assert_eq!(order.len(), 3);
9189 assert!(!order.contains(&held.id));
9190 assert_eq!(
9191 order.first().cloned(),
9192 queue.next_runnable().map(|t| t.id),
9193 "the loop's first candidate is exactly what the queue offers"
9194 );
9195 assert_eq!(
9196 order,
9197 vec![
9198 "20260902-000000-0002".to_owned(),
9199 "20260903-000000-0003".to_owned(),
9200 "20260901-000000-0001".to_owned(),
9201 ],
9202 "priority first, then oldest, so nothing starves"
9203 );
9204 }
9205
9206 #[test]
9207 fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
9208 let dir = tempfile::tempdir().unwrap();
9209 let queue = Queue::at(dir.path().to_path_buf());
9210 let mut old = task();
9211 old.id = "20260101-000000-old0".to_owned();
9212 queue.put(&mut old).unwrap();
9213 let mut fresh = task();
9214 fresh.id = "20260101-000000-new0".to_owned();
9215 queue.put(&mut fresh).unwrap();
9216
9217 std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
9221 std::thread::sleep(Duration::from_millis(60));
9222 let live = queue.claim(&fresh.id).unwrap();
9223
9224 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
9225 assert_eq!(swept, vec![old.id.clone()]);
9226 assert!(
9227 queue.claim(&old.id).is_ok(),
9228 "an unparseable lock older than the threshold is swept"
9229 );
9230 assert!(
9231 queue.claim(&fresh.id).is_err(),
9232 "a live pid protects its lock regardless of age"
9233 );
9234 drop(live);
9235 }
9236
9237 #[test]
9238 fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
9239 let dir = tempfile::tempdir().unwrap();
9242 let queue = Queue::at(dir.path().to_path_buf());
9243 let mut t = task();
9244 t.id = "20260101-000000-live".to_owned();
9245 queue.put(&mut t).unwrap();
9246
9247 let claim = queue.claim(&t.id).unwrap();
9248 std::thread::sleep(Duration::from_millis(60));
9249
9250 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
9251 assert!(
9252 swept.is_empty(),
9253 "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
9254 );
9255 assert!(
9256 queue.claim(&t.id).is_err(),
9257 "the lock still protects its task"
9258 );
9259 drop(claim);
9260 }
9261
9262 fn injected_dead_pid() -> u32 {
9265 std::process::id().checked_add(1).unwrap_or(1)
9266 }
9267
9268 #[test]
9269 fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
9270 let dir = tempfile::tempdir().unwrap();
9271 let queue = Queue::at(dir.path().to_path_buf());
9272 let mut t = task();
9273 t.id = "20260101-000000-dead".to_owned();
9274 queue.put(&mut t).unwrap();
9275 let dead_pid = injected_dead_pid();
9276
9277 std::fs::write(
9282 dir.path().join(format!("{}.lock", t.id)),
9283 dead_pid.to_string(),
9284 )
9285 .unwrap();
9286
9287 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
9288 pid != dead_pid
9289 });
9290 assert_eq!(
9291 swept,
9292 vec![t.id.clone()],
9293 "a dead owner is reclaimed immediately, not after STALE_CLAIM"
9294 );
9295 assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
9296 }
9297
9298 #[test]
9299 fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
9300 let dir = tempfile::tempdir().unwrap();
9301 let queue = Queue::at(dir.path().to_path_buf());
9302 let mut t = task();
9303 t.id = "20260101-000000-late".to_owned();
9304 queue.put(&mut t).unwrap();
9305 let dead_pid = injected_dead_pid();
9306
9307 assert!(
9310 sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
9311 "nothing has claimed the task yet"
9312 );
9313
9314 std::fs::write(
9317 dir.path().join(format!("{}.lock", t.id)),
9318 dead_pid.to_string(),
9319 )
9320 .unwrap();
9321
9322 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
9326 pid != dead_pid
9327 });
9328 assert_eq!(swept, vec![t.id.clone()]);
9329 }
9330
9331 #[test]
9332 fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
9333 crate::run::pin_test_home();
9338 let dir = tempfile::tempdir().unwrap();
9339 let queue = Queue::at(dir.path().to_path_buf());
9340 let mut t = task();
9341 t.id = "20260101-000000-crsh".to_owned();
9342 t.status = TaskStatus::Running;
9343 t.attempts = 1;
9344 t.runs.push("20260904-000000-4043".to_owned());
9348 queue.put(&mut t).unwrap();
9349 let dead_pid = injected_dead_pid();
9350
9351 std::fs::write(
9354 dir.path().join(format!("{}.lock", t.id)),
9355 dead_pid.to_string(),
9356 )
9357 .unwrap();
9358
9359 assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
9365 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
9366
9367 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
9368 pid != dead_pid
9369 });
9370 assert_eq!(swept, vec![t.id.clone()]);
9371
9372 let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
9373 assert_eq!(reclaimed, vec![t.id.clone()]);
9374 let after = queue.get(&t.id).unwrap();
9375 assert_eq!(
9376 after.status,
9377 TaskStatus::Held,
9378 "no run.json to recover from, so a human is asked"
9379 );
9380 assert_eq!(
9381 after.runs,
9382 vec!["20260904-000000-4043".to_owned()],
9383 "the crashed run's id is kept as evidence, not discarded"
9384 );
9385 }
9386
9387 #[test]
9388 fn a_lock_is_kept_when_the_process_query_is_unavailable() {
9389 let dir = tempfile::tempdir().unwrap();
9390 let queue = Queue::at(dir.path().to_path_buf());
9391 let mut t = task();
9392 t.id = "20260101-000000-unknown".to_owned();
9393 queue.put(&mut t).unwrap();
9394 let dead_pid = injected_dead_pid();
9395 std::fs::write(
9396 dir.path().join(format!("{}.lock", t.id)),
9397 dead_pid.to_string(),
9398 )
9399 .unwrap();
9400
9401 let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
9402 assert!(swept.is_empty(), "an unknown pid must keep its lock");
9403 assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
9404 }
9405
9406 fn run_state_in(status: RunStatus, language: &str) -> RunState {
9407 let mut s = run_state(status);
9408 s.config.graph.language = language.to_owned();
9409 s
9410 }
9411
9412 fn unstarted_verdict(status: RunStatus) -> Verdict {
9413 Verdict {
9414 status,
9415 left_pr: false,
9416 quota_hit: false,
9417 parked: false,
9418 no_viable_candidates: false,
9419 }
9420 }
9421
9422 #[test]
9423 fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
9424 let mut t = task();
9425 t.attempts = 1;
9426 settle_in(
9427 &mut t,
9428 unstarted_verdict(RunStatus::AlreadyInBase),
9429 "already in main",
9430 1,
9431 phrases("en"),
9432 None,
9433 );
9434 assert_eq!(t.status, TaskStatus::Done);
9435 assert_eq!(t.attempts, 0);
9436 }
9437
9438 #[test]
9439 fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
9440 let reason = |language: &str| {
9441 let mut t = task();
9442 settle_in(
9443 &mut t,
9444 unstarted_verdict(RunStatus::Judging),
9445 "boom",
9446 1,
9447 phrases(language),
9448 None,
9449 );
9450 t.last_error.or(t.hold_reason).unwrap_or_default()
9451 };
9452 assert!(
9453 reason("en").starts_with("the graph stopped at `"),
9454 "{}",
9455 reason("en")
9456 );
9457 assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
9458 assert!(reason("日本語").contains("boom"));
9459 assert_eq!(reason("fr"), reason("en"));
9460 }
9461
9462 #[test]
9463 fn describe_follows_the_run_language_and_keeps_the_run_id() {
9464 let en = describe(&run_state_in(RunStatus::Stalled, "en"));
9465 assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
9466 let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
9467 assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
9468 assert!(ja.contains("[run "), "{ja}");
9469 let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
9470 assert!(ended.starts_with("run 終了: "), "{ended}");
9471 let mut de = run_state_in(RunStatus::Failed, "de");
9472 let mut en = run_state_in(RunStatus::Failed, "en");
9473 de.id = "same".to_owned();
9474 en.id = "same".to_owned();
9475 assert_eq!(describe(&de), describe(&en));
9476 }
9477
9478 #[test]
9479 fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
9480 use crate::handover::Refused;
9481 let cases = [
9482 Refused::Foreign {
9483 branch: "b".into(),
9484 path: "/w/x".into(),
9485 why: "made by hand".into(),
9486 },
9487 Refused::Unsafe {
9488 branch: "b".into(),
9489 path: "/w/x".into(),
9490 why: "its worktree has uncommitted changes (a.rs)".into(),
9491 },
9492 Refused::ReleaseFailed {
9493 branch: "b".into(),
9494 path: "/w/x".into(),
9495 run: "ab12".into(),
9496 },
9497 ];
9498 for r in &cases {
9499 let en = (phrases("en").handover_refused)(r);
9500 assert_eq!(en, r.to_string());
9501 let ja = (phrases("ja").handover_refused)(r);
9502 assert!(
9503 !ja.contains("is checked out") && !ja.contains("try again"),
9504 "{ja}"
9505 );
9506 assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
9507 if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
9508 assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
9509 }
9510 }
9511 assert!(phrases("en").handover_hint.contains("release the task"));
9512 assert!(phrases("ja").handover_hint.contains("解放"));
9513 }
9514
9515 #[test]
9516 fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
9517 let build = |lang: &str| {
9518 let mut s = run_state_in(RunStatus::Blocked, lang);
9519 s.id = "same".to_owned();
9520 s.config.graph.review_rounds = 3;
9521 let mut r = review_round(3);
9522 r.expected = 3;
9523 r.answered = 1;
9524 s.reviews.push(r);
9525 s.event(
9526 "review",
9527 "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
9528 );
9529 s
9530 };
9531 let en = describe(&build("en"));
9532 assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
9533 let ja = describe(&build("ja"));
9534 assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
9535 assert!(!ja.contains("never answered"), "{ja}");
9536 assert!(ja.contains("[run "), "{ja}");
9537
9538 let mut failed = build("ja");
9541 failed.reviews[0].e2e.push(crate::run::CommandOutcome {
9542 command: "cargo test".to_owned(),
9543 code: Some(1),
9544 output_tail: String::new(),
9545 duration_ms: 0,
9546 resource_blocked: false,
9547 ..Default::default()
9548 });
9549 failed.event("review", "stopped; e2e failed: cargo test");
9550 let ja = describe(&failed);
9551 assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
9552 assert!(!ja.contains("席のレビュアー"), "{ja}");
9553 }
9554
9555 #[test]
9556 fn refusals_and_recovery_prose_follow_the_language() {
9557 let home = crate::run::test_home();
9558 let t = held_task_with("r1");
9559 let q = action_question(
9560 "r1",
9561 ask::ChoiceAction::Resume {
9562 run: "r1".to_owned(),
9563 },
9564 );
9565 let refuse = |p: &Phrases| match decide_action(&home, &t, &q, p, |_: &str| bail!("gone")) {
9566 ActionDecision::Refuse(s) => s,
9567 other => panic!("{other:?}"),
9568 };
9569 assert!(refuse(phrases("en")).contains("could not be read: gone"));
9570 assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
9571 assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
9572
9573 let mut held = task();
9574 reclaim(&mut held, None, 2, "ja");
9575 assert!(held.hold_reason.unwrap().contains("保留にしました"));
9576 let mut held = task();
9577 reclaim(&mut held, None, 2, "xx");
9578 assert!(held.hold_reason.unwrap().contains("held for a human"));
9579 }
9580
9581 fn run_state(status: RunStatus) -> RunState {
9582 let mut state = RunState::new(
9583 PathBuf::from("/repo"),
9584 "main".to_owned(),
9585 "abc1234def".to_owned(),
9586 "add retries".to_owned(),
9587 Config::default(),
9588 );
9589 state.status = status;
9590 state
9591 }
9592
9593 #[test]
9594 fn settlement_audits_the_loaded_run_instead_of_reloading_a_stale_snapshot() {
9595 crate::run::pin_test_home();
9596 let dir = tempfile::tempdir().unwrap();
9597 let mut state = run_state(RunStatus::Blocked);
9598 state.id = "20260101-000000-audit".into();
9599 state.save_under(dir.path()).unwrap();
9600 let mut t = task();
9601 t.start(state.id.clone());
9602 state.status = RunStatus::Ready;
9605 settle_and_diagnose(
9606 &mut t,
9607 unstarted_verdict(RunStatus::Ready),
9608 "Verified local delivery",
9609 2,
9610 &state,
9611 );
9612 let completion = t.completion_history.last().unwrap();
9613 assert_eq!(completion.actor, CompletionActor::DaemonSettle);
9614 assert_eq!(completion.prior_status, TaskStatus::Running);
9615 assert_eq!(
9616 completion.reason.as_deref(),
9617 Some("Verified local delivery")
9618 );
9619 let snapshot = completion.run.as_ref().unwrap();
9620 assert_eq!(snapshot.id, state.id);
9621 assert_eq!(snapshot.status, Some(RunStatus::Ready));
9622 assert_eq!(
9623 RunState::load_under(&state.id, dir.path()).unwrap().status,
9624 RunStatus::Blocked,
9625 "settlement records the actual outcome without rewriting run history"
9626 );
9627 }
9628
9629 fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
9630 Candidate {
9631 index: 0,
9632 label,
9633 agent: "claude".to_owned(),
9634 branch: format!("magi/x/{label}"),
9635 worktree: PathBuf::from("/repo"),
9636 summary: summary.to_owned(),
9637 stat: String::new(),
9638 files: 0,
9639 commits: usize::from(!empty),
9640 empty,
9641 failed: failed.map(str::to_owned),
9642 verified_noop: None,
9643 duration_ms: 0,
9644 folded: false,
9645 }
9646 }
9647
9648 #[test]
9649 fn diagnostic_names_the_failing_gate_checks_and_their_output() {
9650 let mut state = run_state(RunStatus::Blocked);
9651 state.gate = vec![
9652 CommandOutcome {
9653 command: "cargo make check".to_owned(),
9654 code: Some(0),
9655 output_tail: "ok".to_owned(),
9656 duration_ms: 0,
9657 resource_blocked: false,
9658 ..Default::default()
9659 },
9660 CommandOutcome {
9661 command: "cargo test".to_owned(),
9662 code: Some(101),
9663 output_tail: "thread 'x' panicked: assertion failed".to_owned(),
9664 duration_ms: 0,
9665 resource_blocked: false,
9666 ..Default::default()
9667 },
9668 ];
9669 let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
9670 assert!(d.contains("cargo test"), "{d}");
9671 assert!(
9672 !d.contains("cargo make check"),
9673 "a passing check is not a diagnostic: {d}"
9674 );
9675 assert!(d.contains("assertion failed"), "{d}");
9676 }
9677
9678 #[test]
9679 fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
9680 let mut state = run_state(RunStatus::Blocked);
9681 state.event(
9682 "land",
9683 "stopped: the fixer produced no commit while 2 check(s) were failing \
9684 (build, lint); stopping instead of looping on an unchanged tree",
9685 );
9686 let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
9687 assert!(d.contains("build"), "{d}");
9688 assert!(d.contains("lint"), "{d}");
9689 assert!(d.contains("fixer produced no commit"), "{d}");
9690 }
9691
9692 #[test]
9693 fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
9694 let state = run_state(RunStatus::VerifiedNoop);
9699 let d = describe(&state);
9700 assert!(
9701 d.contains("agent-verified no-op"),
9702 "expected the display label, not the wire spelling: {d}"
9703 );
9704 assert!(!d.contains("verified_noop"), "{d}");
9705 }
9706
9707 #[test]
9708 fn diagnostic_keeps_gate_panic_before_large_backtrace() {
9709 let mut state = run_state(RunStatus::Failed);
9710 state.gate.push(crate::run::CommandOutcome {
9711 command: "cargo test".into(),
9712 code: Some(101),
9713 output_tail: format!(
9714 "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
9715 " 41: 0x1234 - backtrace frame\n".repeat(10000)
9716 ),
9717 duration_ms: 1,
9718 resource_blocked: false,
9719 ..Default::default()
9720 });
9721 let d = diagnostic(&state).unwrap();
9722 assert!(d.contains("panicked at widget.rs:12"), "{d}");
9723 assert!(d.contains("assertion failed: widget missing"));
9724 assert!(d.contains("widget log"));
9725 }
9726
9727 #[test]
9728 fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
9729 let mut state = run_state(RunStatus::Failed);
9735 state.candidates = vec![candidate(
9736 'A',
9737 "opened pull request #42, merged it, tagged v1.2.3 and published the release",
9738 true,
9739 None,
9740 )];
9741 let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
9742 assert!(d.contains("candidate A"), "{d}");
9743 assert!(d.contains("tagged v1.2.3"), "{d}");
9744 }
9745
9746 #[test]
9747 fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
9748 let mut state = run_state(RunStatus::Failed);
9749 state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
9750 let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
9751 assert!(d.contains("candidate A"), "{d}");
9752 assert!(d.contains("agent timed out"), "{d}");
9753 }
9754
9755 #[test]
9756 fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
9757 let mut state = run_state(RunStatus::Failed);
9760 state.candidates = vec![candidate('A', "did the work", false, None)];
9761 assert!(diagnostic(&state).is_none());
9762 }
9763
9764 #[test]
9765 fn diagnostic_is_bounded_however_much_a_run_printed() {
9766 let mut state = run_state(RunStatus::Blocked);
9767 state.gate = vec![
9768 CommandOutcome {
9769 command: "cargo test".to_owned(),
9770 code: Some(101),
9771 output_tail: "x".repeat(50_000),
9772 duration_ms: 0,
9773 resource_blocked: false,
9774 ..Default::default()
9775 },
9776 CommandOutcome {
9777 command: "cargo clippy".to_owned(),
9778 code: Some(1),
9779 output_tail: "y".repeat(50_000),
9780 duration_ms: 0,
9781 resource_blocked: false,
9782 ..Default::default()
9783 },
9784 ];
9785 state.candidates = vec![
9786 candidate('A', &"z".repeat(50_000), true, None),
9787 candidate('B', &"w".repeat(50_000), true, None),
9788 ];
9789 let d = diagnostic(&state).expect("plenty here to diagnose");
9790 assert!(
9791 d.len() <= DIAGNOSTIC_MAX,
9792 "diagnostic grew to {} bytes, unbounded",
9793 d.len()
9794 );
9795 }
9796
9797 #[test]
9798 fn selected_delivery_guards_survive_recovery_failure_accounting() {
9799 for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
9800 let mut t = task();
9801 let mut state = run_state(status);
9802 t.pr_recovery = Some(crate::pr_recovery::Selection {
9803 url: "url".into(),
9804 branch: format!("magi/task-{}", t.id),
9805 head: "a".repeat(40),
9806 source_head: None,
9807 source_run: None,
9808 source_proof: None,
9809 disposition: Some(crate::pr_recovery::Disposition::Land),
9810 instruction: t.instruction.clone(),
9811 approved_at: Timestamp::now(),
9812 });
9813 state.pr_recovery = t.pr_recovery.clone();
9814 t.start(state.id.clone());
9815 settle_and_diagnose(
9816 &mut t,
9817 Verdict {
9818 status,
9819 left_pr: false,
9820 quota_hit: false,
9821 parked: false,
9822 no_viable_candidates: false,
9823 },
9824 "delivery stopped",
9825 5,
9826 &state,
9827 );
9828 assert_eq!(t.status, TaskStatus::Held);
9829 let reason = t.hold_reason.as_deref().unwrap();
9830 if status == RunStatus::Ready {
9831 assert!(reason.contains("Selected PR delivery is incomplete"));
9832 assert!(t.recovery_budget.is_none());
9833 } else {
9834 assert!(reason.contains("Selected recovery stopped"));
9835 assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
9836 }
9837 assert!(t.pr_recovery.is_some());
9838 }
9839 }
9840
9841 #[test]
9842 fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
9843 let mut state = run_state(RunStatus::Voting);
9844 state.base_sync = Some(crate::run::BaseSync {
9845 tip: "base-tip".into(),
9846 behind: 3,
9847 attempts: 4,
9848 conflict: Some("base stopped".into()),
9849 already_in: None,
9850 });
9851 state.record_base_sync_stop("candidate-head");
9852 let mut t = task();
9853 t.start(state.id.clone());
9854 let verdict = Verdict {
9855 status: RunStatus::Blocked,
9856 left_pr: false,
9857 quota_hit: false,
9858 parked: false,
9859 no_viable_candidates: false,
9860 };
9861 settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
9862 assert_eq!(
9863 t.status,
9864 TaskStatus::Held,
9865 "unspent task attempts cannot start another competition"
9866 );
9867 let at = t.held_at;
9868 let cause = t.hold_notice_cause.clone();
9869 state.begin_pass();
9870 t.release_operator("test-resume", None);
9871 t.start(state.id.clone());
9872 settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
9873 assert_eq!(t.status, TaskStatus::Held);
9874 assert_eq!(t.held_at, at);
9875 assert_eq!(t.hold_notice_cause, cause);
9876 }
9877
9878 #[test]
9879 fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
9880 let mut state = run_state(RunStatus::Blocked);
9881 state.gate = vec![CommandOutcome {
9882 command: "cargo test".to_owned(),
9883 code: Some(101),
9884 output_tail: "assertion failed".to_owned(),
9885 duration_ms: 0,
9886 resource_blocked: false,
9887 ..Default::default()
9888 }];
9889 let verdict = Verdict {
9890 status: RunStatus::Blocked,
9891 left_pr: false,
9892 quota_hit: false,
9893 parked: false,
9894 no_viable_candidates: false,
9895 };
9896
9897 let mut t = task();
9900 t.start("run-1".to_owned());
9901 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
9902 assert_eq!(t.status, TaskStatus::Failed);
9903 assert!(t.diagnostic.is_none());
9904
9905 t.start("run-2".to_owned());
9908 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
9909 assert_eq!(t.status, TaskStatus::Held);
9910 let d = t.diagnostic.expect("a held task must carry its diagnostic");
9911 assert!(d.contains("cargo test"), "{d}");
9912 }
9913
9914 fn verified_noop_run_state() -> RunState {
9915 let mut state = run_state(RunStatus::VerifiedNoop);
9916 let summary = r#"NO CHANGE NEEDED: {"status":"already_satisfied","requirements":[{"requirement":"requested fix already landed","satisfied":true,"evidence":["c1"]}],"checks":[{"id":"c1","kind":"commit","target":"b32cfc4","method":"git merge-base --is-ancestor b32cfc4 HEAD","observed":"exit 0; b32cfc4 is on main","passed":true}],"unresolved":[]}"#;
9917 let mut c = candidate('A', summary, true, None);
9918 c.verified_noop = Some(summary.to_owned());
9919 state.candidates = vec![c];
9920 state
9921 }
9922
9923 #[test]
9924 fn a_held_task_names_the_open_question_it_is_waiting_on() {
9925 crate::run::pin_test_home();
9930 let home = crate::run::home();
9931 let state = verified_noop_run_state();
9932 let mut q = ask::Question::new(
9933 state.id.clone(),
9934 "implement".to_owned(),
9935 "impl-A".to_owned(),
9936 "is this really a no-op?".to_owned(),
9937 String::new(),
9938 Vec::new(),
9939 );
9940 Questions::at(home.join("questions")).put(&mut q).unwrap();
9941
9942 let verdict = Verdict {
9943 status: RunStatus::VerifiedNoop,
9944 left_pr: false,
9945 quota_hit: false,
9946 parked: false,
9947 no_viable_candidates: true,
9948 };
9949 let mut t = task();
9950 t.start(state.id.clone());
9951 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
9952
9953 assert_eq!(t.status, TaskStatus::Held);
9954 let reason = t.hold_reason.expect("a held task must record why");
9955 assert!(
9956 reason.starts_with("run ended agent-verified no-op"),
9957 "the original settle reason must survive unchanged: {reason}"
9958 );
9959 assert!(
9960 reason.contains(q.short()),
9961 "the open question's id must be named so the notice is actionable: {reason}"
9962 );
9963 }
9964
9965 #[test]
9966 fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
9967 crate::run::pin_test_home();
9968 let state = verified_noop_run_state();
9969
9970 let verdict = Verdict {
9971 status: RunStatus::VerifiedNoop,
9972 left_pr: false,
9973 quota_hit: false,
9974 parked: false,
9975 no_viable_candidates: true,
9976 };
9977 let mut t = task();
9978 t.start(state.id.clone());
9979 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
9980
9981 assert_eq!(t.status, TaskStatus::Held);
9982 assert_eq!(
9983 t.hold_reason.as_deref(),
9984 Some("run ended agent-verified no-op"),
9985 "nothing to append when the question was already answered or never asked"
9986 );
9987 }
9988
9989 #[test]
9990 fn inconsistent_verified_noop_state_settles_and_reclaims_as_ordinary_failure() {
9991 crate::run::pin_test_home();
9992
9993 let mut bad = run_state(RunStatus::VerifiedNoop);
9996 let mut c = candidate(
9997 'A',
9998 "NO CHANGE NEEDED: Not established. No source changes, commit, or reproduction checks were completed. The reported Git configuration lock contention remains unresolved.",
9999 true,
10000 None,
10001 );
10002 c.verified_noop = Some("Not established.".to_owned());
10003 bad.candidates = vec![c];
10004
10005 let mut t = task();
10006 t.start(bad.id.clone());
10007 let verdict = Verdict {
10008 status: RunStatus::VerifiedNoop,
10009 left_pr: false,
10010 quota_hit: true,
10011 parked: false,
10012 no_viable_candidates: true,
10013 };
10014 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 3, &bad);
10015 assert_eq!(
10016 t.status,
10017 TaskStatus::Failed,
10018 "inconsistent verified_noop must retry as Failed when attempts remain"
10019 );
10020 assert_eq!(t.attempts, 1);
10021 assert_eq!(
10022 t.last_error.as_deref(),
10023 Some("no-change result lacks verified evidence")
10024 );
10025 assert!(t.hold_reason.is_none());
10026
10027 let mut t_exhausted = task();
10031 t_exhausted.start(bad.id.clone());
10032 reclaim(&mut t_exhausted, Some(bad.clone()), 1, "en");
10033 assert_eq!(t_exhausted.status, TaskStatus::Held);
10034 assert_eq!(t_exhausted.attempts, 1);
10035 assert_eq!(
10036 t_exhausted
10037 .hold_notice_cause
10038 .as_ref()
10039 .map(|c| c.stage.as_str()),
10040 Some("failed"),
10041 "exhausted inconsistent verified_noop must not emit a verified_noop notice cause"
10042 );
10043 let diag = t_exhausted.diagnostic.as_deref().unwrap_or("");
10044 assert!(
10045 !diag.contains("agent-verified no-op"),
10046 "diagnostic must not mislabel an invalid claim as verified no-op: {diag}"
10047 );
10048 assert!(diag.contains("Not established"), "{diag}");
10049 }
10050
10051 #[test]
10052 fn saved_noop_declaration_is_the_evidence_not_the_display_summary() {
10053 let mut state = verified_noop_run_state();
10054 let summary = state.candidates[0].summary.clone();
10055 state.candidates[0].summary = "Already satisfied.".to_owned();
10056 assert!(state.all_candidates_verified_noop());
10057
10058 state.candidates[0].summary = summary;
10059 state.candidates[0].verified_noop = Some("Historical prose only.".to_owned());
10060 assert!(!state.all_candidates_verified_noop());
10061 }
10062
10063 #[test]
10064 fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
10065 crate::run::pin_test_home();
10066 let mut first = run_state(RunStatus::Blocked);
10067 first.id = "20260101-000000-sup1".to_owned();
10068 first.save().unwrap();
10069 let mut second = run_state(RunStatus::Merged);
10070 second.id = "20260101-000000-sup2".to_owned();
10071 second.save().unwrap();
10072
10073 let mut t = task();
10074 t.runs = vec![first.id.clone(), second.id.clone()];
10075 t.status = TaskStatus::Done;
10076
10077 supersede_prior_runs(&t, &crate::run::home());
10078
10079 assert_eq!(
10080 RunState::load(&first.id).unwrap().status,
10081 RunStatus::Superseded,
10082 "the first attempt's Blocked no longer needs anyone's attention"
10083 );
10084 assert_eq!(
10085 RunState::load(&second.id).unwrap().status,
10086 RunStatus::Merged,
10087 "the run that actually succeeded is left exactly as it was"
10088 );
10089 }
10090
10091 #[test]
10092 fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
10093 crate::run::pin_test_home();
10099 let mut first = run_state(RunStatus::Blocked);
10100 first.id = "20260101-000000-sup9".to_owned();
10101 first.driver_pid = Some(std::process::id());
10104 first.driver_started_at = Some(
10105 crate::proc::process_started_at(std::process::id())
10106 .expect("this test process's own start time must be queryable"),
10107 );
10108 first.save().unwrap();
10109 let mut second = run_state(RunStatus::Merged);
10110 second.id = "20260101-000000-supa".to_owned();
10111 second.save().unwrap();
10112
10113 let mut t = task();
10114 t.runs = vec![first.id.clone(), second.id.clone()];
10115 t.status = TaskStatus::Done;
10116
10117 supersede_prior_runs(&t, &crate::run::home());
10118
10119 assert_eq!(
10120 RunState::load(&first.id).unwrap().status,
10121 RunStatus::Blocked,
10122 "a live driver_pid means something is still actually working this run, \
10123 even though no daemon claims it - rewriting under it would just be \
10124 undone the next time that process saves"
10125 );
10126 }
10127
10128 #[test]
10129 fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
10130 let dir = tempfile::tempdir().unwrap();
10136 let home = dir.path().to_path_buf();
10137 let queue = Queue::at(dir.path().join("queue"));
10138
10139 let mut first = run_state(RunStatus::Blocked);
10140 first.id = "20260101-000000-supd".to_owned();
10141 first.driver_pid = Some(std::process::id());
10142 first.driver_started_at = Some(
10143 crate::proc::process_started_at(std::process::id())
10144 .expect("this test process's own start time must be queryable"),
10145 );
10146 first.save_under(&home).unwrap();
10147 let mut second = run_state(RunStatus::Merged);
10148 second.id = "20260101-000000-supe".to_owned();
10149 second.save_under(&home).unwrap();
10150
10151 let mut t = task();
10152 t.runs = vec![first.id.clone(), second.id.clone()];
10153 t.status = TaskStatus::Done;
10154 queue.put(&mut t).unwrap();
10155
10156 resweep_superseded_attempts(&queue, &home);
10157 assert_eq!(
10158 RunState::load_under(&first.id, &home).unwrap().status,
10159 RunStatus::Blocked,
10160 "still live on the first pass, so still untouched"
10161 );
10162
10163 let mut stale = RunState::load_under(&first.id, &home).unwrap();
10169 stale.driver_started_at = Some("1".to_owned());
10170 stale.save_under(&home).unwrap();
10171
10172 resweep_superseded_attempts(&queue, &home);
10173 assert_eq!(
10174 RunState::load_under(&first.id, &home).unwrap().status,
10175 RunStatus::Superseded,
10176 "the second pass catches up what the first one correctly skipped"
10177 );
10178 }
10179
10180 #[test]
10181 fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
10182 crate::run::pin_test_home();
10183 let mut first = run_state(RunStatus::Blocked);
10184 first.id = "20260101-000000-sup3".to_owned();
10185 first.save().unwrap();
10186 let mut second = run_state(RunStatus::Blocked);
10187 second.id = "20260101-000000-sup4".to_owned();
10188 second.save().unwrap();
10189
10190 let mut t = task();
10191 t.runs = vec![first.id.clone(), second.id.clone()];
10192 t.status = TaskStatus::Failed;
10196
10197 supersede_prior_runs(&t, &crate::run::home());
10198
10199 assert_eq!(
10200 RunState::load(&first.id).unwrap().status,
10201 RunStatus::Blocked
10202 );
10203 assert_eq!(
10204 RunState::load(&second.id).unwrap().status,
10205 RunStatus::Blocked
10206 );
10207 }
10208
10209 #[test]
10210 fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
10211 crate::run::pin_test_home();
10215 let mut first = run_state(RunStatus::Blocked);
10216 first.id = "20260101-000000-sup5".to_owned();
10217 first.save().unwrap();
10218
10219 let mut t = task();
10220 t.runs = vec![first.id.clone()];
10221 t.status = TaskStatus::Done;
10222
10223 supersede_prior_runs(&t, &crate::run::home());
10224
10225 assert_eq!(
10226 RunState::load(&first.id).unwrap().status,
10227 RunStatus::Blocked,
10228 "a single-attempt task has no earlier run to supersede"
10229 );
10230 }
10231
10232 #[test]
10233 fn supersede_prior_runs_preserves_blocked_work_after_an_audited_manual_close() {
10234 for status in [
10235 RunStatus::Blocked,
10236 RunStatus::Stalled,
10237 RunStatus::Failed,
10238 RunStatus::Ready,
10239 RunStatus::Merged,
10240 ] {
10241 let dir = tempfile::tempdir().unwrap();
10242 let home = dir.path();
10243 let mut first = run_state(RunStatus::Blocked);
10244 first.id = "20260101-000000-supb".to_owned();
10245 first.save_under(home).unwrap();
10246 let mut second = run_state(status);
10247 second.id = "20260101-000000-supc".to_owned();
10248 second.save_under(home).unwrap();
10249
10250 let mut t = task();
10251 t.runs = vec![first.id.clone(), second.id.clone()];
10252 t.hold_manual(Some("Unmerged work remains".into()));
10253 let mut context = CompletionContext::new(
10254 CompletionActor::Cli,
10255 Some("Discard the unmerged attempts".into()),
10256 home,
10257 &t,
10258 );
10259 context.discard = true;
10260 t.succeed(context);
10261 assert_eq!(t.completion_history.len(), 1);
10262
10263 supersede_prior_runs(&t, home);
10264
10265 assert_eq!(
10266 RunState::load_under(&first.id, home).unwrap().status,
10267 RunStatus::Blocked,
10268 "an audited manual close is not proof the earlier work landed"
10269 );
10270 assert_eq!(
10271 RunState::load_under(&second.id, home).unwrap().status,
10272 status,
10273 "the latest attempt retains its actual outcome"
10274 );
10275 }
10276 }
10277
10278 #[test]
10279 fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
10280 crate::run::pin_test_home();
10284 let mut failed = run_state(RunStatus::Failed);
10285 failed.id = "20260101-000000-sup6".to_owned();
10286 failed.save().unwrap();
10287 let mut noop = run_state(RunStatus::VerifiedNoop);
10288 noop.id = "20260101-000000-sup7".to_owned();
10289 noop.save().unwrap();
10290 let mut winner = run_state(RunStatus::Ready);
10291 winner.id = "20260101-000000-sup8".to_owned();
10292 winner.save().unwrap();
10293
10294 let mut t = task();
10295 t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
10296 t.status = TaskStatus::Done;
10297
10298 supersede_prior_runs(&t, &crate::run::home());
10299
10300 assert_eq!(
10301 RunState::load(&failed.id).unwrap().status,
10302 RunStatus::Failed
10303 );
10304 assert_eq!(
10305 RunState::load(&noop.id).unwrap().status,
10306 RunStatus::VerifiedNoop
10307 );
10308 }
10309
10310 fn approval_question(run: &str) -> ask::Question {
10311 ask::Question::new(
10312 run.to_owned(),
10313 land::APPROVAL_NODE.to_owned(),
10314 "land".to_owned(),
10315 "merge?".to_owned(),
10316 String::new(),
10317 vec!["merge".to_owned(), "hold".to_owned()],
10318 )
10319 }
10320
10321 #[test]
10322 fn land_resume_state_leaves_a_fresh_open_question_waiting() {
10323 crate::run::pin_test_home();
10324 let mut state = run_state(RunStatus::Landing);
10325 state.id = "20260101-000000-fre1".to_owned();
10326 state.parked = true;
10327 state.save().unwrap();
10328 ask::Questions::open()
10329 .put(&mut approval_question(&state.id))
10330 .unwrap();
10331
10332 let mut t = task();
10333 t.runs.push(state.id.clone());
10334 assert_eq!(
10335 land_resume_state(&t),
10336 LandResume::StillWaiting,
10337 "nobody has answered and the timeout has not passed"
10338 );
10339 }
10340
10341 #[test]
10342 fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
10343 crate::run::pin_test_home();
10344 let mut state = run_state(RunStatus::Gating);
10345 state.id = "20260101-000000-gt01".to_owned();
10346 state.parked = true;
10347 state.config.graph.answer_timeout = 60;
10348 state.github_text = Some(crate::run::GithubTextAsk {
10349 rewrite: None,
10350 fingerprint: "f".into(),
10351 title: true,
10352 body: false,
10353 categories: vec!["title-language".into()],
10354 question: None,
10355 asks: 1,
10356 resolved: false,
10357 chosen_title: None,
10358 choice: None,
10359 publication: None,
10360 });
10361 state.save().unwrap();
10362 let store = ask::Questions::open();
10363 let mut q = ask::Question::new(
10364 state.id.clone(),
10365 crate::github_text::ASK_NODE.to_owned(),
10366 crate::github_text::ASK_SEAT.to_owned(),
10367 "s".into(),
10368 String::new(),
10369 vec!["use fallback".into()],
10370 );
10371 store.put(&mut q).unwrap();
10372 let mut t = task();
10373 t.runs.push(state.id.clone());
10374 assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
10375 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
10376 store.put(&mut q).unwrap();
10377 assert_eq!(land_resume_state(&t), LandResume::Ready);
10378 assert!(!store.get(&q.id).unwrap().status.open());
10379 state.github_text.as_mut().unwrap().resolved = true;
10381 state.save().unwrap();
10382 assert_eq!(land_resume_state(&t), LandResume::NotLanding);
10383 }
10384
10385 #[test]
10386 fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
10387 crate::run::pin_test_home();
10392 let mut state = run_state(RunStatus::Landing);
10393 state.id = "20260101-000000-exp1".to_owned();
10394 state.parked = true;
10395 state.config.graph.answer_timeout = 60;
10396 state.save().unwrap();
10397
10398 let store = ask::Questions::open();
10399 let mut q = approval_question(&state.id);
10400 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
10401 store.put(&mut q).unwrap();
10402
10403 let mut t = task();
10404 t.runs.push(state.id.clone());
10405 assert_eq!(
10406 land_resume_state(&t),
10407 LandResume::Ready,
10408 "an expired question must not be waited on forever"
10409 );
10410
10411 let after = store.get(&q.id).unwrap();
10412 assert!(
10413 !after.status.open(),
10414 "the question is abandoned, not silently ignored"
10415 );
10416 assert!(
10417 after.resolution().is_none(),
10418 "an abandoned question is not read as a decision"
10419 );
10420 }
10421
10422 #[test]
10423 fn reclaim_settles_a_running_task_against_its_last_run() {
10424 let mut t = task();
10425 t.start("20260904-000000-4043".to_owned());
10426 reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
10427 assert_eq!(
10428 t.status,
10429 TaskStatus::Done,
10430 "a run that actually finished must not stay `running` forever"
10431 );
10432 }
10433
10434 #[test]
10435 fn reclaim_preserves_dispatched_inquiries_until_a_committed_pass() {
10436 let dir = tempfile::tempdir().unwrap();
10437 let queue = Queue::at(dir.path().join("queue"));
10438 let mut task = task();
10439 let mut run = run_state(RunStatus::Blocked);
10440 run.reserve_under(dir.path()).unwrap();
10441 run.driver_exited = true;
10442 run.save_under(dir.path()).unwrap();
10443 queue.put(&mut task).unwrap();
10444 let stale = task.clone();
10445 task.resume_override = Some(crate::queue::OperatorResume {
10446 question_id: "pending-resume".into(),
10447 at: Timestamp::now(),
10448 conductor_rehold: None,
10449 forced: true,
10450 pinned_run: Some(run.id.clone()),
10451 });
10452 task.start(run.id.clone());
10453 queue.put(&mut task).unwrap();
10454 let mut recovered = queue.get(&task.id).unwrap();
10456 let disk = RunState::load_under(&run.id, dir.path()).unwrap();
10457 reclaim(&mut recovered, Some(disk), 2, "en");
10458 queue.put(&mut recovered).unwrap();
10459 assert!(recovered.resume_override.is_none());
10460 assert_eq!(
10461 recovered.dispatched_resumes.get("pending-resume"),
10462 Some(&run.id)
10463 );
10464 let mut stale = stale;
10465 queue.put(&mut stale).unwrap();
10466 assert_eq!(
10467 stale.dispatched_resumes, recovered.dispatched_resumes,
10468 "a stale task writer cannot erase dispatch ownership"
10469 );
10470 let mut resumed = RunState::load_under(&run.id, dir.path()).unwrap();
10471 assert!(resumed.decision_starts.is_empty());
10472 resumed.carry_dispatched_resumes(&queue.get(&task.id).unwrap());
10473 assert!(
10474 resumed.decision_starts.is_empty(),
10475 "handoff is not execution proof"
10476 );
10477 resumed.begin_pass();
10478 resumed.save_under(dir.path()).unwrap();
10479 let mut disk = RunState::load_under(&run.id, dir.path()).unwrap();
10480 assert_eq!(disk.decision_starts.get("pending-resume"), Some(&0));
10481 disk.carry_dispatched_resumes(&recovered);
10482 disk.begin_pass();
10483 assert_eq!(
10484 disk.decision_starts.get("pending-resume"),
10485 Some(&0),
10486 "later execution must preserve the original pass receipt"
10487 );
10488 }
10489
10490 #[test]
10491 fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
10492 let mut t = task();
10493 t.start("20260904-000000-4043".to_owned());
10494 t.last_error = Some("earlier trouble".to_owned());
10495 let mut state = run_state(RunStatus::Judging);
10496 state.parked = true;
10497 reclaim(&mut t, Some(state), 1, "en");
10498 assert_eq!(t.status, TaskStatus::Parked);
10499 assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
10500 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
10501 assert!(t.park_reason.is_some());
10502 assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
10503 assert!(!t.fresh_start);
10504 assert!(t.status.runnable());
10505 }
10506
10507 #[test]
10508 fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
10509 let mut t = task();
10510 t.start("20260904-000000-4043".to_owned());
10511 t.last_error = Some("earlier trouble".to_owned());
10512 settle(
10513 &mut t,
10514 Verdict {
10515 status: RunStatus::Judging,
10516 left_pr: false,
10517 quota_hit: false,
10518 parked: true,
10519 no_viable_candidates: false,
10520 },
10521 "parked after `judging`",
10522 1,
10523 );
10524 assert_eq!(t.status, TaskStatus::Parked);
10525 assert_eq!(t.attempts, 0);
10526 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
10527 assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
10528 assert_eq!(t.schema, crate::queue::SCHEMA);
10529 assert!(
10530 crate::notices::task_held(&t).is_none(),
10531 "a park is not news"
10532 );
10533 t.start("20260904-000000-4043".to_owned());
10534 assert_eq!(t.park_reason, None);
10535 }
10536
10537 #[test]
10538 fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
10539 let mut t = task();
10543 t.start("20260904-000000-4043".to_owned());
10544 reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
10545 assert_eq!(t.status, TaskStatus::Failed);
10546 assert!(t.status.runnable());
10547 }
10548
10549 #[test]
10550 fn a_settled_parked_pass_records_its_cause_and_the_refund() {
10551 let mut t = task();
10552 t.start("20260904-000000-4043".to_owned());
10553 assert_eq!(t.attempts, 1);
10554 let mut run = run_state(RunStatus::Implementing);
10555 run.id = "20260904-000000-4043".to_owned();
10556 run.begin_pass();
10557 let cause = crate::run::ParkCause::Upgrade {
10558 from: "0.121.0".to_owned(),
10559 to: Some("0.121.1".to_owned()),
10560 };
10561 run.end_pass_parked(cause.clone());
10562 run.parked = true;
10563 let verdict = Verdict {
10564 status: run.status,
10565 left_pr: false,
10566 quota_hit: false,
10567 parked: true,
10568 no_viable_candidates: false,
10569 };
10570 let mut orphan = t.clone();
10573 reclaim(&mut orphan, Some(run.clone()), 2, "en");
10574 assert_eq!(orphan.status, TaskStatus::Parked);
10575 assert_eq!(orphan.attempts, 0);
10576 assert_eq!(
10577 orphan.upgrade_resume_key(),
10578 Some((run.passes[0].started_at, orphan.id.as_str()))
10579 );
10580 settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
10581 assert_eq!(t.attempts, 0);
10582 assert_eq!(t.passes.len(), 1);
10583 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
10584 assert_eq!(t.passes[0].parked, Some(cause));
10585 assert_eq!(t.passes[0].pass_index, 0);
10586 assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
10587 assert!(t.upgrade_resume_key().is_some());
10588
10589 t.start("20260904-000000-4043".to_owned());
10592 run.begin_pass();
10593 run.status = RunStatus::Failed;
10594 let verdict = Verdict {
10595 status: RunStatus::Failed,
10596 left_pr: false,
10597 quota_hit: false,
10598 parked: false,
10599 no_viable_candidates: false,
10600 };
10601 settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
10602 assert_eq!(t.passes.len(), 2);
10603 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
10604 assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
10605 assert_eq!(t.passes[1].pass_index, 1);
10606 assert_eq!(t.attempts, 1);
10607 }
10608
10609 #[test]
10610 fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
10611 let mut t = task();
10612 t.start("20260904-000000-4043".to_owned());
10613 reclaim(&mut t, None, 2, "en");
10614 assert_eq!(t.status, TaskStatus::Held);
10615 assert!(
10616 t.last_error
10617 .as_deref()
10618 .is_some_and(|e| e.contains("running")),
10619 "the operator needs to know why this task was held"
10620 );
10621 }
10622
10623 #[test]
10624 fn sync_base_only_orphan_holds_without_replay_or_attempt_change() {
10625 let dir = tempfile::tempdir().unwrap();
10626 let queue = Queue::at(dir.path().to_path_buf());
10627 let mut task = task();
10628 let run = "20261124-000000-dead";
10629 task.link_run(run);
10630 task.attempts = 2;
10631 task.status = TaskStatus::Running;
10632 task.sync_only = Some(crate::base_sync_only::Request {
10633 run: run.into(),
10634 at: Timestamp::now(),
10635 });
10636 queue.put(&mut task).unwrap();
10637 assert_eq!(
10638 reclaim_orphaned_running(&queue, 3, &Default::default()),
10639 vec![task.id.clone()]
10640 );
10641 let saved = queue.get(&task.id).unwrap();
10642 assert_eq!(saved.status, TaskStatus::Held);
10643 assert_eq!(saved.attempts, 2);
10644 assert_eq!(saved.execution_runs(), [run]);
10645 assert!(
10646 saved
10647 .last_error
10648 .unwrap()
10649 .contains("verification was not allowed")
10650 );
10651 assert!(reclaim_orphaned_running(&queue, 3, &Default::default()).is_empty());
10652 }
10653
10654 #[test]
10655 fn sync_base_only_completed_orphan_holds_without_charging_or_double_refunding() {
10656 use crate::base_sync_only::{Outcome, Pass, Request};
10657
10658 let mut state = run_state(RunStatus::Blocked);
10659 let mut task = task();
10660 let request = Request {
10661 run: state.id.clone(),
10662 at: Timestamp::now(),
10663 };
10664 task.start(state.id.clone());
10665 task.sync_only = Some(request.clone());
10666 task.attempts = 2;
10668 let mut pass = Pass::new(request, &state);
10669 pass.result = Outcome::AlreadyCurrent;
10670 state.sync_only_passes.push(pass);
10671 state.begin_pass();
10672
10673 reclaim(&mut task, Some(state), 3, "en");
10674
10675 assert_eq!(task.status, TaskStatus::Held);
10676 assert_eq!(task.attempts, 2);
10677 assert!(task.sync_only.is_none());
10678 let detail = task.hold_reason.unwrap();
10679 assert!(detail.contains("HEAD already contains the base"));
10680 assert!(detail.contains("verification was not allowed"));
10681 }
10682
10683 #[test]
10684 fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
10685 let dir = tempfile::tempdir().unwrap();
10686 let queue = Queue::at(dir.path().to_path_buf());
10687
10688 let mut orphaned = task();
10690 orphaned.id = "20260904-000000-orph".to_owned();
10691 orphaned.status = TaskStatus::Running;
10692 orphaned.attempts = 1;
10693 queue.put(&mut orphaned).unwrap();
10694
10695 let mut alive = task();
10696 alive.id = "20260904-000000-live".to_owned();
10697 alive.status = TaskStatus::Running;
10698 alive.attempts = 1;
10699 queue.put(&mut alive).unwrap();
10700 let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
10701
10702 let mut queued = task();
10703 queued.id = "20260904-000000-wait".to_owned();
10704 queue.put(&mut queued).unwrap();
10705
10706 let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
10707 assert_eq!(reclaimed, vec![orphaned.id.clone()]);
10708
10709 assert_eq!(
10710 queue.get(&orphaned.id).unwrap().status,
10711 TaskStatus::Held,
10712 "nothing was driving it and there was no run to recover"
10713 );
10714 assert_eq!(
10715 queue.get(&alive.id).unwrap().status,
10716 TaskStatus::Running,
10717 "a live claim must protect the task it belongs to"
10718 );
10719 assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
10720 }
10721
10722 fn read_run_under(home: &Path, id: &str) -> RunState {
10728 let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
10729 serde_json::from_str(&body).unwrap()
10730 }
10731
10732 #[test]
10733 fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
10734 let dir = tempfile::tempdir().unwrap();
10735 let home = dir.path().to_path_buf();
10736 let now = Timestamp::now();
10737 let overrun_seat = || crate::run::ActiveSeat {
10738 node: "implement".to_owned(),
10739 started_at: now - jiff::SignedDuration::new(21_000, 0),
10740 timeout_secs: 3_600,
10741 attempt: 0,
10742 task: None,
10743 command: None,
10744 index: None,
10745 total: None,
10746 };
10747
10748 let mut dead = run_state(RunStatus::Implementing);
10749 dead.id = "20260101-000000-dead".to_owned();
10750 dead.active.insert("impl-A".to_owned(), overrun_seat());
10751 dead.driver_pid = Some(4242);
10754 dead.save_under(&home).unwrap();
10755
10756 let mut alive = run_state(RunStatus::Implementing);
10759 alive.id = "20260101-000000-aliv".to_owned();
10760 alive.active.insert("impl-A".to_owned(), overrun_seat());
10761 alive.save_under(&home).unwrap();
10762 let mut status = Status::new();
10763 status.current = vec![Current {
10764 worker: None,
10765 task: "20260101-000000-task".to_owned(),
10766 run: alive.id.clone(),
10767 }];
10768 write_status_to(&home.join("daemon.json"), &status).unwrap();
10769
10770 let questions = Questions::at(home.join("questions"));
10774 let mut q = ask::Question::new(
10775 dead.id.clone(),
10776 "implement".to_owned(),
10777 "impl-A".to_owned(),
10778 "Which storage backend?".to_owned(),
10779 String::new(),
10780 vec!["SQLite".to_owned(), "Redis".to_owned()],
10781 );
10782 questions.put(&mut q).unwrap();
10783
10784 let abandoned = reclaim_abandoned_runs_with(
10785 &home,
10786 now,
10787 |pid| if pid == 4242 { Some(false) } else { None },
10788 |_| panic!("a query answering Dead outright needs no identity corroboration"),
10789 );
10790 assert_eq!(abandoned, vec![dead.id.clone()]);
10791
10792 let reloaded = read_run_under(&home, &dead.id);
10793 assert_eq!(reloaded.status, RunStatus::Failed);
10794 assert!(reloaded.active.is_empty());
10795 assert!(
10796 !questions.get(&q.id).unwrap().status.open(),
10797 "the failed run's own open question must be settled in the same pass"
10798 );
10799
10800 let still_alive = read_run_under(&home, &alive.id);
10801 assert_eq!(
10802 still_alive.status,
10803 RunStatus::Implementing,
10804 "a live daemon's claim protects it"
10805 );
10806 assert!(!still_alive.active.is_empty());
10807 }
10808
10809 #[test]
10819 fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
10820 let dir = tempfile::tempdir().unwrap();
10821 let home = dir.path().to_path_buf();
10822 let now = Timestamp::now();
10823
10824 let mut manual = run_state(RunStatus::Reviewing);
10825 manual.id = "20260101-000000-manl".to_owned();
10826 manual.active.insert(
10827 "review-1".to_owned(),
10828 crate::run::ActiveSeat {
10829 node: "review".to_owned(),
10830 started_at: now - jiff::SignedDuration::new(21_000, 0),
10831 timeout_secs: 3_600,
10832 attempt: 0,
10833 task: None,
10834 command: None,
10835 index: None,
10836 total: None,
10837 },
10838 );
10839 manual.driver_pid = Some(4242);
10843 manual.driver_started_at = Some("1790000000".to_owned());
10844 manual.save_under(&home).unwrap();
10845
10846 let abandoned = reclaim_abandoned_runs_with(
10847 &home,
10848 now,
10849 |pid| if pid == 4242 { Some(true) } else { None },
10850 |pid| {
10851 if pid == 4242 {
10852 Some("1790000000".to_owned())
10853 } else {
10854 None
10855 }
10856 },
10857 );
10858 assert!(
10859 abandoned.is_empty(),
10860 "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
10861 );
10862
10863 let reloaded = read_run_under(&home, &manual.id);
10864 assert_eq!(reloaded.status, RunStatus::Reviewing);
10865 assert!(!reloaded.active.is_empty());
10866 }
10867
10868 #[test]
10869 fn an_already_claimed_task_is_skipped_rather_than_failed() {
10870 let dir = tempfile::tempdir().unwrap();
10871 let queue = Queue::at(dir.path().to_path_buf());
10872 let mut only = task();
10873 queue.put(&mut only).unwrap();
10874
10875 let _elsewhere = queue.claim(&only.id).unwrap();
10876 let candidates = runnable(&queue);
10877 assert_eq!(candidates.len(), 1, "the task is still runnable");
10878 assert!(
10879 queue.claim(&candidates[0].id).is_err(),
10880 "the loop cannot take a claim somebody else holds"
10881 );
10882
10883 let after = queue.get(&only.id).unwrap();
10884 assert_eq!(after.status, TaskStatus::Queued);
10885 assert_eq!(
10886 after.attempts, 0,
10887 "losing the race is not an attempt at the task"
10888 );
10889 assert_eq!(after.last_error, None);
10890 }
10891
10892 #[test]
10893 fn the_status_file_round_trips_and_its_heartbeat_advances() {
10894 let dir = tempfile::tempdir().unwrap();
10895 let path = dir.path().join("daemon.json");
10896
10897 let mut status = Status::new();
10898 status.idle = false;
10899 status.completed = 7;
10900 status.current = vec![Current {
10901 worker: None,
10902 task: "20260902-000000-t111".to_owned(),
10903 run: "20260902-000001-r111".to_owned(),
10904 }];
10905 write_status_to(&path, &status).unwrap();
10906 let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
10907 assert_eq!(first.schema, SCHEMA);
10908 assert_eq!(first.pid, std::process::id());
10909 assert!(!first.idle);
10910 assert_eq!(first.completed, 7);
10911 assert_eq!(first.current, status.current);
10912 assert!(
10913 !path.with_extension("json.tmp").exists(),
10914 "the temp file is renamed, not left behind"
10915 );
10916
10917 std::thread::sleep(Duration::from_millis(5));
10918 status.updated_at = Timestamp::now();
10919 status.polls = 3;
10920 write_status_to(&path, &status).unwrap();
10921 let second: Status =
10922 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
10923 assert!(
10924 second.updated_at > first.updated_at,
10925 "a reader can only detect staleness if the heartbeat moves"
10926 );
10927 assert_eq!(
10928 second.started_at, first.started_at,
10929 "the start time is not a heartbeat"
10930 );
10931 assert_eq!(second.polls, 3);
10932 }
10933
10934 #[test]
10935 fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
10936 let dir = tempfile::tempdir().unwrap();
10937
10938 assert!(read_status(dir.path()).is_none(), "no file, no daemon");
10939
10940 let mut status = Status::new();
10941 status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
10942 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10943 let stale = read_status(dir.path()).unwrap();
10944 assert!(
10945 !stale.running(Timestamp::now()),
10946 "a minute without a heartbeat is a dead daemon, not a busy one"
10947 );
10948 assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
10949
10950 status.updated_at = Timestamp::now();
10951 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10952 let fresh = read_status(dir.path()).unwrap();
10953 assert!(fresh.running(Timestamp::now()));
10954 }
10955
10956 #[test]
10957 fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
10958 let dir = tempfile::tempdir().unwrap();
10959 let now = Timestamp::now();
10960 let mine = "20260903-080619-01c2";
10961
10962 assert!(
10963 !is_working_on(dir.path(), mine, now),
10964 "no status file means nobody is working on anything"
10965 );
10966
10967 let mut status = Status::new();
10968 status.current = vec![Current {
10969 worker: None,
10970 task: "20260903-080340-0167".to_owned(),
10971 run: mine.to_owned(),
10972 }];
10973 status.updated_at = now;
10974 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10975 assert!(is_working_on(dir.path(), mine, now));
10976 assert!(
10977 !is_working_on(dir.path(), "20260903-105039-3cbf", now),
10978 "a daemon busy with one run is not working on another"
10979 );
10980
10981 status.updated_at = now - jiff::SignedDuration::from_secs(600);
10984 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10985 assert!(
10986 !is_working_on(dir.path(), mine, now),
10987 "a stale heartbeat is a dead daemon, so its run is a leftover"
10988 );
10989 }
10990
10991 #[test]
10992 fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
10993 let dir = tempfile::tempdir().unwrap();
10994 let now = Timestamp::now();
10995
10996 assert!(
10997 !is_working_on_short(dir.path(), "01c2", now),
10998 "no status file means nobody is working on anything"
10999 );
11000
11001 let mut status = Status::new();
11002 status.current = vec![Current {
11003 worker: None,
11004 task: "20260903-080340-0167".to_owned(),
11005 run: "20260903-080619-01c2".to_owned(),
11006 }];
11007 status.updated_at = now;
11008 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
11009 assert!(
11010 is_working_on_short(dir.path(), "01c2", now),
11011 "the run's short id is the last block of its full id"
11012 );
11013 assert!(
11014 !is_working_on_short(dir.path(), "3cbf", now),
11015 "a daemon busy with one worktree bay is not working on another"
11016 );
11017 }
11018
11019 #[test]
11020 fn a_newer_status_file_still_yields_a_reading() {
11021 let dir = tempfile::tempdir().unwrap();
11022 std::fs::write(
11025 dir.path().join("daemon.json"),
11026 serde_json::json!({
11027 "schema": 2,
11028 "updated_at": Timestamp::now().to_string(),
11029 "idle": true,
11030 "surprise": { "nested": [1, 2, 3] },
11031 })
11032 .to_string(),
11033 )
11034 .unwrap();
11035
11036 let reading = read_status(dir.path()).expect("a forward-compatible read");
11037 assert!(reading.running(Timestamp::now()));
11038 assert!(reading.idle);
11039 assert!(reading.current.is_empty());
11040 }
11041
11042 #[test]
11043 fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
11044 let dir = tempfile::tempdir().unwrap();
11050 std::fs::write(
11051 dir.path().join("daemon.json"),
11052 serde_json::json!({
11053 "schema": 1,
11054 "pid": 4242,
11055 "updated_at": Timestamp::now().to_string(),
11056 "idle": false,
11057 "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
11058 "completed": 3,
11059 "polls": 9,
11060 })
11061 .to_string(),
11062 )
11063 .unwrap();
11064
11065 let reading = read_status(dir.path()).expect("an older shape must still parse");
11066 assert!(reading.running(Timestamp::now()));
11067 assert_eq!(
11068 reading.current,
11069 vec![Current {
11070 worker: None,
11071 task: "20260902-140501-aaaa".to_owned(),
11072 run: "20260902-140502-bbbb".to_owned(),
11073 }]
11074 );
11075 }
11076
11077 #[test]
11078 fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
11079 let dir = tempfile::tempdir().unwrap();
11080 std::fs::write(
11081 dir.path().join("daemon.json"),
11082 serde_json::json!({
11083 "schema": 1,
11084 "updated_at": Timestamp::now().to_string(),
11085 "idle": true,
11086 "current": null,
11087 })
11088 .to_string(),
11089 )
11090 .unwrap();
11091 let with_null = read_status(dir.path()).expect("null must still parse");
11092 assert!(with_null.current.is_empty());
11093
11094 std::fs::write(
11095 dir.path().join("daemon.json"),
11096 serde_json::json!({
11097 "schema": 1,
11098 "updated_at": Timestamp::now().to_string(),
11099 "idle": true,
11100 })
11101 .to_string(),
11102 )
11103 .unwrap();
11104 let absent = read_status(dir.path()).expect("a missing field must still parse");
11105 assert!(absent.current.is_empty());
11106 }
11107
11108 #[test]
11109 fn a_task_without_a_repository_runs_in_the_daemons_default() {
11110 let fallback = Path::new("/default");
11111 let mut blank = task();
11112 blank.repo = PathBuf::new();
11113 assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
11114 let mut dot = task();
11115 dot.repo = PathBuf::from(".");
11116 assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
11117 assert_eq!(
11118 repo_for(&task(), fallback),
11119 PathBuf::from("/repo"),
11120 "a task that names a repository keeps it"
11121 );
11122 }
11123
11124 #[test]
11125 fn new_tasks_inherit_the_daemon_build_cache_but_historical_tasks_remain_shared() {
11126 let dir = tempfile::tempdir().unwrap();
11127 let repo = dir.path();
11128 let path = repo.join("explicit.toml");
11129 std::fs::write(
11130 &path,
11131 "[verify]\nbuild_cache = 'isolated'\n[graph]\njudges = 1\n",
11132 )
11133 .unwrap();
11134 let opts = Opts {
11135 config: Some(path),
11136 ..Opts::default()
11137 };
11138 let queue = Queue::at(repo.join("queue"));
11139 let mut new = task();
11140 queue.put(&mut new).unwrap();
11141 let resolved = |task: &Task| prepare_for(repo, &opts, task).unwrap();
11142 assert_eq!(
11143 resolved(&queue.get(&new.id).unwrap()).verify.build_cache,
11144 BuildCache::Isolated
11145 );
11146
11147 let mut old = task();
11148 old.schema = 22;
11149 queue.put(&mut old).unwrap();
11150 let mut old = queue.get(&old.id).unwrap();
11151 let config = resolved(&old);
11152 assert_eq!(config.verify.build_cache, BuildCache::Shared);
11153 assert_eq!(config.graph.judges, 1, "preserve daemon config inheritance");
11154 old.hold_manual(Some("wait".into()));
11155 queue.put(&mut old).unwrap();
11156
11157 let mut saved = queue.get(&old.id).unwrap();
11158 assert_eq!(resolved(&saved).verify.build_cache, BuildCache::Shared);
11159 saved
11160 .overrides
11161 .as_mut()
11162 .unwrap()
11163 .merge_over(&crate::queue::RunOverrides {
11164 build_cache: Some(BuildCache::Isolated),
11165 ..Default::default()
11166 });
11167 queue.put(&mut saved).unwrap();
11168 assert_eq!(
11169 resolved(&queue.get(&saved.id).unwrap()).verify.build_cache,
11170 BuildCache::Isolated
11171 );
11172 }
11173
11174 #[test]
11175 fn urgent_build_cache_precedes_config_but_not_an_explicit_choice() {
11176 let dir = tempfile::tempdir().unwrap();
11177 let path = dir.path().join("explicit.toml");
11178 let write = |verify: &str| {
11179 std::fs::write(&path, format!("[verify]\nbuild_cache = 'shared'\n{verify}")).unwrap();
11180 };
11181 write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test\"]\n");
11182 let opts = Opts {
11183 config: Some(path.clone()),
11184 ..Opts::default()
11185 };
11186 let mut task = task();
11187 task.set_urgent(true).unwrap();
11188 let resolved = |task: &Task| {
11189 prepare_for(dir.path(), &opts, task)
11190 .unwrap()
11191 .verify
11192 .build_cache
11193 };
11194 assert_eq!(resolved(&task), BuildCache::Isolated);
11195 task.change_build_cache(Some(BuildCache::Shared)).unwrap();
11196 assert_eq!(resolved(&task), BuildCache::Shared);
11197 task.change_build_cache(None).unwrap();
11198 assert_eq!(resolved(&task), BuildCache::Isolated);
11199 task.set_urgent(false).unwrap();
11200 assert_eq!(resolved(&task), BuildCache::Shared);
11201
11202 task.set_urgent(true).unwrap();
11206 write("e2e = [\"npm test\"]\n");
11207 assert_eq!(resolved(&task), BuildCache::Shared);
11208 write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test | tee log\"]\n");
11209 assert_eq!(resolved(&task), BuildCache::Shared);
11210 task.change_build_cache(Some(BuildCache::Isolated)).unwrap();
11212 assert_eq!(resolved(&task), BuildCache::Isolated);
11213 }
11214
11215 #[test]
11216 fn task_implementers_edit_inherits_daemon_config_and_merge() {
11217 let dir = tempfile::tempdir().unwrap();
11218 let path = dir.path().join("explicit.toml");
11219 std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
11220 let opts = Opts {
11221 config: Some(path),
11222 merge: Some("none".into()),
11223 ..Default::default()
11224 };
11225 let mut t = task();
11226 t.set_implementers(
11227 2,
11228 &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
11229 .unwrap(),
11230 )
11231 .unwrap();
11232 let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
11233 assert_eq!(cfg.graph.implementers, 2);
11234 assert_eq!(cfg.graph.judges, 1);
11235 assert_eq!(cfg.merge.mode, MergeMode::None);
11236 t.set_implementers(1, &cfg).unwrap();
11237 let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
11238 apply_task_implementers(&mut cfg, &t);
11239 assert_eq!(cfg.graph.implementers, 1);
11240 assert_eq!(cfg.graph.judges, 1);
11241 assert_eq!(cfg.merge.mode, MergeMode::None);
11242 }
11243
11244 #[test]
11245 fn task_implementers_direct_overrides_stay_isolated_after_edits() {
11246 let dir = tempfile::tempdir().unwrap();
11247 let repo = dir.path().join("repo");
11248 std::fs::create_dir(&repo).unwrap();
11249 std::fs::write(
11250 repo.join("magi.toml"),
11251 "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
11252 )
11253 .unwrap();
11254 let daemon_config = dir.path().join("daemon.toml");
11255 std::fs::write(
11256 &daemon_config,
11257 "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
11258 )
11259 .unwrap();
11260 let opts = Opts {
11261 config: Some(daemon_config),
11262 merge: Some("pr".into()),
11263 ..Default::default()
11264 };
11265 let q = Queue::at(dir.path().join("queue"));
11266 let validation: Config =
11267 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
11268 .unwrap();
11269 for record in ["{}", r#"{"candidates":2}"#] {
11271 let overrides = serde_json::from_str(record).unwrap();
11272 let filing = crate::direct::Filing {
11273 instruction: "work".into(),
11274 title: "direct".into(),
11275 repo: repo.clone(),
11276 source: crate::queue::Source::Human,
11277 solo: false,
11278 overrides,
11279 review_of: None,
11280 sources: Default::default(),
11281 };
11282 let filed =
11283 crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
11284 let crate::direct::Filed::Standalone {
11285 mut task,
11286 claim: _claim,
11287 } = filed
11288 else {
11289 panic!("local filing")
11290 };
11291 let before = prepare_for(&repo, &opts, &task).unwrap();
11292 assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
11293 assert_eq!(
11294 before.merge.mode,
11295 MergeMode::None,
11296 "daemon --merge must not leak"
11297 );
11298 for n in [2, 1, 2] {
11299 task.set_implementers(n, &validation).unwrap();
11300 q.put(&mut task).unwrap();
11301 task = q.get(&task.id).unwrap();
11302 assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
11303 let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
11304 apply_task_implementers(&mut cfg, &task);
11305 assert_eq!(cfg.graph.implementers, usize::from(n));
11306 assert_eq!(cfg.graph.judges, 2);
11307 assert_eq!(cfg.merge.mode, MergeMode::None);
11308 }
11309 }
11310 }
11311
11312 #[test]
11313 fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
11314 let cfg: Config =
11315 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
11316 .unwrap();
11317 let mut t = task();
11318 t.review_of = Some("review-target".into());
11319 t.hold_manual(Some("retry".into()));
11320 let mut previous = RunState::new(
11321 PathBuf::from("/repo"),
11322 "main".into(),
11323 "abc1234".into(),
11324 "review".into(),
11325 cfg.clone(),
11326 );
11327 previous.config.graph.implementers = 2;
11328 for count in [1, 3] {
11329 t.set_implementers(count, &cfg).unwrap();
11330 t.release();
11331 assert_eq!(t.review_of.as_deref(), Some("review-target"));
11332 for proposed in [
11333 Starter::Resume(previous.id.clone()),
11334 Starter::Review("recovery-target".into()),
11335 ] {
11336 assert_eq!(
11337 starter_with_implementers(&t, Some(&previous), proposed),
11338 Starter::Review("review-target".into())
11339 );
11340 }
11341 let mut configured = cfg.clone();
11342 apply_task_implementers(&mut configured, &t);
11343 assert_eq!(configured.graph.implementers, usize::from(count));
11344 assert_eq!(previous.config.graph.implementers, 2);
11345 }
11346 }
11347
11348 #[test]
11349 fn task_implementers_dispatch_and_resume_agree() {
11350 let mut t = task();
11351 let cfg: crate::config::Config =
11352 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
11353 .unwrap();
11354 let mut run = RunState::new(
11355 PathBuf::from("/repo"),
11356 "main".into(),
11357 "abc1234".into(),
11358 "work".into(),
11359 cfg.clone(),
11360 );
11361 run.config.graph.implementers = 2;
11362 for n in [2, 1, 3, 2] {
11363 t.set_implementers(n, &cfg).unwrap();
11364 let mut dispatched = cfg.clone();
11365 apply_task_implementers(&mut dispatched, &t);
11366 assert_eq!(dispatched.graph.implementers, usize::from(n));
11367 assert_eq!(implementers_match(&t, &run), n == 2);
11368 for proposed in [
11369 Starter::Resume(run.id.clone()),
11370 Starter::Review("old-branch".into()),
11371 ] {
11372 let expected = if n == 2 {
11373 proposed.clone()
11374 } else {
11375 Starter::Start
11376 };
11377 assert_eq!(
11378 starter_with_implementers(&t, Some(&run), proposed),
11379 expected
11380 );
11381 }
11382 assert_eq!(
11383 run.config.graph.implementers, 2,
11384 "history must not be rewritten"
11385 );
11386 }
11387 t.solo = false;
11388 t.overrides = None;
11389 assert!(implementers_match(&t, &run));
11390 }
11391
11392 #[test]
11393 fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
11394 let mut solo_cfg = Config::default();
11400 solo_cfg.graph.implementers = 3;
11401 let mut solo_task = task();
11402 solo_task.solo = true;
11403 apply_task_implementers(&mut solo_cfg, &solo_task);
11404 assert_eq!(solo_cfg.graph.implementers, 1);
11405
11406 let mut plain_cfg = Config::default();
11407 plain_cfg.graph.implementers = 3;
11408 let plain_task = task();
11409 assert!(!plain_task.solo);
11410 apply_task_implementers(&mut plain_cfg, &plain_task);
11411 assert_eq!(
11412 plain_cfg.graph.implementers, 3,
11413 "a task that did not ask to run alone keeps the config's candidates"
11414 );
11415 }
11416
11417 fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
11418 QuotaLoss {
11419 cause: crate::agent::QuotaCause::UsageLimit,
11420 agent: String::new(),
11421 seat: seat.into(),
11422 node: "judge".into(),
11423 at: at.parse().unwrap(),
11424 reset: reset.map(str::to_string),
11425 }
11426 }
11427
11428 #[test]
11429 fn authentication_losses_never_arm_a_cooldown_even_with_reset_hints() {
11430 let now = Timestamp::now();
11431 for reset in [None, Some("in 1h")] {
11432 let auth = crate::agent::Quota {
11433 cause: crate::agent::QuotaCause::Authentication,
11434 agent: "alpha".into(),
11435 reset: reset.map(str::to_owned),
11436 };
11437 let loss = QuotaLoss::from_report("advisor-1".into(), "advise", Some(&auth));
11438 assert_eq!(cooldown_until(&[loss], now), None);
11439 }
11440 }
11441
11442 #[test]
11443 fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
11444 let old: Vec<QuotaLoss> = (1..=4)
11445 .map(|i| {
11446 loss(
11447 &format!("judge-{i}"),
11448 "2026-09-23T05:23:00Z",
11449 Some("2:40pm (Asia/Tokyo)"),
11450 )
11451 })
11452 .collect();
11453 let fresh = losses_this_attempt(&old, &old);
11454 assert!(fresh.is_empty());
11455 assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
11456 }
11458
11459 #[test]
11460 fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
11461 let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
11462 let now = Timestamp::now();
11463 let mut after = old.clone();
11464 after.push(loss("judge-2", &now.to_string(), None));
11465 let fresh = losses_this_attempt(&old, &after);
11466 assert_eq!(fresh, vec![after[1].clone()]);
11467 let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
11468 assert_eq!(
11469 until,
11470 now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
11471 );
11472 }
11473
11474 #[test]
11475 fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
11476 let before = vec![
11479 loss("judge-1", "2026-09-23T05:23:00Z", None),
11480 loss("judge-2", "2026-09-23T05:24:00Z", None),
11481 ];
11482 let after = vec![
11483 loss("judge-2", "2026-09-23T05:24:00Z", None),
11484 loss("judge-1", "2026-09-24T01:00:00Z", None),
11485 ];
11486 assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
11487 }
11488
11489 #[test]
11490 fn merge_overrides_are_parsed_or_refused() {
11491 assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
11492 assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
11493 assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
11494 assert!(merge_mode("squash").is_err());
11495 }
11496
11497 #[test]
11498 fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
11499 let now = Timestamp::now();
11500 let fallback = Duration::from_secs(300);
11501 let cap = Duration::from_secs(1800);
11502
11503 assert_eq!(quota_wait(None, now, fallback, cap), fallback);
11505
11506 let soon = now + jiff::SignedDuration::from_secs(600);
11508 assert_eq!(
11509 quota_wait(Some(soon), now, fallback, cap),
11510 Duration::from_secs(600)
11511 );
11512
11513 let past = now - jiff::SignedDuration::from_secs(60);
11516 assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
11517
11518 let far = now + jiff::SignedDuration::from_secs(3 * 3600);
11521 assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
11522 }
11523
11524 #[test]
11525 fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
11526 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
11527
11528 let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
11529 assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
11530
11531 let already_past =
11535 parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
11536 assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
11537
11538 assert!(
11539 parse_reset_hint("session limit reached", now, now).is_none(),
11540 "free text with no recognised shape is not guessed at"
11541 );
11542 assert!(
11543 parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
11544 "an unresolvable zone name is not guessed at either"
11545 );
11546 }
11547
11548 #[test]
11549 fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
11550 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
11551
11552 let at = parse_reset_hint(
11553 "You've hit your usage limit. Visit \
11554 https://chatgpt.com/codex/settings/usage to purchase more \
11555 credits or try again at Sep 19th, 2026 5:10 PM.",
11556 now,
11557 now,
11558 )
11559 .expect("the codex reset wording is a recognised shape");
11560 assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
11561
11562 let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
11567 .expect("an explicit year needs no rollover");
11568 assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
11569
11570 assert!(
11571 parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
11572 "a two-digit year is not the documented shape and is not guessed at"
11573 );
11574 assert!(
11575 parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
11576 "a four-letter month name is not the documented three-letter abbreviation"
11577 );
11578 assert!(
11579 parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
11580 "an explicit zone on the dated shape is a format nobody has \
11581 documented, and is refused rather than guessed at as UTC"
11582 );
11583 }
11584
11585 #[test]
11586 fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
11587 let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
11588 let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
11589
11590 let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
11591 assert_eq!(at.as_second() - recorded.as_second(), 3769);
11592
11593 let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
11594 assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
11595
11596 for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
11597 assert!(
11598 parse_reset_hint(bad, now, recorded).is_none(),
11599 "{bad:?} must not be guessed at"
11600 );
11601 }
11602 }
11603
11604 fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
11608 let config = dir.join("magi.toml");
11609 std::fs::write(
11610 &config,
11611 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
11612 )
11613 .unwrap();
11614 let opts = Opts {
11615 poll: Duration::from_secs(30),
11616 config: Some(config),
11617 repo: dir.join("repo"),
11621 ..Opts::default()
11622 };
11623 let home = dir.join("home");
11632 let stamps = home.join("service-ticks");
11635 std::fs::create_dir_all(&stamps).unwrap();
11636 for service in ["waiter", "deputies", "release-watch"] {
11637 std::fs::write(
11638 stamps.join(service),
11639 Timestamp::now().as_second().to_string(),
11640 )
11641 .unwrap();
11642 }
11643 for operation in [
11644 "conductor",
11645 "maintenance",
11646 "housekeeping",
11647 "disk-pressure",
11648 "cache",
11649 "fetch",
11650 "chat-goals",
11651 ] {
11652 std::fs::write(
11653 stamps.join(format!("daemon-{operation}")),
11654 serde_json::to_vec(&Timestamp::now()).unwrap(),
11655 )
11656 .unwrap();
11657 }
11658 let worktrees = dir.join("wt");
11659 (
11660 opts,
11661 Queue::at(dir.join("queue")),
11662 home.join("daemon.json"),
11663 home,
11664 worktrees,
11665 )
11666 }
11667
11668 #[tokio::test]
11669 async fn disk_wait_maintenance_recovers_while_another_task_is_running() {
11670 let dir = tempfile::tempdir().unwrap();
11671 let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
11672 let mut waiting = task();
11673 waiting.repo = opts.repo.clone();
11674 waiting.hold_machine(crate::disk::gate(1, 100));
11675 waiting.mark_disk_capacity();
11676 waiting.attempts = 2;
11677 queue.put(&mut waiting).unwrap();
11678 let mut busy = task();
11679 busy.status = TaskStatus::Running;
11680 queue.put(&mut busy).unwrap();
11681 let payload = serde_json::to_value(ServiceWorker {
11682 opts,
11683 queue: queue.root().to_owned(),
11684 worktrees_root: worktrees,
11685 operation: "maintenance".into(),
11686 })
11687 .unwrap();
11688 run_service_worker(&home, payload.clone()).await.unwrap();
11689 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Queued);
11690 assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
11691 assert_eq!(queue.get(&busy.id).unwrap().status, TaskStatus::Running);
11692 run_service_worker(&home, payload).await.unwrap();
11693 assert!(
11694 crate::worker::active(&home).unwrap().is_empty(),
11695 "monitoring only queues; normal dispatch owns launches"
11696 );
11697 assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
11698 }
11699
11700 #[tokio::test]
11701 async fn source_eviction_service_receipts_explain_idle_and_active_skips() {
11702 let dir = tempfile::tempdir().unwrap();
11703 let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
11704 let cfg = Config::default();
11705 start_service(
11706 &home,
11707 &opts,
11708 &queue,
11709 &worktrees,
11710 "housekeeping",
11711 Some(&cfg),
11712 true,
11713 )
11714 .await
11715 .unwrap();
11716 let receipt = home.join("source-eviction-housekeeping-dispatch.json");
11717 let read = |path: &Path| -> serde_json::Value {
11718 serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap()
11719 };
11720 assert_eq!(read(&receipt)["detail"], "cadence not due");
11721 std::fs::remove_file(home.join("service-ticks/daemon-housekeeping")).unwrap();
11722 start_service(
11723 &home,
11724 &opts,
11725 &queue,
11726 &worktrees,
11727 "housekeeping",
11728 Some(&cfg),
11729 true,
11730 )
11731 .await
11732 .unwrap();
11733 assert_eq!(
11734 read(&receipt)["detail"],
11735 "active work or runnable task queue"
11736 );
11737 assert_eq!(read(&receipt)["version"], env!("CARGO_PKG_VERSION"));
11738 assert_eq!(read(&receipt)["auto_fold"], cfg.disk.auto_fold);
11739 std::fs::remove_file(home.join("service-ticks/daemon-disk-pressure")).unwrap();
11740 start_service(
11741 &home,
11742 &opts,
11743 &queue,
11744 &worktrees,
11745 "disk-pressure",
11746 Some(&cfg),
11747 false,
11748 )
11749 .await
11750 .unwrap();
11751 assert_eq!(
11752 read(&home.join("source-eviction-disk-pressure-dispatch.json"))["detail"],
11753 "no active work; idle housekeeping owns scan"
11754 );
11755 assert!(crate::worker::active(&home).unwrap().is_empty());
11756 }
11757
11758 #[tokio::test]
11759 async fn goal_observation_service_does_not_block_scheduler_decisions() {
11760 let dir = tempfile::tempdir().unwrap();
11761 let (opts, _, _, home, worktrees) = idle_loop(dir.path());
11762 let queue = Queue::at(home.join("queue"));
11763 let mut task = task();
11764 task.repo = opts.repo.clone();
11765 task.chat = Some("decision-chat".into());
11766 task.hold_machine(Some("waiting for a decision".into()));
11767 queue.put(&mut task).unwrap();
11768 let questions = Questions::at(home.join("questions"));
11769 let mut question = action_question(&task.id, ask::ChoiceAction::Done);
11770 question.node = crate::conduct::NODE.into();
11771 question.status = ask::QuestionStatus::Open;
11772 question.answer = None;
11773 question.answered_at = None;
11774 questions.put(&mut question).unwrap();
11775 questions
11776 .update(&question.id, |q| {
11777 q.answer(ask::Answer::Choice("resume で続行する".into()))
11778 })
11779 .unwrap();
11780
11781 let talks = crate::talk::Talks::at(home.join("talks"));
11782 let mut decision_chat = crate::talk::seeded_for_test("decision-chat", opts.repo.clone());
11783 decision_chat.pending = "Keep this unsent status question".into();
11784 talks.put(&mut decision_chat).unwrap();
11785 let mut talk = crate::talk::seeded_for_test("observing-chat", opts.repo.clone());
11786 talk.goals.push(serde_json::from_value(serde_json::json!({
11787 "id":"goal","purpose":"follow the retained job","scope":"one task",
11788 "condition":{"description":"land the result","kind":"runs_merged"},
11789 "state":"runnable","step":"reading the forge","source_turn":0,"owner_input":"land this job",
11790 "tasks":[],"runs":[],"watches":[],"evidence":"","wake":1,"handled":0,
11791 "started":1,"wakes":1,"last_checked":null,"fingerprint":""
11792 })).unwrap());
11793 talks.put(&mut talk).unwrap();
11794
11795 let directory = home.join("workers/jobs/abcdef");
11798 std::fs::create_dir_all(&directory).unwrap();
11799 let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
11800 crate::pr_head::try_lock_file(&lease).unwrap();
11801 let mut job = crate::worker::Job {
11802 id: "abcdef".into(),
11803 sequence: 1,
11804 kind: "daemon-service".into(),
11805 key: "service:daemon-chat-goals".into(),
11806 payload: serde_json::Value::Null,
11807 generation: "fixture".into(),
11808 version: None,
11809 status: crate::worker::Status::Running,
11810 result: None,
11811 pid: Some(std::process::id()),
11812 created_at: Timestamp::now().as_second() as u64,
11813 finished_at: None,
11814 };
11815 let record = directory.join("job.json");
11816 std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11817 let status = Arc::new(Mutex::new(Status::new()));
11818 let stop = Stop::new();
11819 let mut dispatch = Box::pin(poll(
11820 &opts,
11821 &queue,
11822 &status,
11823 &home,
11824 &worktrees,
11825 &stop,
11826 DispatchLimits {
11827 max_concurrent: 1,
11828 pause_for_interrupts: false,
11829 recovery_cfg: None,
11830 },
11831 ));
11832 std::future::poll_fn(|cx| {
11833 assert!(dispatch.as_mut().poll(cx).is_pending());
11834 std::task::Poll::Ready(())
11835 })
11836 .await;
11837 assert!(lock(&status).polls > 0);
11838 let saved = queue.get(&task.id).unwrap();
11839 assert_eq!(saved.status, TaskStatus::Done);
11840 assert!(saved.action_applied(&question.id));
11841 assert!(
11842 talks
11843 .get("decision-chat")
11844 .unwrap()
11845 .pending
11846 .contains("Keep this unsent status question")
11847 );
11848 let goal = talks.get(&talk.id).unwrap().goals.remove(0);
11849 assert_eq!(goal.state, crate::chat_goal::State::Runnable);
11850 assert_eq!(
11851 goal.started,
11852 Some(1),
11853 "only the observation worker may reconcile its goal"
11854 );
11855 assert_eq!(crate::worker::active(&home).unwrap()[0].id, job.id);
11856
11857 stop.stop();
11858 dispatch.await.unwrap();
11859 job.status = crate::worker::Status::Finished;
11860 std::fs::write(record, serde_json::to_vec(&job).unwrap()).unwrap();
11861 drop(lease);
11862 }
11863
11864 #[test]
11865 fn a_stop_is_idempotent_and_once_set_stays_set() {
11866 let stop = Stop::new();
11867 assert!(!stop.stopped());
11868
11869 stop.stop();
11870 assert!(stop.stopped());
11871 stop.stop();
11872 assert!(stop.stopped(), "a second stop is not a toggle");
11873
11874 let shared = stop.clone();
11875 assert!(
11876 shared.stopped(),
11877 "a clone is the same stop; that is how the loop and its caller share one"
11878 );
11879 }
11880
11881 #[tokio::test]
11882 async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
11883 for operation in ["conductor", "maintenance", "housekeeping"] {
11884 let dir = tempfile::tempdir().unwrap();
11885 let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
11886 opts.once = true;
11887 opts.poll = Duration::from_millis(1);
11888 let mut state = run_state(RunStatus::Ready);
11891 state.reserve_under(&home).unwrap();
11892 state.save_under(&home).unwrap();
11893 let mut task = task();
11894 task.runs.push(state.id.clone());
11895 queue.put(&mut task).unwrap();
11896 let claim = queue.claim(&task.id).unwrap();
11897
11898 let directory = home.join("workers/jobs/abcdef");
11901 std::fs::create_dir_all(&directory).unwrap();
11902 let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
11903 crate::pr_head::try_lock_file(&lease).unwrap();
11904 let mut job = crate::worker::Job {
11905 id: "abcdef".into(),
11906 sequence: 1,
11907 kind: "daemon-service".into(),
11908 key: format!("service:daemon-{operation}"),
11909 payload: serde_json::Value::Null,
11910 generation: "fixture".into(),
11911 version: None,
11912 status: crate::worker::Status::Running,
11913 result: None,
11914 pid: Some(std::process::id()),
11915 created_at: Timestamp::now().as_second() as u64,
11916 finished_at: None,
11917 };
11918 let record = directory.join("job.json");
11919 std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11920
11921 let status = Arc::new(Mutex::new(Status::new()));
11922 let stop = Stop::new();
11923 let mut drain = Box::pin(poll(
11924 &opts,
11925 &queue,
11926 &status,
11927 &home,
11928 &worktrees,
11929 &stop,
11930 DispatchLimits {
11931 max_concurrent: 1,
11932 pause_for_interrupts: false,
11933 recovery_cfg: None,
11934 },
11935 ));
11936 std::future::poll_fn(|cx| {
11937 use std::future::Future;
11938 assert!(
11939 drain.as_mut().poll(cx).is_pending(),
11940 "--once must wait for {operation} to release its queue claim"
11941 );
11942 std::task::Poll::Ready(())
11943 })
11944 .await;
11945 assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
11946
11947 let questions = Questions::at(home.join("questions"));
11950 let mut q = action_question(&state.id, ask::ChoiceAction::Done);
11951 questions.put(&mut q).unwrap();
11952 drop(claim);
11953 let expired =
11957 serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
11958 for service in [operation, "housekeeping"] {
11959 std::fs::write(
11960 home.join("service-ticks").join(format!("daemon-{service}")),
11961 &expired,
11962 )
11963 .unwrap();
11964 }
11965 job.status = crate::worker::Status::Finished;
11966 std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11967 drop(lease);
11968 tokio::time::timeout(Duration::from_secs(2), drain)
11969 .await
11970 .expect("the settled service must allow the drain to finish")
11971 .unwrap();
11972 let after = queue.get(&task.id).unwrap();
11973 assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
11974 assert!(after.action_applied(&q.id));
11975 for service in [operation, "housekeeping"] {
11976 assert_eq!(
11977 std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
11978 .unwrap(),
11979 expired,
11980 "the final once rescan must not restart {service}"
11981 );
11982 }
11983 }
11984 }
11985
11986 #[test]
11987 fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
11988 let stop = Stop::new();
11989 stop.busy.store(1, Ordering::SeqCst);
11990 assert!(
11991 !stop.finishing(),
11992 "a busy loop nobody has asked to stop is just running"
11993 );
11994
11995 stop.stop();
11996 assert!(
11997 stop.finishing(),
11998 "a stop asked for mid-run has not landed until the run is settled"
11999 );
12000
12001 stop.busy.store(0, Ordering::SeqCst);
12002 assert!(
12003 !stop.finishing(),
12004 "once the run is settled the stop has landed and there is nothing to finish"
12005 );
12006 }
12007
12008 #[test]
12009 fn finishing_stays_true_until_the_last_of_several_runs_exits() {
12010 let stop = Stop::new();
12011 stop.busy.store(2, Ordering::SeqCst);
12012 stop.stop();
12013 assert!(stop.finishing(), "two runs still in flight");
12014
12015 stop.busy.store(1, Ordering::SeqCst);
12016 assert!(
12017 stop.finishing(),
12018 "one run finished, but a sibling is still working"
12019 );
12020
12021 stop.busy.store(0, Ordering::SeqCst);
12022 assert!(
12023 !stop.finishing(),
12024 "the last run out is what actually lands the stop"
12025 );
12026 }
12027
12028 #[tokio::test]
12029 async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
12030 let dir = tempfile::tempdir().unwrap();
12031 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
12032 let stop = Stop::new();
12033 stop.stop();
12034
12035 let began = std::time::Instant::now();
12036 tokio::time::timeout(
12037 Duration::from_secs(2),
12038 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
12039 )
12040 .await
12041 .expect("a stopped loop must return, not sit out its poll interval")
12042 .expect("the loop's own setup and teardown must not fail");
12043 assert!(
12044 began.elapsed() < opts.poll,
12045 "returned only after {:?}, which is a poll interval, not a stop",
12046 began.elapsed()
12047 );
12048 }
12049
12050 #[tokio::test]
12051 async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
12052 let dir = tempfile::tempdir().unwrap();
12053 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
12054 let stop = Stop::new();
12055
12056 let asker = {
12059 let stop = stop.clone();
12060 tokio::spawn(async move {
12061 tokio::time::sleep(Duration::from_millis(20)).await;
12062 stop.stop();
12063 })
12064 };
12065
12066 let began = std::time::Instant::now();
12067 tokio::time::timeout(
12068 Duration::from_secs(2),
12069 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
12070 )
12071 .await
12072 .expect("a stop asked for while idle must wake the wait")
12073 .expect("the loop's own setup and teardown must not fail");
12074 asker.await.unwrap();
12075 assert!(
12076 began.elapsed() < opts.poll,
12077 "returned only after {:?}, so the stop waited on the sleep",
12078 began.elapsed()
12079 );
12080 }
12081
12082 #[tokio::test]
12083 async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
12084 let dir = tempfile::tempdir().unwrap();
12085 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
12086 let stop = Stop::new();
12087 stop.stop();
12088
12089 tokio::time::timeout(
12090 Duration::from_secs(2),
12091 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
12092 )
12093 .await
12094 .expect("a stopped loop must return")
12095 .expect("the loop's own setup and teardown must not fail");
12096
12097 assert!(
12098 home.is_dir(),
12099 "the loop did publish a status file, so its removal is the teardown and not an absence"
12100 );
12101 assert!(
12102 !status_file.exists(),
12103 "a stopped loop clears its status file"
12104 );
12105 assert!(
12106 read_status(&home).is_none(),
12107 "a reader must see no daemon at all, not a heartbeat that merely stopped"
12108 );
12109 }
12110
12111 #[tokio::test]
12112 async fn housekeeping_worker_settles_questions_without_a_scheduler() {
12113 let dir = tempfile::tempdir().unwrap();
12114 let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
12115
12116 let mut settled = RunState::new(
12117 dir.path().join("repo"),
12118 "main".to_owned(),
12119 "abc1234".to_owned(),
12120 "fixture".to_owned(),
12121 Config::default(),
12122 );
12123 settled.status = RunStatus::Ready;
12124 let run_dir = home.join("runs").join(&settled.id);
12125 std::fs::create_dir_all(&run_dir).unwrap();
12126 std::fs::write(
12127 run_dir.join("run.json"),
12128 serde_json::to_string_pretty(&settled).unwrap(),
12129 )
12130 .unwrap();
12131 let questions = Questions::at(home.join("questions"));
12132 let mut question = ask::Question::new(
12133 settled.id.clone(),
12134 "review".to_owned(),
12135 "reviewer-1".to_owned(),
12136 "Continue?".to_owned(),
12137 String::new(),
12138 Vec::new(),
12139 );
12140 questions.put(&mut question).unwrap();
12141
12142 run_service_worker(
12143 &home,
12144 serde_json::to_value(ServiceWorker {
12145 opts,
12146 queue: queue.root().to_path_buf(),
12147 worktrees_root: worktrees,
12148 operation: "housekeeping".to_owned(),
12149 })
12150 .unwrap(),
12151 )
12152 .await
12153 .unwrap();
12154
12155 assert_eq!(
12156 questions.get(&question.id).unwrap().status,
12157 ask::QuestionStatus::Abandoned,
12158 "the independent housekeeping worker settles ended-run questions"
12159 );
12160 }
12161
12162 #[test]
12163 fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
12164 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
12165
12166 assert!(
12167 cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
12168 "never checked before: due at once"
12169 );
12170
12171 let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
12172 assert!(
12173 !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
12174 "well inside the interval: not due yet"
12175 );
12176
12177 let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
12178 assert!(
12179 !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
12180 "exactly at the edge: not yet due, same convention as `clean::due`"
12181 );
12182
12183 let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
12184 assert!(
12185 cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
12186 "past the interval: due again"
12187 );
12188 }
12189
12190 fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
12195 let config = dir.join("magi.toml");
12196 std::fs::write(
12202 &config,
12203 format!(
12204 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
12205 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
12206 cache_dir.display()
12207 ),
12208 )
12209 .unwrap();
12210 Opts {
12211 config: Some(config),
12212 repo: dir.join("repo"),
12213 ..Opts::default()
12214 }
12215 }
12216
12217 #[tokio::test]
12218 async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
12219 let dir = tempfile::tempdir().unwrap();
12220 let home = dir.path().join("home");
12221 let cache_dir = dir.path().join("cache");
12222 std::fs::create_dir_all(&cache_dir).unwrap();
12223 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
12224 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
12225
12226 let running = Stop::new();
12229 let mut last_checked = None;
12230 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
12231 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
12232 .await;
12233 assert_eq!(
12234 crate::disk::dir_size(&cache_dir),
12235 0,
12236 "over the cap on the first check ever: pruned at once, no idle queue required"
12237 );
12238 assert_eq!(last_checked, Some(t0));
12239
12240 std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
12242 let too_soon = t0 + jiff::SignedDuration::from_secs(1);
12243 maybe_prune_cache_between_runs(
12244 &opts.repo,
12245 &opts,
12246 &home,
12247 &running,
12248 &mut last_checked,
12249 too_soon,
12250 )
12251 .await;
12252 assert_eq!(
12253 crate::disk::dir_size(&cache_dir),
12254 10,
12255 "too soon since the last check: left alone rather than rescanned every call"
12256 );
12257 assert_eq!(
12258 last_checked,
12259 Some(t0),
12260 "an idle check does not reset the clock"
12261 );
12262
12263 let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
12265 maybe_prune_cache_between_runs(
12266 &opts.repo,
12267 &opts,
12268 &home,
12269 &running,
12270 &mut last_checked,
12271 due_again,
12272 )
12273 .await;
12274 assert_eq!(
12275 crate::disk::dir_size(&cache_dir),
12276 0,
12277 "due again: pruned back under the cap"
12278 );
12279 }
12280
12281 #[tokio::test]
12289 async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
12290 let dir = tempfile::tempdir().unwrap();
12291 let home = dir.path().join("home");
12292 let cache_dir = dir.path().join("cache");
12293 std::fs::create_dir_all(&cache_dir).unwrap();
12294 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
12295 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
12296
12297 let stop = Stop::new();
12298 stop.stop();
12299 assert!(
12300 !stop.finishing(),
12301 "no run is in flight at a between-runs boundary, so nothing else \
12302 would tell the operator this stop had not taken effect yet"
12303 );
12304
12305 let mut last_checked = None;
12306 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
12307 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
12308 .await;
12309 assert_eq!(
12310 crate::disk::dir_size(&cache_dir),
12311 10,
12312 "over its cap, and due for the first check ever, but a stop outranks \
12313 it: the cap is a standing policy the next start measures again"
12314 );
12315 assert_eq!(
12316 last_checked, None,
12317 "a check that never happened must not claim the interval"
12318 );
12319 }
12320
12321 #[tokio::test]
12324 async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
12325 let dir = tempfile::tempdir().unwrap();
12326 let cache_dir = dir.path().join("cache");
12327 std::fs::create_dir_all(&cache_dir).unwrap();
12328 std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
12329
12330 let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
12331 opts.poll = Duration::from_millis(20);
12332 opts.max_attempts = 1_000;
12333
12334 let queue = Queue::at(dir.path().join("queue"));
12335 for i in 0..128 {
12336 let mut task = Task::new(
12337 format!("queued work {i}"),
12338 format!("queued work {i}"),
12339 opts.repo.clone(),
12340 Source::Human,
12341 );
12342 queue.put(&mut task).unwrap();
12343 }
12344
12345 let home = dir.path().join("home");
12346 let worktrees = dir.path().join("wt");
12347 run_service_worker(
12348 &home,
12349 serde_json::to_value(ServiceWorker {
12350 opts,
12351 queue: queue.root().to_path_buf(),
12352 worktrees_root: worktrees,
12353 operation: "cache".to_owned(),
12354 })
12355 .unwrap(),
12356 )
12357 .await
12358 .unwrap();
12359 let after = queue.list();
12360 assert_eq!(after.len(), 128);
12361 assert!(
12362 after
12363 .iter()
12364 .all(|task| task.status.runnable() && task.attempts == 0)
12365 );
12366
12367 assert_eq!(
12368 crate::disk::dir_size(&cache_dir),
12369 0,
12370 "an oversized cache must not be left to grow unboundedly just because the \
12371 queue kept the loop busy the whole time"
12372 );
12373 }
12374
12375 #[test]
12376 fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
12377 let dir = tempfile::tempdir().unwrap();
12378 let queue = Queue::at(dir.path().join("queue"));
12379 let questions = Questions::at(dir.path().join("questions"));
12380 let mut task = task();
12381 queue.put(&mut task).unwrap();
12382
12383 let mut task_question = ask::Question::new(
12384 task.id.clone(),
12385 crate::conduct::NODE.to_owned(),
12386 "conduct".to_owned(),
12387 "Which backend?".to_owned(),
12388 String::new(),
12389 Vec::new(),
12390 );
12391 questions.put(&mut task_question).unwrap();
12392 task.block(vec![task_question.id.clone()], None);
12393 queue.put(&mut task).unwrap();
12394
12395 let mut run_question = ask::Question::new(
12396 "20260101-000000-run1".to_owned(),
12397 "review".to_owned(),
12398 "reviewer-1".to_owned(),
12399 "Run question".to_owned(),
12400 String::new(),
12401 Vec::new(),
12402 );
12403 questions.put(&mut run_question).unwrap();
12404
12405 let mut coincidental = ask::Question::new(
12410 task.id.clone(),
12411 "review".to_owned(),
12412 "reviewer-1".to_owned(),
12413 "Unrelated review question".to_owned(),
12414 String::new(),
12415 Vec::new(),
12416 );
12417 questions.put(&mut coincidental).unwrap();
12418
12419 reconcile_task_questions(&queue, &questions);
12420 assert!(questions.get(&task_question.id).unwrap().status.open());
12421 assert!(questions.get(&run_question.id).unwrap().status.open());
12422 assert!(questions.get(&coincidental.id).unwrap().status.open());
12423
12424 task.release();
12425 queue.put(&mut task).unwrap();
12426 reconcile_task_questions(&queue, &questions);
12427 assert_eq!(
12428 questions.get(&task_question.id).unwrap().status,
12429 ask::QuestionStatus::Abandoned
12430 );
12431 assert!(
12432 questions.get(&run_question.id).unwrap().status.open(),
12433 "run questions remain the run janitor's responsibility"
12434 );
12435 assert!(
12436 questions.get(&coincidental.id).unwrap().status.open(),
12437 "a non-conductor question must not be abandoned just because its \
12438 run id coincides with a task id"
12439 );
12440 }
12441
12442 #[test]
12443 fn a_freshly_started_running_task_is_never_stalled() {
12444 let dir = tempfile::tempdir().unwrap();
12445 let mut t = task();
12446 t.start("run-1".to_owned());
12447 assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
12450 }
12451
12452 #[test]
12453 fn a_long_running_task_with_no_live_daemon_is_stalled() {
12454 let dir = tempfile::tempdir().unwrap();
12455 let mut t = task();
12456 t.start("run-1".to_owned());
12457 t.updated_at = Timestamp::now()
12458 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
12459 assert!(is_stalled(&t, dir.path(), Timestamp::now()));
12460 assert_eq!(
12461 stalled_tasks(
12462 &Queue::at(dir.path().join("q")),
12463 dir.path(),
12464 Timestamp::now()
12465 )
12466 .len(),
12467 0,
12468 "the task was never written to this queue"
12469 );
12470 }
12471
12472 #[test]
12473 fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
12474 let dir = tempfile::tempdir().unwrap();
12475 let mut t = task();
12476 t.id = "20260903-080340-0167".to_owned();
12477 t.start("20260903-080619-01c2".to_owned());
12478 t.updated_at = Timestamp::now()
12479 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
12480
12481 let mut status = Status::new();
12482 status.current = vec![Current {
12483 worker: None,
12484 task: t.id.clone(),
12485 run: "20260903-080619-01c2".to_owned(),
12486 }];
12487 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12488
12489 assert!(
12490 !is_stalled(&t, dir.path(), Timestamp::now()),
12491 "a live daemon's own heartbeat rules out stalled, however long the task has run"
12492 );
12493 }
12494
12495 fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
12499 let path = queue.path_of(id);
12500 let body = std::fs::read_to_string(&path).unwrap();
12501 let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
12502 let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
12503 v["updated_at"] = serde_json::Value::String(old.to_string());
12504 std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
12505 }
12506
12507 #[test]
12508 fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
12509 let dir = tempfile::tempdir().unwrap();
12522 let queue = Queue::at(dir.path().join("queue"));
12523 let home = dir.path().join("home");
12524
12525 let mut t = task();
12526 t.id = "20260101-000001-lock".to_owned();
12527 t.start("run-1".to_owned());
12528 queue.put(&mut t).unwrap();
12529 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
12530 std::fs::write(
12531 dir.path().join("queue").join(format!("{}.lock", t.id)),
12532 "not a pid",
12533 )
12534 .unwrap();
12535
12536 let now = Timestamp::now();
12537 assert!(
12538 reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
12539 "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
12540 and reclaim must leave the task alone"
12541 );
12542 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
12543
12544 let stalled = stalled_tasks(&queue, &home, now);
12545 assert_eq!(
12546 stalled.len(),
12547 1,
12548 "reclaim's inability to claim it yet must not hide it from the conductor"
12549 );
12550 assert_eq!(stalled[0].id, t.id);
12551 }
12552
12553 #[test]
12554 fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
12555 let dir = tempfile::tempdir().unwrap();
12556 crate::run::set_home(dir.path().join("run-home"));
12557 let queue = Queue::at(dir.path().join("queue"));
12558 let home = dir.path().join("home");
12559 let questions = Questions::at(dir.path().join("questions"));
12560
12561 let mut t = task();
12562 t.id = "20260101-000003-dead".to_owned();
12563 t.start("missing-run".to_owned());
12564 queue.put(&mut t).unwrap();
12565 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
12566
12567 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
12570 assert_eq!(
12571 stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
12572 [&t.id]
12573 );
12574 assert_eq!(
12575 reclaim_orphaned_running(&queue, 2, &Default::default()),
12576 [t.id.clone()]
12577 );
12578 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12579
12580 crate::conduct::apply(
12583 &queue,
12584 &questions,
12585 &crate::conduct::Verdict {
12586 decisions: vec![crate::conduct::Decision {
12587 id: t.id.clone(),
12588 recovery: Some(crate::conduct::Recovery::Requeue),
12589 ..crate::conduct::Decision::default()
12590 }],
12591 },
12592 )
12593 .unwrap();
12594 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
12595 }
12596
12597 #[test]
12598 fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
12599 let dir = tempfile::tempdir().unwrap();
12600 let queue = Queue::at(dir.path().join("queue"));
12601 let home = dir.path().join("home");
12602
12603 let mut fresh = task();
12604 fresh.id = "20260101-000001-aaaa".to_owned();
12605 fresh.start("run-1".to_owned());
12606 queue.put(&mut fresh).unwrap();
12607
12608 let mut old = task();
12609 old.id = "20260101-000002-bbbb".to_owned();
12610 old.start("run-2".to_owned());
12611 queue.put(&mut old).unwrap();
12612 backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
12613
12614 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
12615 assert_eq!(stalled.len(), 1);
12616 assert_eq!(stalled[0].id, old.id);
12617 }
12618
12619 #[test]
12620 fn queued_and_finished_task_views_partition_by_status() {
12621 let dir = tempfile::tempdir().unwrap();
12622 let queue = Queue::at(dir.path().join("queue"));
12623
12624 let mut queued = task();
12625 queued.id = "20260101-000001-aaaa".to_owned();
12626 queue.put(&mut queued).unwrap();
12627
12628 let mut failed = task();
12629 failed.id = "20260101-000002-bbbb".to_owned();
12630 failed.start("run-1".to_owned());
12631 failed.fail("gate red", 5);
12632 queue.put(&mut failed).unwrap();
12633
12634 let mut held = task();
12635 held.id = "20260101-000003-cccc".to_owned();
12636 held.hold_machine(None);
12637 queue.put(&mut held).unwrap();
12638
12639 let mut running = task();
12640 running.id = "20260101-000004-dddd".to_owned();
12641 running.start("run-2".to_owned());
12642 queue.put(&mut running).unwrap();
12643
12644 let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
12645 assert_eq!(queued_ids, [queued.id.clone()]);
12646
12647 let mut finished_ids: Vec<String> =
12648 finished_tasks(&queue).into_iter().map(|t| t.id).collect();
12649 finished_ids.sort_unstable();
12650 let mut want = vec![failed.id.clone(), held.id.clone()];
12651 want.sort_unstable();
12652 assert_eq!(finished_ids, want);
12653 }
12654
12655 #[test]
12656 fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
12657 for short in [false, true] {
12658 let dir = tempfile::tempdir().unwrap();
12659 let queue = Queue::at(dir.path().join("queue"));
12660 let questions = ask::Questions::at(dir.path().join("questions"));
12661 let mut running = task();
12662 running.id = "20261013-192213-feb2".into();
12663 running.start("existing-run".into());
12664 queue.put(&mut running).unwrap();
12665 let mut middle = task();
12666 middle.id = "20261013-193611-ca5b".into();
12667 middle.block(
12668 vec![if short {
12669 "feb2".into()
12670 } else {
12671 running.id.clone()
12672 }],
12673 None,
12674 );
12675 queue.put(&mut middle).unwrap();
12676 let mut waiting = task();
12677 waiting.id = "20261013-202849-ee37".into();
12678 waiting.block(
12679 vec![if short {
12680 "ca5b".into()
12681 } else {
12682 middle.id.clone()
12683 }],
12684 Some("wait for implementation".into()),
12685 );
12686 queue.put(&mut waiting).unwrap();
12687 assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
12688 let inv = crate::blockers::Inventory::load(&queue, &questions);
12689 assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
12690 assert!(inv.stuck().is_empty());
12691 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12692 assert!(report.quarantined.is_empty());
12693 assert!(report.asked.is_empty());
12694 resolve_blockers(&queue, &questions);
12695 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12696 assert!(questions.list().is_empty());
12697 running.succeed(CompletionContext::new(
12700 CompletionActor::DaemonSettle,
12701 None,
12702 dir.path(),
12703 &running,
12704 ));
12705 queue.put(&mut running).unwrap();
12706 resolve_blockers(&queue, &questions);
12707 assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
12708 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12709 middle = queue.get(&middle.id).unwrap();
12710 middle.succeed(CompletionContext::new(
12711 CompletionActor::DaemonSettle,
12712 None,
12713 dir.path(),
12714 &middle,
12715 ));
12716 queue.put(&mut middle).unwrap();
12717 resolve_blockers(&queue, &questions);
12718 let after = queue.get(&waiting.id).unwrap();
12719 assert_eq!(after.status, TaskStatus::Queued);
12720 assert!(after.blocked_by.is_empty());
12721 assert_eq!(after.instruction, waiting.instruction);
12722 }
12723 }
12724
12725 #[test]
12726 fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
12727 for future_schema in [false, true] {
12728 let name = "20261013-193611-ca5b";
12729 let mut future = task();
12730 future.id = name.into();
12731 future.schema = crate::queue::SCHEMA + 1;
12732 let contents = if future_schema {
12733 serde_json::to_string(&future).unwrap()
12734 } else {
12735 "corrupt".into()
12736 };
12737 let dir = tempfile::tempdir().unwrap();
12738 let queue = Queue::at(dir.path().join("queue"));
12739 let questions = ask::Questions::at(dir.path().join("questions"));
12740 let mut waiting = task();
12741 waiting.id = "20261013-202849-ee37".into();
12742 waiting.block(vec!["ca5b".into()], None);
12743 queue.put(&mut waiting).unwrap();
12744 std::fs::write(queue.path_of(name), contents).unwrap();
12745 assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
12746 assert!(
12747 crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
12748 );
12749 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12750 assert!(report.asked.is_empty());
12751 resolve_blockers(&queue, &questions);
12752 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12753 assert!(questions.list().is_empty());
12754 }
12755 let dir = tempfile::tempdir().unwrap();
12756 let queue = Queue::at(dir.path().join("queue"));
12757 let questions = ask::Questions::at(dir.path().join("questions"));
12758 let mut waiting = task();
12759 waiting.id = "20261013-202849-ee37".into();
12760 waiting.block(vec!["ca5b".into()], None);
12761 queue.put(&mut waiting).unwrap();
12762 let mut done = task();
12763 done.id = "20261013-193611-ca5b".into();
12764 done.succeed(CompletionContext::new(
12765 CompletionActor::Cli,
12766 None,
12767 dir.path(),
12768 &done,
12769 ));
12770 queue.put(&mut done).unwrap();
12771 std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
12774 assert!(queue.get("ca5b").is_err());
12775 assert_eq!(
12776 crate::queue::dependency(&queue, &questions, "ca5b"),
12777 crate::queue::Dependency::Ambiguous
12778 );
12779 resolve_blockers(&queue, &questions);
12780 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12781 assert!(report.asked.is_empty());
12782 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12783 assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
12784 }
12785
12786 #[test]
12787 fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
12788 for held in [false, true] {
12789 for question in [false, true] {
12790 for reference in ["ca5b", "20261013-193611-ca5b"] {
12791 let dir = tempfile::tempdir().unwrap();
12792 let queue = Queue::at(dir.path().join("queue"));
12793 let questions = ask::Questions::at(dir.path().join("questions"));
12794 let mut prerequisite = task();
12795 prerequisite.id = "20261013-193611-ca5b".into();
12796 prerequisite.start("existing-run".into());
12797 queue.put(&mut prerequisite).unwrap();
12798 let mut waiting = task();
12799 waiting.id = "20261013-202849-ee37".into();
12800 if held {
12801 waiting.hold_machine(Some("waiting for separate consent".into()));
12802 }
12803 queue.put(&mut waiting).unwrap();
12804 let reason = "Deleting saved data requires separate owner consent";
12805 crate::conduct::apply(
12806 &queue,
12807 &questions,
12808 &crate::conduct::Verdict {
12809 decisions: vec![crate::conduct::Decision {
12810 id: waiting.id.clone(),
12811 blocked_by: vec![reference.into()],
12812 question: question.then(|| "May the saved data be deleted?".into()),
12813 recovery: (!question).then_some(crate::conduct::Recovery::Hold),
12814 reason: Some(reason.into()),
12815 ..crate::conduct::Decision::default()
12816 }],
12817 },
12818 )
12819 .unwrap();
12820 let before = queue.get(&waiting.id).unwrap();
12821 if question {
12822 assert_eq!(before.status, TaskStatus::Blocked);
12823 let q = questions.get(&before.blocked_by[0]).unwrap();
12824 assert_eq!(q.summary, "May the saved data be deleted?");
12825 assert!(q.status.open());
12826 } else {
12827 assert_eq!(before.status, TaskStatus::Held);
12828 let recorded_reason = before.hold_reason.as_deref().unwrap();
12829 assert!(recorded_reason.starts_with(reason));
12830 if held {
12831 assert!(recorded_reason.contains("waiting for separate consent"));
12832 }
12833 }
12834 prerequisite.succeed(CompletionContext::new(
12835 CompletionActor::DaemonSettle,
12836 None,
12837 dir.path(),
12838 &prerequisite,
12839 ));
12840 queue.put(&mut prerequisite).unwrap();
12841 resolve_blockers(&queue, &questions);
12842 let after = queue.get(&waiting.id).unwrap();
12843 assert_eq!(after.status, before.status);
12844 assert_eq!(after.blocked_by, before.blocked_by);
12845 assert_eq!(after.hold_reason, before.hold_reason);
12846 assert_eq!(after.instruction, waiting.instruction);
12847 if question {
12848 assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
12849 }
12850 assert!(
12851 queue.next_runnable().is_none(),
12852 "dependency completion is not consent"
12853 );
12854 }
12855 }
12856 }
12857 }
12858
12859 #[test]
12860 fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
12861 let dir = tempfile::tempdir().unwrap();
12862 let queue = Queue::at(dir.path().join("queue"));
12863 let questions = ask::Questions::at(dir.path().join("questions"));
12864
12865 let mut dep = task();
12866 dep.id = "20260101-000001-dep0".to_owned();
12867 dep.succeed(CompletionContext::new(
12868 CompletionActor::DaemonSettle,
12869 None,
12870 dir.path(),
12871 &dep,
12872 ));
12873 queue.put(&mut dep).unwrap();
12874
12875 let mut still_going = task();
12876 still_going.id = "20260101-000002-dep1".to_owned();
12877 queue.put(&mut still_going).unwrap();
12878
12879 let mut blocked = task();
12880 blocked.id = "20260101-000003-main".to_owned();
12881 blocked.block(
12882 vec![dep.id.clone(), still_going.id.clone()],
12883 Some("waits on both".to_owned()),
12884 );
12885 queue.put(&mut blocked).unwrap();
12886
12887 resolve_blockers(&queue, &questions);
12888
12889 let after = queue.get(&blocked.id).unwrap();
12890 assert_eq!(
12891 after.status,
12892 TaskStatus::Blocked,
12893 "one dependency is still outstanding"
12894 );
12895 assert_eq!(after.blocked_by, [still_going.id.clone()]);
12896 }
12897
12898 #[test]
12899 fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
12900 let dir = tempfile::tempdir().unwrap();
12901 let queue = Queue::at(dir.path().join("queue"));
12902 let questions = ask::Questions::at(dir.path().join("questions"));
12903
12904 let mut q = crate::ask::Question::new(
12905 "20260101-000001-main".to_owned(),
12906 crate::conduct::NODE.to_owned(),
12907 "conduct".to_owned(),
12908 "Which backend?".to_owned(),
12909 String::new(),
12910 Vec::new(),
12911 );
12912 questions.put(&mut q).unwrap();
12913 q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
12914 .unwrap();
12915 questions.put(&mut q).unwrap();
12916
12917 let mut blocked = task();
12918 blocked.id = "20260101-000001-main".to_owned();
12919 blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
12920 queue.put(&mut blocked).unwrap();
12921
12922 resolve_blockers(&queue, &questions);
12923
12924 let after = queue.get(&blocked.id).unwrap();
12925 assert_eq!(
12926 after.status,
12927 TaskStatus::Queued,
12928 "the only blocker resolved"
12929 );
12930 assert_eq!(after.answers.len(), 1);
12931 assert_eq!(after.answers[0].question, "Which backend?");
12932 assert_eq!(after.answers[0].answer, "SQLite");
12933
12934 let instruction = instruction_for(&after);
12936 assert!(instruction.contains("Which backend?"));
12937 assert!(instruction.contains("SQLite"));
12938 }
12939
12940 #[test]
12941 fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
12942 let dir = tempfile::tempdir().unwrap();
12943 let queue = Queue::at(dir.path().join("queue"));
12944 let questions = ask::Questions::at(dir.path().join("questions"));
12945
12946 let mut q = crate::ask::Question::new(
12947 "20260101-000001-main".to_owned(),
12948 crate::conduct::NODE.to_owned(),
12949 "conduct".to_owned(),
12950 "Is the setup done?".to_owned(),
12951 String::new(),
12952 Vec::new(),
12953 );
12954 q.abandon("no answer within 60s of asking");
12955 questions.put(&mut q).unwrap();
12956
12957 let mut blocked = task();
12958 blocked.id = "20260101-000001-main".to_owned();
12959 blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
12960 queue.put(&mut blocked).unwrap();
12961
12962 resolve_blockers(&queue, &questions);
12963
12964 let after = queue.get(&blocked.id).unwrap();
12965 assert_eq!(
12966 after.status,
12967 TaskStatus::Held,
12968 "never left blocked on nothing"
12969 );
12970 assert!(!after.operator_held(), "a machine hold, for triage");
12971 assert!(
12972 after
12973 .hold_reason
12974 .as_deref()
12975 .unwrap_or_default()
12976 .contains("went unanswered")
12977 );
12978 }
12979
12980 #[test]
12981 fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
12982 let dir = tempfile::tempdir().unwrap();
12988 let queue = Queue::at(dir.path().join("queue"));
12989 let questions = ask::Questions::at(dir.path().join("questions"));
12990
12991 let mut q = crate::ask::Question::new(
12992 "20260101-000001-main".to_owned(),
12993 crate::conduct::NODE.to_owned(),
12994 "conduct".to_owned(),
12995 "How should this be handled?".to_owned(),
12996 String::new(),
12997 Vec::new(),
12998 );
12999 questions.put(&mut q).unwrap();
13000 q.answer(crate::ask::Answer::Text(
13001 "leave it held, a human will look at it later".to_owned(),
13002 ))
13003 .unwrap();
13004 questions.put(&mut q).unwrap();
13005
13006 let mut held = task();
13007 held.id = "20260101-000001-main".to_owned();
13008 held.hold_machine(Some("out of attempts".to_owned()));
13009 held.block(vec![q.id.clone()], Some("what now?".to_owned()));
13010 queue.put(&mut held).unwrap();
13011
13012 resolve_blockers(&queue, &questions);
13013
13014 let after = queue.get(&held.id).unwrap();
13015 assert_eq!(after.status, TaskStatus::Held);
13016 assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
13017 assert_eq!(
13018 after.answers[0].answer,
13019 "leave it held, a human will look at it later"
13020 );
13021 }
13022
13023 #[test]
13024 fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
13025 let dir = tempfile::tempdir().unwrap();
13026 let queue = Queue::at(dir.path().join("queue"));
13027 let questions = ask::Questions::at(dir.path().join("questions"));
13028 let mut dep = task();
13029 dep.id = "20260101-000001-gone".to_owned();
13030 queue.put(&mut dep).unwrap();
13031 let mut blocked = task();
13032 blocked.id = "20260101-000003-main".to_owned();
13033 blocked.block(vec![dep.id.clone()], None);
13034 queue.put(&mut blocked).unwrap();
13035
13036 let claim = queue.claim(&blocked.id).unwrap();
13038 queue.remove(&dep.id, false, &questions).unwrap();
13039 drop(claim);
13040 resolve_blockers(&queue, &questions);
13041
13042 let after = queue.get(&blocked.id).unwrap();
13043 assert_eq!(after.status, TaskStatus::Queued);
13044 assert!(after.blocked_by.is_empty());
13045 }
13046
13047 #[test]
13048 fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
13049 let dir = tempfile::tempdir().unwrap();
13055 let queue = Queue::at(dir.path().join("queue"));
13056 let questions = ask::Questions::at(dir.path().join("questions"));
13057
13058 let mut still_going = task();
13059 still_going.id = "20260101-000002-dep1".to_owned();
13060 queue.put(&mut still_going).unwrap();
13061
13062 let mut blocked = task();
13063 blocked.id = "20260101-000003-main".to_owned();
13064 blocked.block(
13065 vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
13066 Some("waits on both".to_owned()),
13067 );
13068 queue.put(&mut blocked).unwrap();
13069
13070 resolve_blockers(&queue, &questions);
13071
13072 let after = queue.get(&blocked.id).unwrap();
13073 assert_eq!(
13074 after.status,
13075 TaskStatus::Held,
13076 "a missing dependency must not leave the task blocked forever"
13077 );
13078 assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
13079 assert!(after.blocked_by.is_empty());
13080 let reason = after.hold_reason.as_deref().unwrap_or_default();
13081 assert!(
13082 reason.contains("20260101-000001-gone"),
13083 "the missing id must be named so an operator can tell what happened: {reason}"
13084 );
13085 assert!(
13086 reason.contains(&still_going.id),
13087 "the still-valid dependency must not silently vanish from the record: {reason}"
13088 );
13089 }
13090
13091 #[test]
13092 fn instruction_for_is_unchanged_without_any_answers() {
13093 let t = task();
13094 assert_eq!(instruction_for(&t), t.instruction);
13095 }
13096
13097 #[test]
13098 fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
13099 let dir = tempfile::tempdir().unwrap();
13100 let q = Queue::at(dir.path().join("queue"));
13101 let src = dir.path().join("shot.png");
13102 std::fs::write(&src, "x").unwrap();
13103 let mut t = task();
13104 q.attach(&mut t, &[src]).unwrap();
13105 let paths = task_attachments(&q, &t).unwrap();
13106 assert_eq!(paths.len(), 1);
13107 assert!(paths[0].is_absolute() && paths[0].is_file());
13108 std::fs::remove_file(&paths[0]).unwrap();
13109 let err = task_attachments(&q, &t).unwrap_err().to_string();
13110 assert!(err.contains("shot.png"), "{err}");
13111 }
13112
13113 #[tokio::test]
13114 async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
13115 let dir = tempfile::tempdir().unwrap();
13116 let queue_path = dir.path().join("queue");
13117 let queue = Queue::at(queue_path.clone());
13118 let mut t = task();
13119 t.source = Source::Agent {
13120 run: "originating-chat".into(),
13121 node: crate::queue::CHAT_NODE.into(),
13122 };
13123 let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
13124 stage: "config-fetch",
13125 target: "origin/main".into(),
13126 });
13127 record_config_failure(&mut t, &fetch);
13128 t.hold_machine(Some(format!("{fetch:#}")));
13129 let fetch_key = t.chat_notice_due().unwrap();
13130 t.chat_notices.push(fetch_key.clone());
13131 queue.put(&mut t).unwrap();
13132
13133 let queue = Queue::at(queue_path);
13134 let mut t = queue.get(&t.id).unwrap();
13135 let a = dir.path().join("a.toml");
13136 let b = dir.path().join("b.toml");
13137 for (path, text, new_cause) in [
13138 (&a, "[graph", true),
13139 (&a, "[verify", false),
13140 (&a, "[graph]\nimplementers = 'invalid-type'", true),
13141 (&b, "[graph]\nimplementers = 'invalid-type'", true),
13142 ] {
13143 t.release_operator("test", None);
13144 std::fs::write(path, text).unwrap();
13145 let error = Config::discover_fetched(dir.path(), Some(path))
13146 .await
13147 .unwrap_err();
13148 record_config_failure(&mut t, &error);
13149 t.hold_machine(Some(format!("{error:#}")));
13150 let due = t.chat_notice_due();
13151 assert_eq!(due.is_some(), new_cause, "{error:#}");
13152 if let Some(key) = due {
13153 assert_ne!(key, fetch_key);
13154 t.chat_notices.push(key);
13155 }
13156 }
13157 t.succeed(CompletionContext::new(
13158 CompletionActor::DaemonSettle,
13159 None,
13160 dir.path(),
13161 &t,
13162 ));
13163 assert_eq!(
13164 t.chat_notice_due(),
13165 Some(format!(
13166 "done:{}",
13167 t.completion_history.last().unwrap().occurrence
13168 ))
13169 );
13170 }
13171
13172 #[test]
13173 fn different_missing_attachments_have_distinct_persisted_notice_causes() {
13174 let dir = tempfile::tempdir().unwrap();
13175 let queue_path = dir.path().join("queue");
13176 let queue = Queue::at(queue_path.clone());
13177 let mut t = task();
13178 t.source = crate::queue::Source::Agent {
13179 run: "originating-chat".into(),
13180 node: crate::queue::CHAT_NODE.into(),
13181 };
13182 let a = dir.path().join("a.png");
13183 let b = dir.path().join("b.png");
13184 std::fs::write(&a, "a").unwrap();
13185 std::fs::write(&b, "b").unwrap();
13186 queue.attach(&mut t, &[a, b]).unwrap();
13187 let paths = task_attachments(&queue, &t).unwrap();
13188 for path in &paths {
13189 std::fs::remove_file(path).unwrap();
13190 }
13191 let missing = task_attachments(&queue, &t).unwrap_err();
13192 t.attempts += 1;
13193 let reason = missing.to_string();
13194 t.fail_startup_target("startup-attachments", missing.name, reason, 1);
13195 let first = t.chat_notice_due().expect("first attachment notice");
13196 t.chat_notices.push(first.clone());
13197 queue.put(&mut t).unwrap();
13198
13199 let queue = Queue::at(queue_path.clone());
13200 let mut t = queue.get(&t.id).unwrap();
13201 assert!(t.chat_notice_due().is_none(), "restart does not replay");
13202 t.release_operator("test", None);
13203 t.attempts += 1;
13204 let missing = task_attachments(&queue, &t).unwrap_err();
13205 t.fail_startup_target(
13206 "startup-attachments",
13207 missing.name,
13208 "same missing attachment with regenerated wording",
13209 1,
13210 );
13211 assert!(t.chat_notice_due().is_none(), "same object stays quiet");
13212
13213 std::fs::write(&paths[0], "restored").unwrap();
13214 t.release_operator("test", None);
13215 t.attempts += 1;
13216 let missing = task_attachments(&queue, &t).unwrap_err();
13217 let reason = missing.to_string();
13218 t.fail_startup_target("startup-attachments", missing.name, reason, 1);
13219 let second = t
13220 .chat_notice_due()
13221 .expect("different attachment must notify");
13222 assert_ne!(first, second);
13223 assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
13224 }
13225
13226 #[test]
13227 fn resumed_instruction_is_unchanged_without_any_answers() {
13228 let t = task();
13229 assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
13230 }
13231
13232 #[test]
13233 fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
13234 let mut t = task();
13235 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
13236 let old = t.instruction.clone();
13240
13241 let refreshed = resumed_instruction(&old, &t);
13242 assert!(refreshed.starts_with(&old), "the original text is kept");
13243 assert!(refreshed.contains("Which backend?"));
13244 assert!(refreshed.contains("SQLite"));
13245 }
13246
13247 #[test]
13248 fn resumed_instruction_keeps_an_original_answers_heading() {
13249 let mut t = task();
13250 t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
13251 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
13252
13253 let refreshed = resumed_instruction(&t.instruction, &t);
13254
13255 assert!(
13256 refreshed.starts_with(&t.instruction),
13257 "an answers heading in the original instruction is not the appended block"
13258 );
13259 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
13260 assert!(refreshed.contains("Which backend?"));
13261 assert!(refreshed.contains("SQLite"));
13262
13263 let repeated = resumed_instruction(&refreshed, &t);
13264 assert_eq!(
13265 repeated, refreshed,
13266 "only the final appended block is refreshed"
13267 );
13268 }
13269
13270 #[test]
13271 fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
13272 let mut t = task();
13273 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
13274
13275 let once = resumed_instruction(&t.instruction, &t);
13279 let twice = resumed_instruction(&once, &t);
13280 assert_eq!(once, twice);
13281 assert_eq!(once.matches("Which backend?").count(), 1);
13282
13283 t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
13285 let refreshed = resumed_instruction(&once, &t);
13286 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
13287 assert!(refreshed.contains("Which backend?"));
13288 assert!(refreshed.contains("Which cache?"));
13289 }
13290
13291 #[test]
13292 fn prepare_instruction_covers_all_three_starters() {
13293 let mut t = task();
13294 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
13295
13296 assert_eq!(
13299 prepare_instruction(&Starter::Start, None, &t),
13300 Some(instruction_for(&t))
13301 );
13302
13303 let old = t.instruction.clone();
13306 assert_eq!(
13307 prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
13308 Some(resumed_instruction(&old, &t))
13309 );
13310
13311 assert_eq!(
13315 prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
13316 None
13317 );
13318 }
13319
13320 #[test]
13321 fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
13322 assert_eq!(
13323 choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
13324 Starter::Review("magi/eba2/A".to_owned())
13325 );
13326 }
13327
13328 #[test]
13329 fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
13330 assert_eq!(
13331 choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
13332 Starter::Start,
13333 "a vanished review branch must not fall back to resuming the old run either"
13334 );
13335 }
13336
13337 #[test]
13338 fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
13339 let mut t = task();
13340 t.start("old-run".to_owned());
13341 t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
13342 t.release();
13343 let branch = t.review_branch.take();
13344 assert_eq!(
13345 choose_starter(branch.as_deref(), true, Some("old-run")),
13346 Starter::Review("magi/eba2/A".to_owned()),
13347 "a review wins over resuming the old run"
13348 );
13349 }
13350
13351 #[test]
13352 fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
13353 assert_eq!(
13354 choose_starter(None, false, Some("some-run")),
13355 Starter::Resume("some-run".to_owned())
13356 );
13357 assert_eq!(choose_starter(None, false, None), Starter::Start);
13358 }
13359
13360 #[test]
13361 fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
13362 let mut released = task();
13363 released.start("stalled-run".to_owned());
13364 released.requeue();
13365 let unfinished = (!released.fresh_start)
13366 .then(|| Some("stalled-run".to_owned()))
13367 .flatten();
13368 assert_eq!(
13369 choose_starter(None, false, unfinished.as_deref()),
13370 Starter::Start,
13371 "release keeps run history but must not resume it"
13372 );
13373 assert_eq!(released.runs, ["stalled-run"]);
13374 }
13375
13376 #[test]
13377 fn landing_hold_receipt_survives_release_retry_and_checkpoint_removal() {
13378 let dir = tempfile::tempdir().unwrap();
13379 let queue = Queue::at(dir.path().join("queue"));
13380 let mut state = run_state(RunStatus::Blocked);
13381 state.merge_decision = Some(crate::merge_decision::Decision {
13382 question: "hold-inquiry".into(),
13383 target: crate::merge_decision::Target {
13384 pr: "https://example.test/pull/1".into(),
13385 head: "reviewed-head".into(),
13386 language: "en".into(),
13387 },
13388 choice: land::HOLD.into(),
13389 closed: false,
13390 replacement_run: None,
13391 replacement_pr: None,
13392 });
13393 let mut t = task();
13394 t.start(state.id.clone());
13395 settle_and_diagnose(
13396 &mut t,
13397 Verdict {
13398 status: RunStatus::Blocked,
13399 left_pr: true,
13400 quota_hit: false,
13401 parked: false,
13402 no_viable_candidates: false,
13403 },
13404 "held",
13405 2,
13406 &state,
13407 );
13408 queue.put(&mut t).unwrap();
13409 t.release_operator("chat", None);
13410 t.edit("revised".into(), "revised instruction".into())
13411 .unwrap();
13412 queue.put(&mut t).unwrap();
13413 drop(state);
13414 assert_eq!(
13415 queue
13416 .get(&t.id)
13417 .unwrap()
13418 .decision_effects
13419 .get("hold-inquiry"),
13420 Some(&format!("decision: {}", land::HOLD))
13421 );
13422 }
13423
13424 fn stopped_public_run(status: RunStatus) -> RunState {
13425 let mut state = run_state(status);
13426 state.driver_exited = true;
13427 state.config.graph.land = true;
13428 state.config.graph.review_rounds = 1;
13429 state.reviews = vec![review_round(1)];
13430 state.merge = Some(crate::run::MergeOutcome {
13431 mode: MergeMode::Pr,
13432 ok: false,
13433 detail: "landing stopped".into(),
13434 empty: false,
13435 });
13436 state.pr = Some(crate::run::PrRecord {
13437 url: "https://example.test/pull/1".into(),
13438 number: 1,
13439 state: "open".into(),
13440 checks: "red".into(),
13441 round: 1,
13442 rounds: 1,
13443 red_at_merge: Vec::new(),
13444 });
13445 state
13446 }
13447
13448 #[test]
13449 fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
13450 for status in [RunStatus::Blocked, RunStatus::Gating] {
13451 let home = tempfile::tempdir().unwrap();
13452 let mut state = stopped_public_run(status);
13453 state.save_under(home.path()).unwrap();
13454 assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
13455 assert!(!exhausted_review_budget(&state));
13456 let mut task = held_task_with(&state.id);
13457 task.release();
13458 let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
13459 assert_eq!(
13460 choose_starter(None, false, unfinished.as_deref()),
13461 Starter::Resume(state.id.clone())
13462 );
13463 let question = action_question(&state.id, resume_action(&state.id));
13464 assert_eq!(
13465 decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
13466 state.clone()
13467 )),
13468 ActionDecision::Resume(state.id.clone())
13469 );
13470 assert_eq!(
13472 crate::resume::validate(home.path(), &state.id).unwrap().id,
13473 state.id
13474 );
13475 let queue = Queue::at(home.path().join("queue"));
13476 let mut controlled = Task::new(
13477 "resume land".into(),
13478 state.instruction.clone(),
13479 state.repo.clone(),
13480 Source::Agent {
13481 run: "talk".into(),
13482 node: crate::queue::CHAT_NODE.into(),
13483 },
13484 );
13485 controlled.runs.push(state.id.clone());
13486 controlled.hold_machine(Some("land stopped".into()));
13487 queue.put(&mut controlled).unwrap();
13488 let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
13489 assert_eq!(resumed.status, TaskStatus::Queued);
13490 assert_eq!(
13491 resumed.resume_override.unwrap().pinned_run,
13492 Some(state.id.clone())
13493 );
13494 assert_eq!(resumed.attempts, 0);
13495 }
13496 }
13497
13498 #[test]
13499 fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
13500 for review_rounds in [0, 1] {
13501 let home = tempfile::tempdir().unwrap();
13502 let mut state = run_state(RunStatus::Blocked);
13503 state.config.graph.review_rounds = review_rounds;
13504 if review_rounds > 0 {
13505 let mut review = review_round(1);
13506 review.clean = true;
13507 state.reviews = vec![review];
13508 }
13509 state.gate_ran = true;
13510 state.gate = vec![crate::run::CommandOutcome {
13511 command: "verify".into(),
13512 code: Some(1),
13513 output_tail: "gate failed after repair budget exhausted".into(),
13514 duration_ms: 0,
13515 resource_blocked: false,
13516 ..Default::default()
13517 }];
13518 state.save_under(home.path()).unwrap();
13519 assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
13520 assert!(exhausted_review_budget(&state));
13521 let mut task = held_task_with(&state.id);
13522 task.release();
13523 assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
13524 let question = action_question(&state.id, resume_action(&state.id));
13525 assert_ne!(
13526 decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
13527 state.clone()
13528 )),
13529 ActionDecision::Resume(state.id.clone())
13530 );
13531 let error = crate::resume::validate(home.path(), &state.id)
13532 .unwrap_err()
13533 .to_string();
13534 assert!(!error.contains("review budget exhausted"), "{error}");
13535 assert!(
13536 error.contains(if review_rounds == 0 {
13537 "review is disabled"
13538 } else {
13539 "gate already ran"
13540 }),
13541 "{error}"
13542 );
13543
13544 state.gate_ran = false;
13546 state.gate.clear();
13547 assert!(!exhausted_review_budget(&state));
13548 assert_eq!(
13549 unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
13550 Some(state.id)
13551 );
13552 }
13553 }
13554
13555 #[test]
13556 fn sequencer_resource_resume_keeps_the_reserved_run_after_review_exhaustion() {
13557 let home = tempfile::tempdir().unwrap();
13558 let mut state = run_state(RunStatus::Blocked);
13559 state.config.graph.review_rounds = 1;
13560 let mut unresolved = review_round(1);
13561 unresolved.blocking = 1;
13562 unresolved.e2e.push(crate::run::CommandOutcome {
13563 command: "verify".into(),
13564 code: Some(1),
13565 output_tail: "previous verification failed".into(),
13566 duration_ms: 0,
13567 resource_blocked: false,
13568 ..Default::default()
13569 });
13570 state.reviews.push(unresolved);
13571 state.base_sync = Some(crate::run::BaseSync {
13572 tip: "base".into(),
13573 behind: 1,
13574 attempts: 0,
13575 conflict: None,
13576 already_in: None,
13577 });
13578 state.reserve_base_operation("winner", "base");
13579 state.resource_block = Some(crate::run::ResourceBlock {
13580 cause: crate::run::ResourceBlockCause::Other,
13581 node: "rebase".into(),
13582 kind: crate::rebase::SEQUENCER_INFRASTRUCTURE.into(),
13583 detail: "recording exec failed".into(),
13584 at: jiff::Timestamp::now(),
13585 });
13586 state.save_under(home.path()).unwrap();
13587 assert_eq!(
13588 crate::resume::validate(home.path(), &state.id).unwrap().id,
13589 state.id
13590 );
13591 assert_eq!(
13592 crate::repair_budget::legacy::classify(&state, "winner", "base").class,
13593 crate::repair_budget::legacy::Class::SequencerInfrastructure
13594 );
13595 state.finish_base_operation(None);
13596 state.save_under(home.path()).unwrap();
13597 assert!(crate::resume::validate(home.path(), &state.id).is_err());
13598 }
13599
13600 #[test]
13601 fn resource_blocked_verification_resumes_the_same_run() {
13602 for (kind, stage) in [
13603 ("cache", "clean"),
13604 ("coordination", "clean"),
13605 ("cache", "review-e2e"),
13606 ("coordination", "no-reviews"),
13607 ("coordination", "handoff"),
13608 ] {
13609 let home = tempfile::tempdir().unwrap();
13610 let mut state = run_state(RunStatus::Blocked);
13611 state.config.graph.review_rounds = 1;
13612 let mut review = review_round(1);
13613 review.clean = true;
13614 state.reviews = vec![review];
13615 if stage == "review-e2e" {
13616 let review = &mut state.reviews[0];
13617 review.clean = false;
13618 review.blocking = 1;
13619 review.e2e = vec![crate::run::CommandOutcome {
13620 command: "verify".into(),
13621 code: None,
13622 output_tail: "resource wait expired".into(),
13623 duration_ms: 0,
13624 resource_blocked: true,
13625 ..Default::default()
13626 }];
13627 } else if stage == "no-reviews" {
13628 state.config.graph.review_rounds = 0;
13629 state.reviews.clear();
13630 } else if stage == "handoff" {
13631 let review = &mut state.reviews[0];
13634 review.clean = false;
13635 review.blocking = 1;
13636 review.e2e = vec![crate::run::CommandOutcome {
13637 command: "verify".into(),
13638 code: Some(0),
13639 output_tail: String::new(),
13640 duration_ms: 0,
13641 resource_blocked: false,
13642 ..Default::default()
13643 }];
13644 }
13645 state.gate_ran = false;
13646 state.resource_block = Some(crate::run::ResourceBlock {
13647 cause: crate::run::ResourceBlockCause::Other,
13648 node: if stage == "review-e2e" {
13649 "review"
13650 } else {
13651 "gate"
13652 }
13653 .into(),
13654 kind: kind.into(),
13655 detail: "resource wait expired".into(),
13656 at: jiff::Timestamp::now(),
13657 });
13658 state.save_under(home.path()).unwrap();
13659 assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
13660 assert!(!exhausted_review_budget(&state));
13661 let mut task = held_task_with(&state.id);
13662 task.release();
13663 let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
13664 assert_eq!(
13665 choose_starter(None, false, unfinished.as_deref()),
13666 Starter::Resume(state.id.clone())
13667 );
13668 let question = action_question(&state.id, resume_action(&state.id));
13669 assert_eq!(
13670 decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
13671 state.clone()
13672 )),
13673 ActionDecision::Resume(state.id.clone())
13674 );
13675 assert_eq!(
13676 crate::resume::validate(home.path(), &state.id).unwrap().id,
13677 state.id
13678 );
13679 let queue = Queue::at(home.path().join("queue"));
13680 let mut controlled = Task::new(
13681 "resume verification".into(),
13682 state.instruction.clone(),
13683 state.repo.clone(),
13684 Source::Agent {
13685 run: "talk".into(),
13686 node: crate::queue::CHAT_NODE.into(),
13687 },
13688 );
13689 controlled.runs.push(state.id.clone());
13690 controlled.hold_machine(Some("verification resource unavailable".into()));
13691 queue.put(&mut controlled).unwrap();
13692 let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
13693 assert_eq!(resumed.status, TaskStatus::Queued);
13694 assert_eq!(
13695 resumed.resume_override.unwrap().pinned_run,
13696 Some(state.id.clone())
13697 );
13698 assert_eq!(resumed.attempts, 0);
13699
13700 state.config.graph.review_rounds = 1;
13702 let mut unresolved = review_round(1);
13703 unresolved.blocking = 1;
13704 state.reviews = vec![unresolved];
13705 state.resource_block = None;
13706 state.save_under(home.path()).unwrap();
13707 assert!(exhausted_review_budget(&state));
13708 assert!(crate::resume::validate(home.path(), &state.id).is_err());
13709 }
13710 }
13711
13712 #[tokio::test]
13713 async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
13714 if !crate::standalone_test(
13715 "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
13716 ) {
13717 return;
13718 }
13719 let home = tempfile::tempdir().unwrap();
13720 let mut owner = stopped_public_run(RunStatus::Blocked);
13721 owner.save_under(home.path()).unwrap();
13722 let history = vec![owner.id.clone()];
13723 let repo = owner.repo.clone();
13724 let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
13725 let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
13726 let initial =
13727 std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
13728 assert!(
13729 initial.is_pending(),
13730 "a busy record must not hold or resume the task"
13731 );
13732 owner.retired_to = Some("20260101-000001-bbbb".into());
13733 owner.save_under(home.path()).unwrap();
13734 drop(lock);
13735 let result = tokio::time::timeout(Duration::from_secs(10), lookup)
13736 .await
13737 .expect("ownership lock released")
13738 .expect("read settled owner");
13739 assert!(
13740 result.is_none(),
13741 "the retired owner must not be resumed from a stale read"
13742 );
13743 }
13744
13745 #[tokio::test]
13746 async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
13747 if !crate::standalone_test(
13748 "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
13749 ) {
13750 return;
13751 }
13752 let home = tempfile::tempdir().unwrap();
13753 let mut owner = stopped_public_run(RunStatus::Blocked);
13754 let repo = tempfile::tempdir().unwrap();
13755 crate::git::git(repo.path(), &["init"]).await.unwrap();
13756 owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
13757 owner.id = "20260101-000000-aaaa".into();
13758 owner.save_under(home.path()).unwrap();
13759 let mut successor = run_state(RunStatus::Blocked);
13760 successor.id = "20260101-000001-bbbb".into();
13761 successor.save_under(home.path()).unwrap();
13762 let runs = vec![owner.id.clone(), successor.id.clone()];
13763 assert_eq!(
13764 public_resume_owner(home.path(), &runs, &owner.repo)
13765 .await
13766 .unwrap()
13767 .unwrap()
13768 .id,
13769 owner.id
13770 );
13771 let subdir = owner.repo.join("nested");
13772 std::fs::create_dir(&subdir).unwrap();
13773 assert_eq!(
13774 public_resume_owner(home.path(), &runs, &subdir)
13775 .await
13776 .unwrap()
13777 .unwrap()
13778 .id,
13779 owner.id
13780 );
13781 #[cfg(unix)]
13782 {
13783 let alias = home.path().join("repo-alias");
13784 std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
13785 assert_eq!(
13786 public_resume_owner(home.path(), &runs, &alias.join("nested"))
13787 .await
13788 .unwrap()
13789 .unwrap()
13790 .id,
13791 owner.id
13792 );
13793 }
13794 let different = tempfile::tempdir().unwrap();
13795 crate::git::git(different.path(), &["init"]).await.unwrap();
13796 assert!(
13797 public_resume_owner(home.path(), &runs, different.path())
13798 .await
13799 .is_err()
13800 );
13801 std::fs::remove_file(
13802 home.path()
13803 .join("runs")
13804 .join(&successor.id)
13805 .join("run.json"),
13806 )
13807 .unwrap();
13808 assert!(
13809 public_resume_owner(home.path(), &runs, &owner.repo)
13810 .await
13811 .is_err()
13812 );
13813 }
13814
13815 #[test]
13816 fn an_ordinary_release_keeps_a_resumable_run_available() {
13817 let mut released = task();
13818 released.start("stalled-run".to_owned());
13819 released.release();
13820 let unfinished = (!released.fresh_start)
13821 .then(|| Some("stalled-run".to_owned()))
13822 .flatten();
13823 assert_eq!(
13824 choose_starter(None, false, unfinished.as_deref()),
13825 Starter::Resume("stalled-run".to_owned()),
13826 "manual release must preserve the normal resume path"
13827 );
13828 }
13829
13830 #[test]
13831 fn resume_refusals_explain_admission_without_changing_task_or_run() {
13832 use crate::handover::{ResumeRefusal, resume_refusal_under};
13833 let home = tempfile::tempdir().unwrap();
13834 let mut exhausted = run_state(RunStatus::Blocked);
13835 exhausted.driver_exited = true;
13836 exhausted.config.graph.review_rounds = 3;
13837 exhausted.reviews = (1..=3).map(review_round).collect();
13838 for refusal in [
13839 ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
13840 ResumeRefusal::Status(RunStatus::Ready),
13841 ResumeRefusal::Released("20261022-000000-aaaa".into()),
13842 ResumeRefusal::Retired("retirement-successor".into()),
13843 ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
13844 ] {
13845 let mut state = exhausted.clone();
13846 let expected = match refusal {
13847 ResumeRefusal::Status(_) => {
13848 state.status = RunStatus::Ready;
13849 "status `ready`"
13850 }
13851 ResumeRefusal::Released(ref target) => {
13852 state.released_to = Some(target.clone());
13853 "execution was released"
13854 }
13855 ResumeRefusal::Retired(ref target) => {
13856 state.retired_to = Some(target.clone());
13857 "execution was retired"
13858 }
13859 ResumeRefusal::OwnershipTransferred(ref target) => {
13860 state.pr_taken_over_by = Some(target.clone());
13861 "PR ownership was transferred"
13862 }
13863 _ => "review budget exhausted (3/3 rounds used)",
13864 };
13865 assert_eq!(
13866 resume_refusal_under(&state, Some(home.path())),
13867 Some(refusal.clone())
13868 );
13869 assert_eq!(
13870 refusal.successor(),
13871 state
13872 .released_to
13873 .as_deref()
13874 .or(state.retired_to.as_deref())
13875 .or(state.pr_taken_over_by.as_deref())
13876 );
13877 state.save_under(home.path()).unwrap();
13878 let queue = Queue::at(home.path().join("queue"));
13879 let mut task = Task::new(
13880 "retained implementation".into(),
13881 state.instruction.clone(),
13882 state.repo.clone(),
13883 Source::Agent {
13884 run: "talk".into(),
13885 node: crate::queue::CHAT_NODE.into(),
13886 },
13887 );
13888 task.runs.push(state.id.clone());
13889 task.hold_machine(Some("stopped".into()));
13890 queue.put(&mut task).unwrap();
13891 let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
13892 let before_run = serde_json::to_value(&state).unwrap();
13893 let error = crate::chat_control::resume(&queue, home.path(), &state.id)
13894 .unwrap_err()
13895 .to_string();
13896 assert!(error.contains(expected), "{error}");
13897 assert!(!error.contains("only a stalled or blocked"), "{error}");
13898 if matches!(refusal, ResumeRefusal::Status(_)) {
13899 assert!(
13900 error.contains("is final; there is nothing left to resume"),
13901 "{error}"
13902 );
13903 }
13904 if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
13905 assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
13906 assert!(error.contains("review-only successor with a new review budget"));
13907 assert!(error.contains("does not resume this run"));
13908 }
13909 for target in [
13910 &state.released_to,
13911 &state.retired_to,
13912 &state.pr_taken_over_by,
13913 ]
13914 .into_iter()
13915 .flatten()
13916 {
13917 let short = if state.retired_to.as_ref() == Some(target) {
13918 target.as_str()
13919 } else {
13920 crate::run::short_of(target)
13921 };
13922 assert!(
13923 error.contains(&format!("run {short}; inspect `magi show {short}`")),
13924 "{error}"
13925 );
13926 if short != target {
13927 assert!(!error.contains(target), "full successor id leaked: {error}");
13928 }
13929 }
13930 assert_eq!(
13931 serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
13932 before_task
13933 );
13934 assert_eq!(
13935 serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
13936 .unwrap(),
13937 before_run
13938 );
13939 let question = action_question(&state.id, resume_action(&state.id));
13940 for phrases in [&PHRASES_EN, &PHRASES_JA] {
13941 let decision = decide_action(home.path(), &task, &question, phrases, |id| {
13942 RunState::load_under(id, home.path())
13943 });
13944 let ActionDecision::Refuse(detail) = decision else {
13945 panic!(
13946 "refusal expected: decision={decision:?}, refusal={refusal:?}, run={}, home={}",
13947 state.id,
13948 home.path().display()
13949 );
13950 };
13951 assert!(detail.contains(expected), "{detail}");
13952 }
13953 }
13954 exhausted.status = RunStatus::Ready;
13956 exhausted.released_to = Some("released".into());
13957 exhausted.retired_to = Some("retired".into());
13958 exhausted.pr_taken_over_by = Some("owner".into());
13959 let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
13960 assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
13961 let detail = reason.diagnostic(&exhausted);
13962 for target in ["released", "retired", "owner"] {
13963 assert!(detail.contains(&format!("magi show {target}")));
13964 }
13965 }
13966
13967 #[test]
13968 fn resume_action_ignores_question_checkpoints_in_another_home() {
13969 crate::run::pin_test_home();
13970 let home = tempfile::tempdir().unwrap();
13971 let mut state = run_state(RunStatus::Blocked);
13972 state.id = format!(
13975 "resume-context-{}",
13976 home.path().file_name().unwrap().to_str().unwrap()
13977 );
13978 state.driver_exited = true;
13979 state.config.graph.review_rounds = 1;
13980 state.reviews = vec![review_round(1)];
13981 state.save_under(home.path()).unwrap();
13982 let task = held_task_with(&state.id);
13983 let answer = action_question(&state.id, resume_action(&state.id));
13984 let mut checkpoint = approval_question(&state.id);
13985 let foreign = Questions::open();
13986 foreign.put(&mut checkpoint).unwrap();
13987 let refusal = crate::handover::resume_refusal_under(&state, Some(home.path()));
13988 let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
13989 RunState::load_under(id, home.path())
13990 });
13991 let matching: Vec<_> = foreign
13992 .list()
13993 .into_iter()
13994 .filter(|q| q.run == state.id && q.status.open())
13995 .collect();
13996 std::fs::remove_file(foreign.path_of(&checkpoint.id)).unwrap();
13997 assert!(
13998 matches!(decision, ActionDecision::Refuse(_)),
13999 "decision={decision:?}, refusal={refusal:?}, run={}, home={}, foreign_home={}, matching={matching:?}",
14000 state.id,
14001 home.path().display(),
14002 crate::run::test_home().display()
14003 );
14004 assert_eq!(
14005 refusal,
14006 Some(crate::handover::ResumeRefusal::ReviewBudget { used: 1, limit: 1 })
14007 );
14008 let local = Questions::at(home.path().join("questions"));
14009 for status in [
14010 ask::QuestionStatus::Open,
14011 ask::QuestionStatus::Answered,
14012 ask::QuestionStatus::Abandoned,
14013 ] {
14014 let mut question = checkpoint.clone();
14015 match status {
14016 ask::QuestionStatus::Open => {}
14017 ask::QuestionStatus::Answered => {
14018 question
14019 .answer(ask::Answer::Choice(question.choices[0].clone()))
14020 .unwrap();
14021 }
14022 ask::QuestionStatus::Abandoned => question.abandon("fixture closed"),
14023 }
14024 local.put(&mut question).unwrap();
14025 let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
14026 RunState::load_under(id, home.path())
14027 });
14028 if status.open() {
14029 assert_eq!(decision, ActionDecision::Resume(state.id.clone()));
14030 } else {
14031 assert!(
14032 matches!(decision, ActionDecision::Refuse(ref detail) if detail.contains("review budget exhausted")),
14033 "status={status:?}, decision={decision:?}"
14034 );
14035 }
14036 }
14037 }
14038
14039 #[test]
14040 fn resume_action_checks_the_driver_lease_in_the_supplied_home() {
14041 let home = tempfile::tempdir().unwrap();
14042 let mut state = run_state(RunStatus::Stalled);
14043 state.id = format!(
14044 "resume-driver-{}",
14045 home.path().file_name().unwrap().to_str().unwrap()
14046 );
14047 state.driver_claimed = Some(false);
14048 state.save_under(home.path()).unwrap();
14049 let task = held_task_with(&state.id);
14050 let question = action_question(&state.id, resume_action(&state.id));
14051 let decide = || {
14052 decide_action(home.path(), &task, &question, &PHRASES_EN, |id| {
14053 RunState::load_under(id, home.path())
14054 })
14055 };
14056 let lease = crate::driver::maintenance(home.path(), &state.id).unwrap();
14057 assert_eq!(state.liveness_under(home.path(), false), Liveness::Live);
14058 assert_eq!(
14059 decide(),
14060 ActionDecision::Refuse("run already has a live driver".into())
14061 );
14062 drop(lease);
14063 assert_eq!(decide(), ActionDecision::Resume(state.id.clone()));
14064 }
14065
14066 #[test]
14067 fn resume_checkpoint_admission_uses_the_supplied_question_store() {
14068 let home = tempfile::tempdir().unwrap();
14069 let mut state = run_state(RunStatus::Blocked);
14070 state.driver_exited = true;
14071 state.config.graph.review_rounds = 1;
14072 state.reviews = vec![review_round(1)];
14073 assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
14074 for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
14075 let mut saved = state.clone();
14076 match checkpoint {
14077 "publication" => saved.pr_publication_pending = true,
14078 "approval" => {
14079 saved.land_approval = Some(crate::run::LandApproval {
14080 question: "approval".into(),
14081 head: "head".into(),
14082 })
14083 }
14084 "armed" => saved.land_armed_head = Some("head".into()),
14085 "landing" => saved.status = RunStatus::Landing,
14086 _ => {
14087 let mut question = ask::Question::new(
14088 saved.id.clone(),
14089 "review".into(),
14090 "review-1".into(),
14091 "continue?".into(),
14092 String::new(),
14093 vec!["continue".into()],
14094 );
14095 ask::Questions::at(home.path().join("questions"))
14096 .put(&mut question)
14097 .unwrap();
14098 }
14099 }
14100 saved.save_under(home.path()).unwrap();
14101 assert!(
14102 crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
14103 "{checkpoint}"
14104 );
14105 assert!(
14106 crate::resume::validate(home.path(), &saved.id).is_ok(),
14107 "{checkpoint}"
14108 );
14109 }
14110 }
14111
14112 #[test]
14113 fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
14114 let mut state = run_state(RunStatus::Blocked);
14115 state.config.graph.review_rounds = 3;
14116 state.reviews = vec![review_round(1), review_round(2), review_round(3)];
14117 assert!(exhausted_review_budget(&state));
14118
14119 state.reviews.pop();
14121 assert!(!exhausted_review_budget(&state));
14122
14123 let mut stalled = run_state(RunStatus::Stalled);
14126 stalled.config.graph.review_rounds = 1;
14127 stalled.reviews = vec![review_round(1)];
14128 assert!(!exhausted_review_budget(&stalled));
14129 }
14130
14131 fn review_round(round: usize) -> crate::run::ReviewRound {
14132 crate::run::ReviewRound {
14133 round,
14134 head: "deadbeef".to_owned(),
14135 verified_head: None,
14136 verified_at: None,
14137 reviews: Vec::new(),
14138 e2e: Vec::new(),
14139 verify_retried: false,
14140 e2e_deferred: false,
14141 e2e_defer_reason: None,
14142 fix: None,
14143 blocking: 0,
14144 answered: 1,
14145 expected: 1,
14146 clean: false,
14147 progressed: true,
14148 vote_split: false,
14149 reconsideration: Vec::new(),
14150 verdict: None,
14151 }
14152 }
14153
14154 #[test]
14155 fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
14156 let mut run = RunState::new(
14157 PathBuf::from("/repo"),
14158 "main".to_owned(),
14159 "abc1234def".to_owned(),
14160 "add retries".to_owned(),
14161 Config::default(),
14162 );
14163 run.status = RunStatus::Judging;
14164 run.parked = true;
14165 let mut task = Task::new(
14166 "add retries".to_owned(),
14167 "add retries".to_owned(),
14168 PathBuf::from("/repo"),
14169 crate::queue::Source::Human,
14170 );
14171 task.status = TaskStatus::Failed;
14172 task.runs = vec![run.id.clone()];
14173 let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
14174 assert!(with(&task, &run), "parked after judging is the case");
14175 let mut parked_task = task.clone();
14176 parked_task.status = TaskStatus::Parked;
14177 assert!(with(&parked_task, &run), "the Parked status is the case");
14178
14179 let mut not_parked = run.clone();
14180 not_parked.parked = false;
14181 not_parked.status = RunStatus::Stalled;
14182 assert!(!with(&task, ¬_parked), "a stall is the conductor's");
14183
14184 let mut fresh = task.clone();
14185 fresh.fresh_start = true;
14186 assert!(!with(&fresh, &run), "a requeue asked for a new competition");
14187
14188 let mut review = task.clone();
14189 review.review_branch = Some("magi/x/A".to_owned());
14190 assert!(!with(&review, &run), "review is ranked before resume");
14191
14192 let mut held = task.clone();
14193 held.status = TaskStatus::Held;
14194 assert!(!with(&held, &run), "a hold stays visible to the conductor");
14195
14196 let mut released = run.clone();
14197 released.released_to = Some("20260901-000000-new1".to_owned());
14198 assert!(!with(&task, &released), "nothing left to resume into");
14199
14200 assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
14201 "unreadable"
14202 )));
14203 }
14204
14205 #[test]
14206 fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
14207 let mut released = RunState::new(
14208 PathBuf::from("/repo"),
14209 "main".to_owned(),
14210 "abc1234def".to_owned(),
14211 "add retries".to_owned(),
14212 Config::default(),
14213 );
14214 released.status = RunStatus::Blocked;
14215 assert_eq!(
14216 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
14217 Some(released.id.clone())
14218 );
14219 released.released_to = Some("20260901-000000-new1".to_owned());
14220 assert_eq!(
14221 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
14222 None,
14223 "there is nothing left to resume it into"
14224 );
14225 }
14226
14227 #[test]
14228 fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
14229 let mut exhausted = RunState::new(
14238 PathBuf::from("/repo"),
14239 "main".to_owned(),
14240 "abc1234def".to_owned(),
14241 "add retries".to_owned(),
14242 Config::default(),
14243 );
14244 exhausted.status = RunStatus::Blocked;
14245 exhausted.config.graph.review_rounds = 1;
14246 exhausted.reviews = vec![review_round(1)];
14247
14248 assert_eq!(
14249 unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
14250 None,
14251 "an exhausted `Blocked` run must not be offered as resumable"
14252 );
14253
14254 let mut has_budget_left = RunState::new(
14257 PathBuf::from("/repo"),
14258 "main".to_owned(),
14259 "abc1234def".to_owned(),
14260 "add retries".to_owned(),
14261 Config::default(),
14262 );
14263 has_budget_left.status = RunStatus::Blocked;
14264 has_budget_left.config.graph.review_rounds = 3;
14265 has_budget_left.reviews = vec![review_round(1)];
14266
14267 assert_eq!(
14268 unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
14269 Ok(has_budget_left.clone())
14270 }),
14271 Some(has_budget_left.id.clone())
14272 );
14273 }
14274
14275 #[test]
14276 fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
14277 let mut run = RunState::new(
14278 PathBuf::from("/repo"),
14279 "main".to_owned(),
14280 "abc1234def".to_owned(),
14281 "add retries".to_owned(),
14282 Config::default(),
14283 );
14284 run.status = RunStatus::Blocked;
14285 run.config.graph.review_rounds = 1;
14286 run.reviews = vec![review_round(1)];
14287 run.pr_publication_pending = true;
14288 assert_eq!(
14289 unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
14290 Some(run.id.clone()),
14291 "a spent review budget must not turn a failed publication into a re-competition"
14292 );
14293 }
14294
14295 #[test]
14296 fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
14297 let mut task = Task::new(
14298 "recover work".into(),
14299 "recover work".into(),
14300 PathBuf::from("/repo"),
14301 crate::queue::Source::Human,
14302 );
14303 let mut history = std::collections::BTreeMap::new();
14304 for index in 0..8 {
14305 let mut run = run_state(RunStatus::Blocked);
14306 run.id = format!("20260101-000000-{index:04}");
14307 run.base_commit = format!("upstream-{index}");
14308 if index > 0 {
14310 run.candidates.clear();
14311 }
14312 task.runs.extend([run.id.clone(), run.id.clone()]);
14313 history.insert(run.id.clone(), run);
14314 task.requeue();
14315 }
14316 let check = |task: &Task, starter: &Starter, limit| {
14317 retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
14318 };
14319 assert!(
14320 check(&task, &Starter::Start, 8)
14321 .unwrap()
14322 .contains("8 unretired")
14323 );
14324 assert!(check(&task, &Starter::Start, 9).is_none());
14325 assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
14326 task.release_operator("owner", None);
14327 assert_eq!(task.attempts, 0);
14328 let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
14329 assert!(check(&restored, &Starter::Start, 8).is_some());
14330 assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
14331 assert!(check(&restored, &Starter::Start, 0).is_none());
14332 }
14333
14334 #[test]
14335 fn retained_attempt_bound_includes_failed_startups_without_execution_history() {
14336 let tmp = tempfile::tempdir().unwrap();
14337 let mut task = Task::new(
14338 "recover selected PR".into(),
14339 "preserve implementation".into(),
14340 tmp.path().join("repo"),
14341 crate::queue::Source::Human,
14342 );
14343 let mut failed = run_state(RunStatus::Failed);
14344 failed.id = "20260101-000000-fail".into();
14345 failed.candidates.clear();
14346 failed.prep_complete = Some(false);
14347 failed.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
14348 failed.startup = Some(crate::run::Startup {
14349 kind: "pr-recovery".into(),
14350 branch: Some("selected-public-head".into()),
14351 stage: "worktree-setup".into(),
14352 complete: false,
14353 failure: Some("setup modified a tracked file and failed".into()),
14354 });
14355 let worktree = failed.worktree_root().join("under-review");
14358 std::fs::create_dir_all(&worktree).unwrap();
14359 let retained_edit = worktree.join("implementation");
14360 std::fs::write(&retained_edit, "retained setup edit").unwrap();
14361 task.record_startup_failure(crate::run::StartupFailure {
14362 run: failed.id.clone(),
14363 stage: "worktree-setup".into(),
14364 });
14365 let task: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
14366 assert!(task.runs.is_empty() && task.passes.is_empty());
14367 assert_eq!(task.attempts, 0);
14368 let starter = Starter::Review("selected-public-head".into());
14369 assert!(
14370 retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone()))
14371 .unwrap()
14372 .contains("1 unretired")
14373 );
14374 assert!(retained_attempt_hold(&task, &starter, 2, |_| Ok(failed.clone())).is_none());
14375 assert!(
14376 retained_attempt_hold(&task, &starter, 2, |_| anyhow::bail!("unreadable"))
14377 .unwrap()
14378 .contains("Cannot verify")
14379 );
14380 let mut mixed = task.clone();
14382 mixed.runs.push(failed.id.clone());
14383 mixed
14384 .startup_failures
14385 .push(task.startup_failures[0].clone());
14386 assert!(retained_attempt_hold(&mixed, &starter, 2, |_| Ok(failed.clone())).is_none());
14387 failed.retired_to = Some("verified-recovery-owner".into());
14388 assert!(retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone())).is_none());
14389 assert!(
14390 retained_attempt_hold(&task, &Starter::Resume(failed.id.clone()), 1, |_| {
14391 panic!("resuming the existing owner must not allocate a new attempt")
14392 })
14393 .is_none()
14394 );
14395 assert_eq!(
14396 std::fs::read_to_string(retained_edit).unwrap(),
14397 "retained setup edit"
14398 );
14399 assert!(task.runs.is_empty() && task.passes.is_empty());
14400 assert_eq!(task.attempts, 0);
14401 }
14402
14403 #[test]
14404 fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
14405 let mut task = Task::new(
14406 "recover work".into(),
14407 "recover work".into(),
14408 PathBuf::from("/repo"),
14409 crate::queue::Source::Human,
14410 );
14411 let mut run = run_state(RunStatus::Superseded);
14412 run.candidates.clear();
14413 task.runs.push(run.id.clone());
14414 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
14415 run.retired_to = Some("authority".into());
14416 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
14417 run.retired_to = None;
14418 run.released_to = Some("authority".into());
14419 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
14420 assert!(
14421 retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
14422 .unwrap()
14423 .contains("Cannot verify")
14424 );
14425 assert!(
14427 retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
14428 panic!("resume must not load historical attempts")
14429 })
14430 .is_none()
14431 );
14432 }
14433
14434 #[test]
14435 fn retired_resume_requires_a_valid_same_repository_authority() {
14436 let mut source = run_state(RunStatus::Blocked);
14437 let mut empty = run_state(RunStatus::Blocked);
14438 empty.retired_to = Some(source.id.clone());
14439 let runs = vec![source.id.clone(), empty.id.clone()];
14440 let resolve = |source: &RunState, empty: &RunState| {
14441 unfinished_run_with(&runs, "fixture", |id| {
14442 if id == source.id {
14443 Ok(source.clone())
14444 } else if id == empty.id {
14445 Ok(empty.clone())
14446 } else {
14447 bail!("unreadable authority")
14448 }
14449 })
14450 };
14451 assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
14452 assert_eq!(
14453 choose_starter(None, false, resolve(&source, &empty).as_deref()),
14454 Starter::Resume(source.id.clone())
14455 );
14456 source.retired_to = Some(empty.id.clone());
14457 assert!(
14458 resolve(&source, &empty).is_none(),
14459 "cycles do not revive obsolete runs"
14460 );
14461 source.retired_to = None;
14462 source.repo = PathBuf::from("/another-repository");
14463 assert!(resolve(&source, &empty).is_none());
14464 source.repo = empty.repo.clone();
14465 source.released_to = Some("later".into());
14466 assert!(resolve(&source, &empty).is_none());
14467 empty.retired_to = Some("unlisted-run".into());
14468 assert!(resolve(&source, &empty).is_none());
14469 }
14470
14471 #[test]
14472 fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
14473 let mut older_stalled = RunState::new(
14481 PathBuf::from("/repo"),
14482 "main".to_owned(),
14483 "abc1234def".to_owned(),
14484 "add retries".to_owned(),
14485 Config::default(),
14486 );
14487 older_stalled.status = RunStatus::Stalled;
14488
14489 let mut newest_exhausted = RunState::new(
14490 PathBuf::from("/repo"),
14491 "main".to_owned(),
14492 "abc1234def".to_owned(),
14493 "add retries".to_owned(),
14494 Config::default(),
14495 );
14496 newest_exhausted.status = RunStatus::Blocked;
14497 newest_exhausted.config.graph.review_rounds = 1;
14498 newest_exhausted.reviews = vec![review_round(1)];
14499
14500 assert_eq!(
14501 unfinished_run_with(
14502 &[older_stalled.id.clone(), newest_exhausted.id.clone()],
14503 "t",
14504 |_| Ok(newest_exhausted.clone())
14505 ),
14506 None,
14507 "the newest run is exhausted, so nothing here is worth resuming - \
14508 least of all the older, already-superseded run"
14509 );
14510 }
14511
14512 #[test]
14513 fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
14514 assert_eq!(
14515 unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
14516 Err(anyhow::anyhow!("fixture is absent"))
14517 }),
14518 None
14519 );
14520 }
14521
14522 fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
14523 let mut q = ask::Question::new(
14524 run.to_owned(),
14525 "implement".to_owned(),
14526 "impl-A".to_owned(),
14527 "continue?".to_owned(),
14528 String::new(),
14529 vec!["resume で続行する".to_owned(), "other".to_owned()],
14530 );
14531 q.actions.insert("resume で続行する".to_owned(), action);
14532 q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
14533 .unwrap();
14534 q
14535 }
14536
14537 fn held_task_with(run: &str) -> Task {
14538 let mut t = task();
14539 t.runs = vec![run.to_owned()];
14540 t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
14541 t
14542 }
14543
14544 fn resume_action(run: &str) -> ask::ChoiceAction {
14545 ask::ChoiceAction::Resume { run: run.into() }
14546 }
14547
14548 #[test]
14549 fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
14550 let home = crate::run::test_home();
14551 for parked in [false, true] {
14552 let mut t = task();
14553 t.start("A".into());
14554 t.start("B".into());
14555 assert_eq!(t.runs, vec!["A", "B"]);
14556 t.start("A".into());
14557 let mut resumed = run_state(RunStatus::Blocked);
14558 resumed.id = "A".into();
14559 resumed.parked = parked;
14560 resumed.driver_exited = true;
14561 t.hold_machine(Some("resumed run stopped".into()));
14562 let q = action_question("A", resume_action("A"));
14563 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
14564 assert_eq!(
14565 decide_action(&home, &t, &q, &PHRASES_EN, |id| {
14566 assert_eq!(id, "A");
14567 Ok(resumed.clone())
14568 }),
14569 ActionDecision::Resume("A".into())
14570 );
14571 assert_eq!(
14572 action_standing(&t, &action_question("B", resume_action("B"))),
14573 ActionStanding::Stale
14574 );
14575 t.release_operator("cli", None);
14576 let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
14577 assert_eq!(id, "A");
14578 Ok(resumed.clone())
14579 });
14580 assert_eq!(
14581 choose_starter(None, false, unfinished.as_deref()),
14582 Starter::Resume("A".into())
14583 );
14584 assert_eq!(t.runs, vec!["B", "A"]);
14585 }
14586 }
14587
14588 #[test]
14589 fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
14590 let home = crate::run::test_home();
14591 let mut state = crate::land::tests::repair_state(true, true);
14592 state.status = RunStatus::Landing;
14593 state.parked = true;
14594 state.driver_exited = true;
14595 let mut q = ask::Question::new(
14596 state.id.clone(),
14597 land::APPROVAL_NODE.into(),
14598 "land".into(),
14599 "Merge?".into(),
14600 String::new(),
14601 vec![land::APPROVE.into(), land::HOLD.into()],
14602 );
14603 q.id = state.id.clone();
14604 state.land_approval = Some(crate::run::LandApproval {
14605 question: q.id.clone(),
14606 head: "current-head".into(),
14607 });
14608 assert!(land::upgrade_repair_choice(&mut q, &state));
14609 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14610 let mut task = held_task_with(&state.id);
14611 task.status = TaskStatus::Parked;
14612 assert_eq!(
14613 decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
14614 ActionDecision::Resume(state.id.clone())
14615 );
14616 q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
14617 q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
14618 task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
14619 assert_eq!(
14620 decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
14621 ActionDecision::Resume(state.id.clone()),
14622 "a repair answer newer than the manual hold resumes the existing owner"
14623 );
14624 task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
14625 for answered_at in [q.answered_at, None] {
14626 let mut older = q.clone();
14627 older.answered_at = answered_at;
14628 let refused = decide_action(&home, &task, &older, &PHRASES_EN, |_| {
14629 panic!("a later manual hold must prevent dispatch")
14630 });
14631 let ActionDecision::Refuse(reason) = refused else {
14632 panic!("expected an actionable refusal, got {refused:?}");
14633 };
14634 assert!(reason.contains("later operator decision"));
14635 assert!(reason.contains(&format!("magi task release {}", task.id)));
14636 }
14637 task.operator_decided_at = None;
14638 let mut superseded = state.clone();
14639 superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
14640 assert_eq!(
14641 decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(superseded)),
14642 ActionDecision::Stale
14643 );
14644 for case in 1..4 {
14645 let mut changed = state.clone();
14646 match case {
14647 1 => changed.status = RunStatus::Blocked,
14648 2 => changed.released_to = Some("new-owner".into()),
14649 _ => changed.land_approval.as_mut().unwrap().head.clear(),
14650 }
14651 assert!(matches!(
14652 decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(changed)),
14653 ActionDecision::Refuse(_)
14654 ));
14655 }
14656 assert!(matches!(
14657 decide_action(&home, &task, &q, &PHRASES_EN, |_| anyhow::bail!(
14658 "missing owner"
14659 )),
14660 ActionDecision::Refuse(_)
14661 ));
14662 task.runs.push("replacement".into());
14663 task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
14664 assert_eq!(
14665 decide_action(&home, &task, &q, &PHRASES_EN, |_| panic!(
14666 "old owner must not load"
14667 )),
14668 ActionDecision::Stale
14669 );
14670 }
14671
14672 #[test]
14673 fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
14674 let mut state = crate::land::tests::repair_state(true, true);
14675 state.status = RunStatus::Landing;
14676 state.parked = true;
14677 state.driver_exited = true;
14678 let mut q = ask::Question::new(
14679 state.id.clone(),
14680 land::APPROVAL_NODE.into(),
14681 "land".into(),
14682 "Merge?".into(),
14683 String::new(),
14684 vec![land::APPROVE.into(), land::HOLD.into()],
14685 );
14686 q.id = state.id.clone();
14687 state.land_approval = Some(crate::run::LandApproval {
14688 question: q.id.clone(),
14689 head: "current-head".into(),
14690 });
14691 state.save().unwrap();
14692 land::upgrade_repair_choice(&mut q, &state);
14693 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14694 Questions::open().put(&mut q).unwrap();
14695 let tmp = tempfile::tempdir().unwrap();
14696 let queue = Queue::at(tmp.path().join("queue"));
14697 let mut task = held_task_with(&state.id);
14698 task.status = TaskStatus::Parked;
14699 queue.put(&mut task).unwrap();
14700 let empty = Arc::new(tokio::sync::Semaphore::new(0));
14701 let free = Arc::new(tokio::sync::Semaphore::new(1));
14702 assert!(matches!(
14703 claim_dispatch(&queue, &task, false, &empty, &free),
14704 Err(SkipReason::OrdinaryCapacity)
14705 ));
14706 assert!(matches!(
14707 claim_dispatch(&queue, &task, true, &free, &free),
14708 Err(SkipReason::CoolingDown)
14709 ));
14710 let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
14711 assert!(claim.permit.is_some());
14712 assert!(matches!(
14713 claim_dispatch(&queue, &task, false, &free, &free),
14714 Err(SkipReason::ClaimUnavailable)
14715 ));
14716 drop(claim);
14717 Questions::open()
14718 .update(&q.id, |q| {
14719 q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
14720 Ok(())
14721 })
14722 .unwrap();
14723 let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
14724 assert!(claim.permit.is_none());
14725 assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
14726 }
14727
14728 #[test]
14729 fn decide_action_resumes_only_the_latest_resumable_run() {
14730 let home = crate::run::test_home();
14731 let t = held_task_with("r1");
14732 let q = action_question("r1", resume_action("r1"));
14733 let load = |s: RunState| move |_: &str| Ok(s);
14734 assert_eq!(
14735 decide_action(
14736 &home,
14737 &t,
14738 &q,
14739 &PHRASES_EN,
14740 load(run_state(RunStatus::Blocked))
14741 ),
14742 ActionDecision::Resume("r1".into())
14743 );
14744 let q_other = action_question("r1", resume_action("r0"));
14746 assert!(matches!(
14747 decide_action(
14748 &home,
14749 &t,
14750 &q_other,
14751 &PHRASES_EN,
14752 load(run_state(RunStatus::Blocked))
14753 ),
14754 ActionDecision::Refuse(_)
14755 ));
14756 assert!(matches!(
14758 decide_action(
14759 &home,
14760 &t,
14761 &q,
14762 &PHRASES_EN,
14763 load(run_state(RunStatus::Ready))
14764 ),
14765 ActionDecision::Refuse(_)
14766 ));
14767 let mut released = run_state(RunStatus::Blocked);
14769 released.released_to = Some("elsewhere".into());
14770 assert!(matches!(
14771 decide_action(&home, &t, &q, &PHRASES_EN, load(released)),
14772 ActionDecision::Refuse(_)
14773 ));
14774 assert!(matches!(
14776 decide_action(&home, &t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
14777 ActionDecision::Refuse(_)
14778 ));
14779 }
14780
14781 #[test]
14782 fn decide_action_ignores_a_question_about_an_earlier_run() {
14783 let home = crate::run::test_home();
14784 let mut t = held_task_with("r1");
14785 t.runs.push("r2".to_owned());
14786 let never = |_: &str| -> Result<RunState> { bail!("not read") };
14787 assert_eq!(
14788 decide_action(
14789 &home,
14790 &t,
14791 &action_question("r1", ask::ChoiceAction::Done),
14792 &PHRASES_EN,
14793 never
14794 ),
14795 ActionDecision::Stale
14796 );
14797 }
14798
14799 #[test]
14800 fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
14801 let home = crate::run::test_home();
14802 let mut t = held_task_with("r1");
14803 let never = |_: &str| -> Result<RunState> { bail!("not read") };
14804 assert_eq!(
14805 decide_action(
14806 &home,
14807 &t,
14808 &action_question("r1", ask::ChoiceAction::Requeue),
14809 &PHRASES_EN,
14810 never
14811 ),
14812 ActionDecision::Requeue
14813 );
14814 let done_q = action_question("r1", ask::ChoiceAction::Done);
14815 assert_eq!(
14816 decide_action(&home, &t, &done_q, &PHRASES_EN, never),
14817 ActionDecision::Done
14818 );
14819 t.mark_action_applied(&done_q.id);
14820 assert_eq!(
14821 decide_action(&home, &t, &done_q, &PHRASES_EN, never),
14822 ActionDecision::Skip
14823 );
14824
14825 let mut plain = action_question("r1", ask::ChoiceAction::Done);
14827 plain.actions.clear();
14828 assert_eq!(
14829 decide_action(&home, &held_task_with("r1"), &plain, &PHRASES_EN, never),
14830 ActionDecision::Skip
14831 );
14832 let mut running = held_task_with("r1");
14834 running.status = TaskStatus::Running;
14835 assert_eq!(
14836 decide_action(
14837 &home,
14838 &running,
14839 &action_question("r1", ask::ChoiceAction::Done),
14840 &PHRASES_EN,
14841 never
14842 ),
14843 ActionDecision::Skip
14844 );
14845 }
14846
14847 #[test]
14848 fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
14849 crate::run::pin_test_home();
14850 for legacy in [false, true] {
14851 let dir = tempfile::tempdir().unwrap();
14852 let queue = Queue::at(dir.path().join("queue"));
14853 let questions = Questions::at(dir.path().join("questions"));
14854 let run = "20260101-000000-hold";
14855 let mut task = held_task_with(run);
14856 task.status = TaskStatus::Parked;
14857 let mut q = ask::Question::new(
14858 run.into(),
14859 land::APPROVAL_NODE.into(),
14860 "land".into(),
14861 "Repair?".into(),
14862 String::new(),
14863 vec![land::REPAIR.into()],
14864 );
14865 q.actions.insert(land::REPAIR.into(), resume_action(run));
14866 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14867 q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
14869 q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
14870 questions.put(&mut q).unwrap();
14871 task.hold_manual(Some("Keep this PR paused".into()));
14872 if legacy {
14873 task.hold_source = None;
14874 }
14875 queue.put(&mut task).unwrap();
14876
14877 apply_task_choice_actions(&queue, &questions, dir.path());
14878 let after = queue.get(&task.id).unwrap();
14879 assert!(after.operator_held());
14880 assert_eq!(after.hold_source, task.hold_source);
14881 assert_eq!(after.operator_decided_at, task.operator_decided_at);
14882 assert_eq!(after.runs, task.runs);
14883 assert_eq!(after.instruction, task.instruction);
14884 assert!(after.resume_override.is_none());
14885 assert!(after.action_applied(&q.id));
14886 let reason = after.hold_reason.as_deref().unwrap();
14887 assert!(reason.starts_with("Keep this PR paused"));
14888 assert!(reason.contains("later operator decision"));
14889 assert!(reason.contains(&format!("magi task release {}", task.id)));
14890
14891 for recovery in [
14892 crate::conduct::Recovery::Review,
14893 crate::conduct::Recovery::Requeue,
14894 ] {
14895 crate::conduct::apply(
14896 &queue,
14897 &questions,
14898 &crate::conduct::Verdict {
14899 decisions: vec![crate::conduct::Decision {
14900 id: task.id.clone(),
14901 recovery: Some(recovery),
14902 ..Default::default()
14903 }],
14904 },
14905 )
14906 .unwrap();
14907 }
14908 apply_task_choice_actions(&queue, &questions, dir.path());
14911 let still_held = queue.get(&task.id).unwrap();
14912 assert!(still_held.operator_held());
14913 assert_eq!(still_held.hold_reason, after.hold_reason);
14914 assert_eq!(still_held.runs, task.runs);
14915 assert!(still_held.review_branch.is_none());
14916 assert!(!still_held.fresh_start);
14917 assert!(queue.next_runnable().is_none());
14918 }
14919 }
14920
14921 #[test]
14922 fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
14923 for held in [false, true] {
14924 for retry in [false, true] {
14925 let dir = tempfile::tempdir().unwrap();
14926 let queue = Queue::at(dir.path().join("queue"));
14927 let questions = Questions::at(dir.path().join("questions"));
14928 let home = dir.path().join("home");
14929 let mut t = task();
14930 if held {
14931 t.hold_machine(Some("driver state unknown".into()));
14932 }
14933 queue.put(&mut t).unwrap();
14934 let verdict = serde_json::from_value(serde_json::json!({
14935 "decisions": [{
14936 "id": t.id,
14937 "question": "Driver state unknown; retry the checks or hold?",
14938 "choices": ["daemon: recheck and retry", "daemon: hold the task"],
14939 "actions": {
14940 "daemon: recheck and retry": {"do": "requeue"},
14941 "daemon: hold the task": {"do": "hold"}
14942 }
14943 }]
14944 }))
14945 .unwrap();
14946 crate::conduct::apply(&queue, &questions, &verdict).unwrap();
14947 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
14948 let mut q = questions.list().pop().unwrap();
14949 let choice = if retry {
14950 "daemon: recheck and retry"
14951 } else {
14952 "daemon: hold the task"
14953 };
14954 assert_eq!(q.actions.len(), 2);
14955 q.answer(ask::Answer::Choice(choice.into())).unwrap();
14956 questions.put(&mut q).unwrap();
14957
14958 questions.beat(&q.id, ask::WaiterKind::Deputy);
14960 for _ in 0..2 {
14961 resolve_blockers(&queue, &questions);
14962 apply_task_choice_actions(&queue, &questions, &home);
14963 let waiting = queue.get(&t.id).unwrap();
14964 assert_eq!(waiting.status, TaskStatus::Blocked);
14965 assert_eq!(waiting.blocked_by, [q.id.clone()]);
14966 assert!(waiting.answers.is_empty());
14967 assert!(!waiting.action_applied(&q.id));
14968 assert!(runnable(&queue).is_empty());
14969 let free = Arc::new(tokio::sync::Semaphore::new(1));
14970 assert!(claim_dispatch(&queue, &t, false, &free, &free).is_err());
14971 }
14972 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
14973
14974 resolve_blockers(&queue, &questions);
14976 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
14977 apply_task_choice_actions(&queue, &questions, &home);
14978 let after = queue.get(&t.id).unwrap();
14979 assert_eq!(
14980 after.status,
14981 if retry {
14982 TaskStatus::Queued
14983 } else {
14984 TaskStatus::Held
14985 }
14986 );
14987 assert!(after.action_applied(&q.id));
14988 assert_eq!(after.operator_held(), !retry);
14989 assert_eq!(after.answers.len(), 1);
14990
14991 let mut changed = after;
14993 if retry {
14994 changed.hold_manual(Some("later hold".into()));
14995 } else {
14996 changed.release_operator("test", None);
14997 }
14998 let expected = changed.status;
14999 queue.put(&mut changed).unwrap();
15000 apply_task_choice_actions(&queue, &questions, &home);
15001 assert_eq!(queue.get(&t.id).unwrap().status, expected);
15002 }
15003 }
15004 }
15005
15006 #[test]
15007 fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
15008 let dir = tempfile::tempdir().unwrap();
15009 let queue = Queue::at(dir.path().join("queue"));
15010 let questions = Questions::at(dir.path().join("questions"));
15011 let home = dir.path().join("home");
15012 let mut state = run_state(RunStatus::Blocked);
15013 state.id = "20260101-000000-act1".to_owned();
15014 state.save_under(&home).unwrap();
15015
15016 let mut t = held_task_with(&state.id);
15017 queue.put(&mut t).unwrap();
15018 let mut q = action_question(&state.id, resume_action(&state.id));
15019 questions.put(&mut q).unwrap();
15020
15021 apply_task_choice_actions(&queue, &questions, &home);
15022 let after = queue.get(&t.id).unwrap();
15023 assert_eq!(after.status, TaskStatus::Queued);
15024 assert!(!after.fresh_start);
15025 assert!(after.action_applied(&q.id));
15026 let pin = after.resume_override.clone().unwrap();
15027 assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
15028 assert!(pin.forced);
15029
15030 let mut again = queue.get(&t.id).unwrap();
15032 again.hold_machine(Some("later".into()));
15033 queue.put(&mut again).unwrap();
15034 apply_task_choice_actions(&queue, &questions, &home);
15035 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
15036 }
15037
15038 #[test]
15039 fn done_choice_cannot_discard_unfinished_work_or_record_success_receipts() {
15040 let dir = tempfile::tempdir().unwrap();
15041 let home = dir.path();
15042 let queue = Queue::at(home.join("queue"));
15043 let questions = Questions::at(home.join("questions"));
15044 let mut state = run_state(RunStatus::Blocked);
15045 state.save_under(home).unwrap();
15046 let mut task = held_task_with(&state.id);
15047 queue.put(&mut task).unwrap();
15048 let mut question = action_question(&state.id, ask::ChoiceAction::Done);
15049 questions.put(&mut question).unwrap();
15050
15051 apply_task_choice_actions(&queue, &questions, home);
15052
15053 let after = queue.get(&task.id).unwrap();
15054 assert_eq!(after.status, TaskStatus::Held);
15055 assert!(after.hold_reason.as_deref().unwrap().contains("--discard"));
15056 assert_eq!(after.runs, task.runs);
15057 assert!(after.completion_history.is_empty());
15058 assert!(!after.decision_effects.contains_key(&question.id));
15059 assert_eq!(
15060 RunState::load_under(&state.id, home).unwrap().status,
15061 RunStatus::Blocked
15062 );
15063 }
15064
15065 #[test]
15066 fn a_delivered_answer_is_still_acted_on_exactly_once() {
15067 let dir = tempfile::tempdir().unwrap();
15068 let queue = Queue::at(dir.path().join("queue"));
15069 let questions = Questions::at(dir.path().join("questions"));
15070 let home = dir.path().join("home");
15071 let mut state = run_state(RunStatus::Blocked);
15072 state.id = "20260101-000000-act2".to_owned();
15073 state.save_under(&home).unwrap();
15074
15075 let mut t = held_task_with(&state.id);
15076 queue.put(&mut t).unwrap();
15077 let mut q = action_question(&state.id, resume_action(&state.id));
15078 q.answer_delivered = true;
15079 questions.put(&mut q).unwrap();
15080
15081 apply_task_choice_actions(&queue, &questions, &home);
15084 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
15085 assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
15086
15087 let mut again = queue.get(&t.id).unwrap();
15089 again.hold_machine(Some("later".into()));
15090 queue.put(&mut again).unwrap();
15091 apply_task_choice_actions(&queue, &questions, &home);
15092 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
15093 }
15094
15095 #[test]
15096 fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
15097 let dir = tempfile::tempdir().unwrap();
15098 let queue = Queue::at(dir.path().join("queue"));
15099 let questions = Questions::at(dir.path().join("questions"));
15100 let home = dir.path().join("home");
15101 let mut state = run_state(RunStatus::Blocked);
15102 state.id = "20260101-000000-act3".to_owned();
15103 state.save_under(&home).unwrap();
15104 let mut t = held_task_with(&state.id);
15105 queue.put(&mut t).unwrap();
15106 let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
15107 questions.put(&mut q).unwrap();
15108
15109 questions.beat(&q.id, crate::ask::WaiterKind::Asker);
15110 apply_task_choice_actions(&queue, &questions, &home);
15111 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
15112
15113 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
15114 apply_task_choice_actions(&queue, &questions, &home);
15115 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
15116 }
15117
15118 #[test]
15119 fn action_standing_tells_the_reasons_apart() {
15120 let mut t = held_task_with("r1");
15121 let q = action_question("r1", ask::ChoiceAction::Requeue);
15122 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
15123 let mut plain = q.clone();
15124 plain.actions.clear();
15125 assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
15126
15127 t.mark_action_applied(&q.id);
15129 assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
15130
15131 let mut t = held_task_with("r1");
15133 t.start("r2".to_owned());
15134 assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
15135 let q2 = action_question("r2", ask::ChoiceAction::Requeue);
15137 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
15138 t.status = TaskStatus::Blocked;
15139 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
15140
15141 let mut c = action_question("r0", ask::ChoiceAction::Requeue);
15143 c.node = crate::conduct::NODE.to_owned();
15144 assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
15145 assert!(!ActionStanding::Busy.daemon_owns());
15146 }
15147
15148 #[test]
15149 fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
15150 let dir = tempfile::tempdir().unwrap();
15151 let queue = Queue::at(dir.path().join("queue"));
15152 let questions = Questions::at(dir.path().join("questions"));
15153 let home = dir.path().join("home");
15154 let mut state = run_state(RunStatus::Ready);
15156 state.id = "20260101-000000-act4".to_owned();
15157 state.save_under(&home).unwrap();
15158 let mut t = held_task_with(&state.id);
15159 t.status = TaskStatus::Running;
15160 queue.put(&mut t).unwrap();
15161 let mut q = action_question(&state.id, ask::ChoiceAction::Done);
15162 q.cwd = Some(dir.path().display().to_string());
15163 questions.put(&mut q).unwrap();
15164
15165 let running = queue.get(&t.id).unwrap();
15168 assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
15169 assert!(matches!(
15170 crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
15171 crate::waiter::Action::Deliver(_)
15172 ));
15173 apply_task_choice_actions(&queue, &questions, &home);
15175 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
15176 let mut back = queue.get(&t.id).unwrap();
15177 back.hold_machine(Some("later".into()));
15178 queue.put(&mut back).unwrap();
15179 apply_task_choice_actions(&queue, &questions, &home);
15180 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
15181 let mut again = queue.get(&t.id).unwrap();
15182 again.hold_machine(Some("again".into()));
15183 queue.put(&mut again).unwrap();
15184 apply_task_choice_actions(&queue, &questions, &home);
15185 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
15186 }
15187}