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)]
143 pub dispatch_skips: std::collections::BTreeMap<String, String>,
144 #[serde(default)]
146 pub question_recovery: Option<crate::question_delivery::Recovery>,
147 #[serde(default)]
149 pub worker_protocol: Option<u32>,
150}
151
152impl Status {
153 #[must_use]
155 pub fn new() -> Self {
156 let now = Timestamp::now();
157 Self {
158 schema: SCHEMA,
159 pid: std::process::id(),
160 started_at: now,
161 updated_at: now,
162 idle: true,
163 current: Vec::new(),
164 completed: 0,
165 polls: 0,
166 dispatch_wait: None,
167 dispatch_skips: std::collections::BTreeMap::new(),
168 question_recovery: None,
169 worker_protocol: Some(1),
170 }
171 }
172}
173
174impl Default for Status {
175 fn default() -> Self {
176 Self::new()
177 }
178}
179
180#[derive(Debug, Clone, Serialize, Deserialize)]
182#[serde(default)]
183pub struct Opts {
184 pub repo: PathBuf,
186 pub config: Option<PathBuf>,
188 pub poll: Duration,
190 pub max_attempts: usize,
192 pub once: bool,
194 pub merge: Option<String>,
196 pub worktrees_root: Option<PathBuf>,
205}
206
207impl Default for Opts {
208 fn default() -> Self {
209 Self {
210 repo: PathBuf::from("."),
211 config: None,
212 poll: POLL,
213 max_attempts: 2,
214 once: false,
215 merge: None,
216 worktrees_root: None,
217 }
218 }
219}
220
221impl Opts {
222 fn absolute(&self) -> Result<Self> {
223 let mut opts = self.clone();
224 opts.repo = std::path::absolute(&opts.repo)?;
225 opts.config = opts
226 .config
227 .as_deref()
228 .map(std::path::absolute)
229 .transpose()?;
230 opts.worktrees_root = opts
231 .worktrees_root
232 .as_deref()
233 .map(std::path::absolute)
234 .transpose()?;
235 Ok(opts)
236 }
237}
238
239fn max_concurrent(n: usize) -> usize {
244 n.max(1)
245}
246
247#[must_use]
249pub fn status_path() -> PathBuf {
250 crate::run::home().join("daemon.json")
251}
252
253pub fn write_status(status: &Status) -> Result<()> {
255 write_status_to(&status_path(), status)
256}
257
258pub fn write_status_to(path: &Path, status: &Status) -> Result<()> {
263 if let Some(parent) = path.parent() {
264 std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
265 }
266 let body = serde_json::to_string_pretty(status).context("serialize daemon status")?;
267 let tmp = path.with_extension("json.tmp");
268 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
269 std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
270 Ok(())
271}
272
273pub fn clear_status() {
276 clear_status_at(&status_path());
277}
278
279fn clear_status_at(path: &Path) {
283 let _ = std::fs::remove_file(path);
284}
285
286#[derive(Debug, Clone, Default)]
298pub struct Stop {
299 stopped: Arc<AtomicBool>,
303 busy: Arc<std::sync::atomic::AtomicUsize>,
305 wake: Arc<Notify>,
309 pause: crate::graph::Pause,
312}
313
314impl Stop {
315 #[must_use]
317 pub fn new() -> Self {
318 Self::default()
319 }
320
321 pub fn stop(&self) {
324 self.stopped.store(true, Ordering::SeqCst);
325 self.wake.notify_one();
329 }
330
331 #[must_use]
333 pub fn stopped(&self) -> bool {
334 self.stopped.load(Ordering::SeqCst)
335 }
336
337 #[must_use]
340 pub fn finishing(&self) -> bool {
341 self.stopped() && self.busy_now()
342 }
343
344 pub fn park(&self, cause: crate::run::ParkCause) {
350 self.pause.park_for(cause);
351 self.stop();
352 }
353
354 #[must_use]
356 pub fn parking(&self) -> bool {
357 self.pause.parked()
358 }
359
360 #[must_use]
362 pub fn pause(&self) -> crate::graph::Pause {
363 self.pause.clone()
364 }
365
366 #[must_use]
368 pub fn busy_now(&self) -> bool {
369 self.busy.load(Ordering::SeqCst) > 0
370 }
371
372 async fn idle(&self, poll: Duration) {
374 tokio::select! {
375 () = tokio::time::sleep(poll) => {}
376 () = self.wake.notified() => {}
377 }
378 }
379}
380
381#[derive(Debug, Clone, Default, Deserialize)]
388#[serde(default)]
389pub struct Reading {
390 pub schema: u32,
392 pub pid: Option<u32>,
394 pub started_at: Option<Timestamp>,
396 pub updated_at: Option<Timestamp>,
398 pub idle: bool,
400 #[serde(deserialize_with = "de_current")]
412 pub current: Vec<Current>,
413 pub completed: u64,
415 pub polls: u64,
417 pub dispatch_wait: Option<DispatchWait>,
419 #[serde(default)]
421 pub dispatch_skips: std::collections::BTreeMap<String, String>,
422 #[serde(default)]
424 pub question_recovery: Option<crate::question_delivery::Recovery>,
425 pub worker_protocol: Option<u32>,
427}
428
429fn de_current<'de, D>(deserializer: D) -> std::result::Result<Vec<Current>, D::Error>
432where
433 D: serde::Deserializer<'de>,
434{
435 #[derive(Deserialize)]
436 #[serde(untagged)]
437 enum Shape {
438 Many(Vec<Current>),
439 One(Current),
440 }
441 Ok(
442 Option::<Shape>::deserialize(deserializer)?.map_or_else(Vec::new, |shape| match shape {
443 Shape::Many(v) => v,
444 Shape::One(c) => vec![c],
445 }),
446 )
447}
448
449impl Reading {
450 #[must_use]
453 pub fn age_secs(&self, now: Timestamp) -> Option<i64> {
454 self.updated_at
455 .map(|at| (now.as_second() - at.as_second()).max(0))
456 }
457
458 #[must_use]
462 pub fn running(&self, now: Timestamp) -> bool {
463 self.age_secs(now).is_some_and(|secs| secs <= STALE_SECS)
464 }
465}
466
467#[must_use]
474pub fn read_status(home: &Path) -> Option<Reading> {
475 let body = std::fs::read_to_string(home.join("daemon.json")).ok()?;
476 serde_json::from_str(&body).ok()
477}
478
479struct ClaimObservation {
480 current: Current,
481 evidence: crate::run::LivenessEvidence,
482}
483
484fn observe_current_work(home: &Path, now: Timestamp) -> Vec<ClaimObservation> {
485 let mut observed: Vec<ClaimObservation> = Vec::new();
486 let reading = read_status(home).filter(|reading| reading.running(now));
487 let daemon_pid = reading.as_ref().and_then(|r| r.pid);
488 let heartbeat_age_secs = reading.as_ref().and_then(|r| r.age_secs(now));
489 if let Some(reading) = reading {
490 for claim in reading.current {
491 let task = (!claim.task.is_empty()).then(|| claim.task.clone());
492 let (worker_pid, worker_status, worker_lookup_error) = match claim.worker.as_deref() {
493 Some(worker_id) => match crate::worker::get(home, worker_id) {
494 Ok(job)
495 if matches!(
496 job.status,
497 crate::worker::Status::Finished | crate::worker::Status::Failed
498 ) =>
499 {
500 continue;
503 }
504 Ok(job) => (job.pid, Some(job.status), None),
505 Err(error) => (None, None, Some(format!("{error:#}"))),
506 },
507 None => (None, None, None),
508 };
509 let evidence = crate::run::LivenessEvidence::DaemonHeartbeat {
510 daemon_pid,
511 heartbeat_age_secs,
512 worker_id: claim.worker.clone(),
513 worker_pid,
514 worker_status,
515 worker_lookup_error,
516 task,
517 };
518 observed.push(ClaimObservation {
519 current: claim,
520 evidence,
521 });
522 }
523 }
524 let workers = crate::worker::observe_active_detailed(home).and_then(|jobs| {
525 jobs.into_iter()
526 .filter(|entry| entry.job.kind == "task")
527 .map(|entry| {
528 let job = entry.job;
529 let request: TaskWorker = serde_json::from_value(job.payload).map_err(|_| {
530 anyhow::anyhow!("invalid task worker payload metadata for worker {}", job.id)
531 })?;
532 let run = Queue::at(request.queue)
533 .get(&request.task)
534 .ok()
535 .and_then(|task| task.execution_runs().last().cloned())
536 .unwrap_or_default();
537 let task_label = (!request.task.is_empty()).then(|| request.task.clone());
538 let current = Current {
539 worker: Some(job.id.clone()),
540 task: request.task,
541 run,
542 };
543 let evidence = crate::run::LivenessEvidence::WorkerClaim {
544 worker_id: job.id,
545 pid: job.pid,
546 status: job.status,
547 reason: entry.reason,
548 task: task_label,
549 daemon_pid: None,
550 };
551 Ok(ClaimObservation { current, evidence })
552 })
553 .collect::<Result<Vec<_>>>()
554 });
555 match workers {
556 Ok(workers) => {
557 for mut worker in workers {
558 if let Some(existing) = observed.iter_mut().find(|claim| {
559 claim.current.task == worker.current.task
560 && claim.current.run == worker.current.run
561 && claim.current.worker == worker.current.worker
562 }) {
563 if let crate::run::LivenessEvidence::WorkerClaim {
564 daemon_pid: ref mut target_daemon_pid,
565 ..
566 } = worker.evidence
567 {
568 *target_daemon_pid = daemon_pid;
569 }
570 existing.evidence = worker.evidence;
571 } else {
572 observed.push(worker);
573 }
574 }
575 }
576 Err(error) => {
577 let detail = format!("{error:#}");
580 tracing::error!("cannot determine active workers: {detail}");
581 let evidence = crate::run::LivenessEvidence::WorkerStoreUnreadable { error: detail };
582 observed.extend(
583 Queue::at(home.join("queue"))
584 .list()
585 .into_iter()
586 .map(|task| ClaimObservation {
587 current: Current {
588 worker: None,
589 task: task.id.clone(),
590 run: task.execution_runs().last().cloned().unwrap_or_default(),
591 },
592 evidence: evidence.clone(),
593 }),
594 );
595 observed.extend(
596 crate::run::list_ids_in(&home.join("runs"))
597 .into_iter()
598 .map(|run| ClaimObservation {
599 current: Current {
600 worker: None,
601 task: String::new(),
602 run,
603 },
604 evidence: evidence.clone(),
605 }),
606 );
607 }
608 }
609 observed
610}
611
612#[must_use]
621pub fn current_work(home: &Path, now: Timestamp) -> Vec<Current> {
622 observe_current_work(home, now)
623 .into_iter()
624 .map(|entry| entry.current)
625 .collect()
626}
627
628#[must_use]
630pub fn claim_for_run(
631 home: &Path,
632 run: &str,
633 now: Timestamp,
634) -> Option<crate::run::LivenessEvidence> {
635 observe_current_work(home, now)
636 .into_iter()
637 .find(|entry| entry.current.run == run)
638 .map(|entry| entry.evidence)
639}
640
641#[must_use]
643pub fn is_working_on(home: &Path, run: &str, now: Timestamp) -> bool {
644 claim_for_run(home, run, now).is_some()
645}
646
647pub(crate) fn is_working_on_other(home: &Path, run: &str, now: Timestamp) -> Result<bool> {
652 Ok(other_claim_for_run(home, run, now)?.is_some())
653}
654
655pub(crate) fn other_claim_for_run(
658 home: &Path,
659 run: &str,
660 now: Timestamp,
661) -> Result<Option<crate::run::LivenessEvidence>> {
662 let same_home = std::env::var_os("MAGI_WORKER_HOME")
665 .is_some_and(|worker_home| Path::new(&worker_home) == home);
666 let caller = if same_home {
667 crate::worker::current_job(home)?
668 } else {
669 None
670 }
671 .filter(|job| {
672 job.kind == "task"
673 && job.status == crate::worker::Status::Running
674 && job.pid == Some(std::process::id())
675 });
676 let caller_id = caller.as_ref().map(|job| job.id.as_str());
677 Ok(observe_current_work(home, now)
678 .into_iter()
679 .find(|entry| {
680 entry.current.run == run
681 && !(caller_id.is_some() && entry.current.worker.as_deref() == caller_id)
682 })
683 .map(|entry| entry.evidence))
684}
685
686#[cfg(test)]
687fn other_claims_run(claims: &[Current], run: &str, caller: Option<&str>) -> bool {
688 claims
689 .iter()
690 .any(|claim| claim.run == run && !(caller.is_some() && claim.worker.as_deref() == caller))
691}
692
693#[must_use]
703pub fn is_working_on_short(home: &Path, short: &str, now: Timestamp) -> bool {
704 current_work(home, now)
705 .iter()
706 .any(|c| crate::run::short_of(&c.run) == short)
707}
708
709#[must_use]
711pub fn is_working_on_task(home: &Path, task: &str, now: Timestamp) -> bool {
712 current_work(home, now).iter().any(|c| c.task == task)
713}
714
715pub fn sweep_stale_claims(queue: &Queue, older_than: Duration) -> Vec<String> {
755 sweep_stale_claims_with(queue, older_than, crate::proc::pid_alive)
756}
757
758fn sweep_stale_claims_with<F>(queue: &Queue, older_than: Duration, pid_alive: F) -> Vec<String>
762where
763 F: Fn(u32) -> bool,
764{
765 let this_process = std::process::id();
766 let mut swept: Vec<String> = std::fs::read_dir(queue.root())
767 .into_iter()
768 .flatten()
769 .flatten()
770 .map(|e| e.path())
771 .filter(|p| p.extension().is_some_and(|x| x == "lock"))
772 .filter(|p| {
773 match std::fs::read_to_string(p)
774 .ok()
775 .and_then(|body| body.trim().parse::<u32>().ok())
776 {
777 Some(pid) if pid == this_process => false,
781 Some(pid) => !pid_alive(pid),
782 None => p
783 .metadata()
784 .and_then(|m| m.modified())
785 .and_then(|t| t.elapsed().map_err(std::io::Error::other))
786 .is_ok_and(|age| age >= older_than),
787 }
788 })
789 .filter(|p| std::fs::remove_file(p).is_ok())
790 .filter_map(|p| {
791 p.file_stem()
792 .and_then(|s| s.to_str())
793 .map(std::borrow::ToOwned::to_owned)
794 })
795 .collect();
796 swept.sort_unstable();
797 swept
798}
799
800fn is_stalled(task: &Task, home: &Path, now: Timestamp) -> bool {
805 task.status == TaskStatus::Running
806 && (now.as_second() - task.updated_at.as_second()) >= STALLED_RUNNING.as_secs() as i64
807 && !is_working_on_task(home, &task.id, now)
808}
809
810fn stalled_tasks(queue: &Queue, home: &Path, now: Timestamp) -> Vec<Task> {
813 queue
814 .list()
815 .into_iter()
816 .filter(|t| is_stalled(t, home, now))
817 .collect()
818}
819
820fn queued_tasks(queue: &Queue) -> Vec<Task> {
826 queue
827 .list()
828 .into_iter()
829 .filter(|t| t.status == TaskStatus::Queued)
830 .collect()
831}
832
833fn finished_tasks(queue: &Queue) -> Vec<Task> {
836 queue
837 .list()
838 .into_iter()
839 .filter(|t| matches!(t.status, TaskStatus::Failed | TaskStatus::Held))
840 .collect()
841}
842
843fn resolve_blockers(queue: &Queue, questions: &Questions) {
860 for listed in queue.list() {
861 if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
862 continue;
863 }
864 let Ok(_claim) = queue.claim(&listed.id) else {
865 continue;
866 };
867 let Ok(mut task) = queue.get(&listed.id) else {
868 continue;
869 };
870 if task.status != TaskStatus::Blocked {
871 continue;
872 }
873 let deleted = queue.apply_deleted_blockers(&mut task, questions);
877 if !deleted.is_empty() {
878 record(queue, &mut task);
879 for id in &deleted {
880 queue.note_dependency_deleted(&task, id);
881 }
882 if task.status != TaskStatus::Blocked {
883 continue;
884 }
885 }
886 let missing = crate::queue::missing_blockers(queue, questions, &task.blocked_by);
887 if !missing.is_empty() {
888 let language = language_of(&task, Path::new("."));
889 let mut cause = missing.clone();
890 cause.sort();
891 cause.dedup();
892 task.notice_cause(&format!("missing-blockers:{}", cause.join(",")), None, None);
893 task.hold_machine(Some(crate::queue::missing_blocker_hold_reason_in(
894 &task.blocked_by,
895 &missing,
896 &language,
897 )));
898 record(queue, &mut task);
899 continue;
900 }
901 if let Some(q) = task.blocked_by.iter().find_map(|id| {
904 let crate::queue::Dependency::Question(full) =
905 crate::queue::dependency(queue, questions, id)
906 else {
907 return None;
908 };
909 questions.get_for_effects(&full).ok().filter(|q| {
910 q.node == crate::conduct::NODE && q.status == ask::QuestionStatus::Abandoned
911 })
912 }) {
913 let language = language_of(&task, Path::new("."));
914 task.notice_cause(&format!("unanswered-question:{}", q.id), None, None);
915 task.hold_machine(Some(unanswered_question_hold_reason(&q, &language)));
916 record(queue, &mut task);
917 continue;
918 }
919 let mut changed = false;
920 for id in task.blocked_by.clone() {
921 let resolved = crate::queue::dependency(queue, questions, &id);
922 if let crate::queue::Dependency::Task(full) = &resolved {
923 if queue
924 .get(full)
925 .is_ok_and(|dep| dep.status == TaskStatus::Done)
926 {
927 task.unblock(&id);
928 changed = true;
929 }
930 continue;
931 }
932 if let crate::queue::Dependency::Question(full) = resolved
933 && let Ok(q) = questions.get_for_effects(&full)
934 && q.status == ask::QuestionStatus::Answered
935 {
936 if q.node == crate::conduct::NODE
940 && q.chosen_action().is_some()
941 && !task.action_applied(&q.id)
942 {
943 continue;
944 }
945 let answer = match &q.answer {
946 Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
947 None => String::new(),
948 };
949 task.record_answer(q.summary.clone(), answer);
950 task.unblock(&id);
951 changed = true;
952 }
953 }
954 if changed {
955 record(queue, &mut task);
956 }
957 }
958}
959
960fn unanswered_question_hold_reason(q: &ask::Question, language: &str) -> String {
962 if crate::lang::is_japanese(language) {
963 format!(
964 "質問 {} 「{}」 に期限内の回答がなく、取り下げられました - `magi task triage` を参照",
965 q.short(),
966 q.summary
967 )
968 } else {
969 format!(
970 "question {} \"{}\" went unanswered and was abandoned - see `magi task triage`",
971 q.short(),
972 q.summary
973 )
974 }
975}
976
977#[derive(Debug, Clone, Copy, PartialEq, Eq)]
980pub(crate) enum ActionStanding {
981 NoAction,
983 Pending,
985 Applied,
988 Stale,
990 Busy,
992}
993
994impl ActionStanding {
995 pub(crate) fn daemon_owns(self) -> bool {
997 matches!(self, Self::Pending | Self::Applied | Self::Stale)
998 }
999}
1000
1001pub(crate) fn action_standing(task: &Task, q: &ask::Question) -> ActionStanding {
1005 if task.stale_question(q) {
1006 ActionStanding::Stale
1007 } else if q.chosen_action().is_none() {
1008 ActionStanding::NoAction
1009 } else if task.action_applied(&q.id) {
1010 ActionStanding::Applied
1011 } else if q.node != crate::conduct::NODE && task.execution_runs().last() != Some(&q.run) {
1012 ActionStanding::Stale
1013 } else if matches!(
1014 task.status,
1015 TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
1016 ) {
1017 ActionStanding::Busy
1018 } else {
1019 ActionStanding::Pending
1020 }
1021}
1022
1023#[derive(Debug, Clone, PartialEq, Eq)]
1025enum ActionDecision {
1026 Skip,
1028 Resume(String),
1030 Requeue,
1032 Hold,
1034 Done,
1036 Stale,
1039 Refuse(String),
1042}
1043
1044fn decide_action<F>(
1053 home: &Path,
1054 task: &Task,
1055 q: &ask::Question,
1056 p: &Phrases,
1057 load: F,
1058) -> ActionDecision
1059where
1060 F: FnOnce(&str) -> Result<RunState>,
1061{
1062 if task.stale_question(q) {
1063 return ActionDecision::Stale;
1064 }
1065 let Some(action) = q.chosen_action() else {
1066 return ActionDecision::Skip;
1067 };
1068 if task.action_applied(&q.id)
1069 || matches!(
1070 task.status,
1071 TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
1072 )
1073 {
1074 return ActionDecision::Skip;
1075 }
1076 if q.node != crate::conduct::NODE && task.execution_runs().last() != Some(&q.run) {
1079 return ActionDecision::Stale;
1080 }
1081 let repair = q.node == land::APPROVAL_NODE && q.resolution().as_deref() == Some(land::REPAIR);
1082 let stopping = q.node == land::APPROVAL_NODE
1083 && q.resolution()
1084 .as_deref()
1085 .is_some_and(crate::merge_decision::stops);
1086 let decision_at = q.answered_at.unwrap_or(q.asked_at);
1090 if task.operator_decided_at.is_some_and(|at| at > decision_at) {
1091 return if repair || stopping {
1092 ActionDecision::Refuse(format!(
1093 "{} 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 {}`",
1094 if repair { "repair" } else { "stop" },
1095 q.id,
1096 q.run,
1097 task.id
1098 ))
1099 } else {
1100 ActionDecision::Stale
1101 };
1102 }
1103 match action {
1104 a if a.maintenance() => ActionDecision::Skip,
1105 ask::ChoiceAction::RecoverBase { .. }
1106 | ask::ChoiceAction::ResumeRun { .. }
1107 | ask::ChoiceAction::ReleaseTask { .. }
1108 | ask::ChoiceAction::RerunChecks { .. }
1109 | ask::ChoiceAction::AbandonRun { .. } => unreachable!(),
1110 ask::ChoiceAction::Requeue => ActionDecision::Requeue,
1111 ask::ChoiceAction::Hold => ActionDecision::Hold,
1112 ask::ChoiceAction::Done => ActionDecision::Done,
1113 ask::ChoiceAction::Resume { run } => {
1114 if task.execution_runs().last() != Some(run) {
1115 return ActionDecision::Refuse((p.resume_not_latest)(
1116 q.short(),
1117 ask::short_id(run),
1118 ));
1119 }
1120 match load(run) {
1121 Ok(s) if stopping => {
1122 if s.merge_decision.as_ref().is_some_and(|d| d.closed)
1123 || !s
1124 .land_approval
1125 .as_ref()
1126 .is_some_and(|binding| binding.question == q.id)
1127 {
1128 ActionDecision::Stale
1129 } else if s.liveness_under(home, false) == Liveness::Live {
1130 ActionDecision::Skip
1131 } else if s.status == RunStatus::Landing
1132 && !s.released()
1133 && s.retired_to.is_none()
1134 {
1135 ActionDecision::Resume(run.clone())
1136 } else {
1137 ActionDecision::Refuse("Owner stop decision cannot resume its original landing execution; inspect the existing run. No replacement or merge was started.".into())
1138 }
1139 }
1140 Ok(s)
1141 if q.node == land::APPROVAL_NODE
1142 && q.resolution().as_deref() == Some(land::REPAIR) =>
1143 {
1144 if s.merge_repairs.iter().any(|r| r.question == q.id)
1145 || s.land_approval.as_ref().is_some_and(|a| a.question != q.id)
1146 {
1147 ActionDecision::Stale
1150 } else if s.liveness_under(home, false) == Liveness::Live {
1151 ActionDecision::Skip
1152 } else if s.status != RunStatus::Landing
1153 || s.released()
1154 || s.reviews.is_empty()
1155 || !implementers_match(task, &s)
1156 || !s
1157 .land_approval
1158 .as_ref()
1159 .is_some_and(|a| a.question == q.id && !a.head.is_empty())
1160 {
1161 ActionDecision::Refuse(format!(
1162 "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",
1163 q.id, run, run
1164 ))
1165 } else {
1166 ActionDecision::Resume(run.clone())
1167 }
1168 }
1169 Ok(s) => {
1170 let assessment = s.assess_liveness_under(home, None, Timestamp::now());
1171 if assessment.verdict == Liveness::Live {
1172 ActionDecision::Refuse(assessment.live_driver_refusal())
1173 } else {
1174 match crate::handover::resume_refusal_under(&s, Some(home)) {
1175 None => ActionDecision::Resume(run.clone()),
1176 Some(reason) => ActionDecision::Refuse((p.resume_cannot_progress)(
1177 q.short(),
1178 ask::short_id(run),
1179 &reason.diagnostic(&s),
1180 )),
1181 }
1182 }
1183 }
1184 Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
1185 q.short(),
1186 ask::short_id(run),
1187 &format!("{e:#}"),
1188 )),
1189 }
1190 }
1191 }
1192}
1193
1194struct Phrases {
1208 graph_stopped: fn(&str, &str) -> String,
1210 quorum_lost: &'static str,
1211 quota_took_out: &'static str,
1213 run_ended: &'static str,
1215 waiting_for_answer: &'static str,
1217 recovered_running: &'static str,
1218 no_run_to_recover: &'static str,
1219 could_not_start: &'static str,
1220 resume_not_latest: fn(&str, &str) -> String,
1221 resume_cannot_progress: fn(&str, &str, &str) -> String,
1222 resume_unreadable: fn(&str, &str, &str) -> String,
1223 handover_refused: fn(&crate::handover::Refused) -> String,
1226 handover_hint: &'static str,
1228 reviewers_never_answered: fn(usize, usize) -> String,
1231}
1232
1233const PHRASES_EN: Phrases = Phrases {
1234 graph_stopped: |status, detail| {
1235 format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
1236 },
1237 quorum_lost: "the judging panel lost its quorum",
1238 quota_took_out: "; quota took out ",
1239 run_ended: "run ended ",
1240 waiting_for_answer: " - waiting for operator answer to question ",
1241 recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
1242 no_run_to_recover: "task was `running` with no live daemon and no readable \
1243 run to recover; held for a human to check what happened",
1244 could_not_start: "could not start the run: ",
1245 resume_not_latest: |q, run| {
1246 format!("question {q} asked to resume run {run}, which is not this task's latest run")
1247 },
1248 resume_cannot_progress: |q, run, reason| {
1249 format!("question {q} asked to resume run {run}, which cannot make progress: {reason}")
1250 },
1251 resume_unreadable: |q, run, e| {
1252 format!("question {q} asked to resume run {run}, which could not be read: {e}")
1253 },
1254 handover_refused: |r| r.to_string(),
1255 handover_hint: " (clean up the other worktree, then release the task from the queue)",
1256 reviewers_never_answered: |missing, rounds| {
1257 format!(
1258 "{missing} reviewer seat(s) never answered after {rounds} rounds; \
1259 refusing to call it clean"
1260 )
1261 },
1262};
1263
1264const PHRASES_JA: Phrases = Phrases {
1265 graph_stopped: |status, detail| {
1266 format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
1267 },
1268 quorum_lost: "審査パネルが定足数を失いました",
1269 quota_took_out: "。クォータで脱落: ",
1270 run_ended: "run 終了: ",
1271 waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
1272 recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
1273 no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
1274 何が起きたか人が確認するため保留にしました",
1275 could_not_start: "run を開始できませんでした: ",
1276 resume_not_latest: |q, run| {
1277 format!(
1278 "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
1279 )
1280 },
1281 resume_cannot_progress: |q, run, reason| {
1282 format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません: {reason}")
1283 },
1284 resume_unreadable: |q, run, e| {
1285 format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
1286 },
1287 handover_refused: |r| {
1288 use crate::handover::Refused;
1289 match r {
1290 Refused::Foreign { branch, path, why } => format!(
1291 "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
1292 削除しません。不要なら `git worktree remove` でその worktree を削除して\
1293 から、やり直してください(詳細: {why})"
1294 ),
1295 Refused::Unsafe { branch, path, why } => format!(
1296 "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
1297 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
1298 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
1299 ),
1300 Refused::ReleaseFailed { branch, path, run } => format!(
1301 "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
1302 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1303 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1304 ),
1305 }
1306 },
1307 handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1308 reviewers_never_answered: |missing, rounds| {
1309 format!(
1310 "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1311 クリーンとは認めません"
1312 )
1313 },
1314};
1315
1316fn phrases(language: &str) -> &'static Phrases {
1317 if crate::lang::is_japanese(language) {
1318 &PHRASES_JA
1319 } else {
1320 &PHRASES_EN
1321 }
1322}
1323
1324fn language_of(task: &Task, fallback: &Path) -> String {
1328 crate::lang::of_repo(&repo_for(task, fallback))
1329}
1330
1331pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1335 if q.node == crate::conduct::NODE {
1336 return tasks.iter().find(|t| t.id == q.run);
1337 }
1338 tasks.iter().find(|t| t.runs.contains(&q.run))
1339}
1340
1341fn repair_choice_offers(questions: &Questions) {
1344 let ownership = crate::task_chat::InquiryOwnership::default();
1345 for q in questions
1346 .list_for_effects_in(&ownership)
1347 .into_iter()
1348 .filter(|q| {
1349 q.status.open()
1350 && q.node == crate::conduct::NODE
1351 && q.choices
1352 .iter()
1353 .any(|c| crate::choice_effect::describe(q, c).is_none())
1354 })
1355 {
1356 let _ = questions.update_in(&q.id, &ownership, |current| {
1357 if current.status.open() {
1358 crate::choice_effect::executable_conductor(current);
1359 if let Some(deputy) = &mut current.deputy {
1360 deputy.brief = crate::deputy::brief(
1361 ¤t.run,
1362 ¤t.detail,
1363 ¤t.choices,
1364 ¤t.actions,
1365 );
1366 }
1367 }
1368 Ok(())
1369 });
1370 }
1371}
1372
1373pub async fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1376 apply_maintenance_choices(queue, questions, home).await;
1377 apply_task_choice_actions(queue, questions, home);
1378}
1379
1380async fn apply_maintenance_choices(queue: &Queue, questions: &Questions, home: &Path) {
1383 let ownership = crate::task_chat::InquiryOwnership::default();
1384 for q in questions.list_for_effects_in(&ownership) {
1385 let Ok(_execution) = crate::task_inquiry::Outbox::at(home).execution_claim(&q.id) else {
1387 continue;
1388 };
1389 let Ok(q) = questions.get_for_effects_in(&q.id, &ownership) else {
1390 continue;
1391 };
1392 let Some(action) = q.chosen_action().filter(|a| a.maintenance()) else {
1393 continue;
1394 };
1395 if asker_may_still_read(questions, &q, home) || !ask::valid_asset_name(&q.id) {
1398 continue;
1399 }
1400 if queue.list().iter().any(|task| {
1401 (task.id == q.run
1402 || task.runs.contains(&q.run)
1403 || q.routed_task.as_deref() == Some(&task.id))
1404 && task.stale_question(&q)
1405 }) {
1406 continue;
1407 }
1408 if let ask::ChoiceAction::RecoverBase { run, stop, episode } = action {
1409 let tasks = queue.list();
1410 let owner = crate::task_chat::task_of(&q, &tasks);
1411 if let Some(owner) = owner
1412 && q.routed_task
1413 .as_deref()
1414 .is_none_or(|routed| routed == owner)
1415 {
1416 let result = crate::base_recovery_control::recover(
1417 queue,
1418 home,
1419 crate::base_recovery_control::Request {
1420 run: run.clone(),
1421 head: stop.head.clone(),
1422 actor: "decisions".into(),
1423 request: q.id.clone(),
1424 decision: Some((owner, q.answered_at.unwrap_or(q.asked_at))),
1425 expected_stop: Some((stop.clone(), *episode)),
1426 evidence_digest: None,
1427 },
1428 )
1429 .await;
1430 if let Err(error) = result {
1431 tracing::warn!(question = %q.id, %error, "base recovery decision refused");
1432 notices::raise_in(home, Notice::warn(
1433 &format!("base-recovery:{}", q.id),
1434 format!("Base recovery decision {} was refused: {error:#}. Inspect the existing run and request; no replacement run was started.", q.id),
1435 ).link(Link::Run { id: run.clone() }));
1436 }
1437 }
1438 continue;
1439 }
1440 let dir = home.join("choice-actions");
1441 if std::fs::create_dir_all(&dir).is_err() {
1442 continue;
1443 }
1444 let Ok(lock) = std::fs::OpenOptions::new()
1445 .create(true)
1446 .truncate(false)
1447 .write(true)
1448 .open(dir.join(format!("{}.lock", q.id)))
1449 else {
1450 continue;
1451 };
1452 if crate::pr_head::try_lock_file(&lock).is_err() {
1453 continue;
1454 }
1455 let fresh = !home
1456 .join("choice-actions")
1457 .join(format!("{}.json", q.id))
1458 .exists();
1459 let result = async {
1460 let receipt = dir.join(format!("{}.json", q.id));
1461 if receipt.exists() {
1462 let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&receipt)?)?;
1463 anyhow::ensure!(
1464 prior.get("status").and_then(|s| s.as_str()) == Some("applied"),
1465 "previous maintenance attempt did not confirm completion; inspect its receipt"
1466 );
1467 return Ok::<_, anyhow::Error>(());
1468 }
1469 let record = |status: &str| -> anyhow::Result<()> {
1472 let tmp = receipt.with_extension("tmp");
1473 std::fs::write(
1474 &tmp,
1475 serde_json::to_vec(&serde_json::json!({
1476 "action": action, "status": status,
1477 }))?,
1478 )?;
1479 std::fs::rename(tmp, &receipt)?;
1480 Ok(())
1481 };
1482 let applied = async {
1483 match action {
1484 ask::ChoiceAction::ResumeRun { run } => {
1485 crate::resume::validate(home, run)?;
1486 record("started")?;
1487 let decided = q.answered_at.unwrap_or(q.asked_at);
1488 if !crate::resume::pin_queued(queue, run, Some(decided), Some(&q.id))? {
1489 crate::resume::validate_unqueued(home, run)?;
1490 crate::resume::start(home, run.clone()).await?;
1491 }
1492 }
1493 ask::ChoiceAction::ReleaseTask {
1494 task,
1495 held_at,
1496 reason,
1497 } => {
1498 anyhow::ensure!(
1499 queue.resolve_id(task)? == *task,
1500 "task action requires an exact task ID"
1501 );
1502 let _claim = queue.claim(task)?;
1503 let mut task = queue.get(task)?;
1504 if task.action_applied(&q.id) {
1505 return Ok(());
1506 }
1507 if q.node == crate::conduct::NODE
1512 && q.run == task.id
1513 && task.status == TaskStatus::Blocked
1514 && task.blocked_from == Some(TaskStatus::Held)
1515 && task.blocked_by.as_slice() == [q.id.as_str()]
1516 {
1517 task.unblock(&q.id);
1518 }
1519 anyhow::ensure!(
1520 task.status == TaskStatus::Held
1521 && task.held_at == Some(*held_at)
1522 && task.hold_reason.as_deref() == reason.as_deref()
1523 && task
1524 .operator_decided_at
1525 .is_none_or(|at| at <= q.answered_at.unwrap_or(q.asked_at)),
1526 "task no longer has the hold this question names"
1527 );
1528 task.release_operator("choice", Some(&q.id));
1529 task.mark_action_applied(&q.id);
1530 queue.put(&mut task)?;
1531 }
1532 ask::ChoiceAction::AbandonRun { run } => {
1533 record("started")?;
1534 crate::driver::abandon_proven_dead(home, run)?;
1535 }
1536 ask::ChoiceAction::RerunChecks {
1537 repo,
1538 pr,
1539 head,
1540 runs,
1541 } => {
1542 rerun_checks_once(home, &q.id, repo, pr, head, runs, || record("started"))
1543 .await?;
1544 }
1545 _ => unreachable!(),
1546 }
1547 Ok::<_, anyhow::Error>(())
1548 }
1549 .await;
1550 match applied {
1551 Ok(()) => record("applied"),
1552 Err(e) => {
1553 record(&format!("refused or failed: {e:#}"))?;
1554 Err(e)
1555 }
1556 }
1557 }
1558 .await;
1559 if home
1564 .join("choice-actions")
1565 .join(format!("{}.json", q.id))
1566 .exists()
1567 && let Some(listed) = task_of_question(&queue.list(), &q)
1568 && !listed.action_applied(&q.id)
1569 && let Ok(_claim) = queue.claim(&listed.id)
1570 && let Ok(mut origin) = queue.get(&listed.id)
1571 {
1572 if !origin.operator_held()
1573 && origin.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1574 && !matches!(origin.status, TaskStatus::Running | TaskStatus::Done)
1575 {
1576 if result.is_err() || matches!(action, ask::ChoiceAction::ResumeRun { .. }) {
1577 origin.hold_machine(Some(format!(
1578 "Maintenance choice {} settled; inspect its target before releasing this task",
1579 q.id
1580 )));
1581 } else {
1582 origin.unblock(&q.id);
1583 }
1584 }
1585 origin.mark_action_applied(&q.id);
1586 let _ = queue.put(&mut origin);
1587 }
1588 if let Err(e) = result
1589 && fresh
1590 {
1591 notices::raise_in(
1592 home,
1593 Notice::warn(
1594 &format!("action:{}", q.id),
1595 format!("Choice action {} was not completed: {e:#}", q.id),
1596 )
1597 .link(if q.run_names_task() {
1598 Link::Task { id: q.run.clone() }
1599 } else {
1600 Link::Run { id: q.run.clone() }
1601 }),
1602 );
1603 }
1604 }
1605}
1606
1607pub(crate) async fn rerun_checks_once(
1614 home: &Path,
1615 request: &str,
1616 repo: &Path,
1617 pr: &str,
1618 head: &str,
1619 runs: &[String],
1620 started: impl FnOnce() -> anyhow::Result<()>,
1621) -> anyhow::Result<()> {
1622 use crate::release_watch::{GhForge, ReleaseForge};
1623 anyhow::ensure!(
1624 !runs.is_empty()
1625 && runs.len() <= 20
1626 && runs
1627 .iter()
1628 .all(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
1629 && !pr.starts_with('-'),
1630 "invalid rerun targets"
1631 );
1632 let snap = GhForge.snapshot(repo, pr).await?;
1633 anyhow::ensure!(
1634 snap.head == head && snap.state == crate::land::PrLifecycle::Open,
1635 "pull request head or lifecycle changed"
1636 );
1637 anyhow::ensure!(
1638 runs.iter().all(|r| snap
1639 .checks
1640 .iter()
1641 .any(|c| c.run.as_ref() == Some(r) && crate::release_watch::is_failed(c.verdict))),
1642 "named workflow is no longer failed on this pull request"
1643 );
1644 started()?;
1645 let dir = home.join("choice-actions");
1646 std::fs::create_dir_all(&dir)?;
1647 let rerun_lock = std::fs::OpenOptions::new()
1648 .create(true)
1649 .truncate(false)
1650 .write(true)
1651 .open(dir.join("reruns.lock"))?;
1652 crate::pr_head::try_lock_file(&rerun_lock)?;
1653 let ledger = dir.join("reruns.json");
1654 let mut recorded: std::collections::BTreeSet<String> = if ledger.exists() {
1655 serde_json::from_slice(&std::fs::read(&ledger)?)?
1656 } else {
1657 Default::default()
1658 };
1659 for run in runs {
1660 let key = serde_json::to_string(&(request, repo, pr, head, run))?;
1661 if !recorded.insert(key) {
1662 continue;
1663 }
1664 let tmp = ledger.with_extension("tmp");
1665 std::fs::write(&tmp, serde_json::to_vec(&recorded)?)?;
1666 std::fs::rename(tmp, &ledger)?;
1667 GhForge.rerun(repo, run).await?;
1668 }
1669 Ok(())
1670}
1671
1672pub(crate) fn apply_task_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1681 let tasks = queue.list();
1682 let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
1683 for q in questions.list_for_effects_in(&ownership) {
1684 let Ok(_execution) = crate::task_inquiry::Outbox::at(home).execution_claim(&q.id) else {
1686 continue;
1687 };
1688 let Ok(q) = questions.get_for_effects_in(&q.id, &ownership) else {
1689 continue;
1690 };
1691 if q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1693 continue;
1694 }
1695 if q.chosen_action().is_none_or(|a| a.maintenance()) {
1696 continue;
1697 }
1698 let Some(listed) = task_of_question(&tasks, &q) else {
1699 if q.node == land::APPROVAL_NODE
1700 && q.resolution().as_deref().is_some_and(|choice| {
1701 choice == land::REPAIR || crate::merge_decision::stops(choice)
1702 })
1703 {
1704 notices::raise_in(
1705 home,
1706 Notice::warn(
1707 &format!("repair-owner:{}", q.id),
1708 format!(
1709 "Approval action is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing task.",
1710 q.run, q.run
1711 ),
1712 ).link(Link::Run { id: q.run.clone() }),
1713 );
1714 }
1715 continue;
1716 };
1717 if listed.action_applied(&q.id) {
1718 continue;
1719 }
1720 let Ok(_claim) = queue.claim(&listed.id) else {
1721 continue;
1722 };
1723 let Ok(mut task) = queue.get(&listed.id) else {
1724 continue;
1725 };
1726 if q.node == crate::conduct::NODE && task.status == TaskStatus::Blocked {
1729 let blockers: Vec<_> = task
1730 .blocked_by
1731 .iter()
1732 .filter(|id| {
1733 crate::queue::dependency(queue, questions, id)
1734 == crate::queue::Dependency::Question(q.id.clone())
1735 })
1736 .cloned()
1737 .collect();
1738 if !blockers.is_empty() {
1739 for id in blockers {
1740 task.unblock(&id);
1741 }
1742 let answer = match &q.answer {
1743 Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
1744 None => String::new(),
1745 };
1746 task.record_answer(q.summary.clone(), answer);
1747 }
1748 }
1749 let language = language_of(&task, Path::new("."));
1750 let mut decision = decide_action(home, &task, &q, phrases(&language), |id| {
1751 RunState::load_under(id, home)
1752 });
1753 let completion = if matches!(decision, ActionDecision::Done) {
1754 match crate::task_completion::prepare_close(
1755 &task,
1756 home,
1757 CompletionActor::DaemonSettle,
1758 Some(format!(
1759 "Question {}: {} — {}",
1760 q.id,
1761 q.summary,
1762 q.resolution().unwrap_or_default()
1763 )),
1764 false,
1765 ) {
1766 Ok(context) => Some(context),
1767 Err(error) => {
1768 decision = ActionDecision::Refuse(error.to_string());
1769 None
1770 }
1771 }
1772 } else {
1773 None
1774 };
1775 let ran = matches!(
1776 decision,
1777 ActionDecision::Resume(_)
1778 | ActionDecision::Requeue
1779 | ActionDecision::Hold
1780 | ActionDecision::Done
1781 );
1782 if ran && asker_may_still_read(questions, &q, home) {
1783 continue;
1792 }
1793 let done = matches!(decision, ActionDecision::Done);
1794 let completed = matches!(
1797 decision,
1798 ActionDecision::Requeue | ActionDecision::Hold | ActionDecision::Done
1799 );
1800 match decision {
1801 ActionDecision::Skip => continue,
1802 ActionDecision::Resume(run) => {
1803 task.release_operator("choice", Some(&q.id));
1804 task.resume_override = Some(crate::queue::OperatorResume {
1805 question_id: q.id.clone(),
1806 at: Timestamp::now(),
1807 conductor_rehold: None,
1808 forced: true,
1809 pinned_run: Some(run),
1810 });
1811 }
1812 ActionDecision::Stale => {}
1813 ActionDecision::Requeue => {
1814 task.release_operator("choice-requeue", Some(&q.id));
1815 task.requeue();
1816 }
1817 ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1818 ActionDecision::Done => {
1819 task.succeed(completion.expect("done passed completion admission"));
1820 }
1821 ActionDecision::Refuse(why) => {
1822 let _ =
1823 crate::task_inquiry::Outbox::at(home).update_decision(&q.id, |d| d.fail(&why));
1824 if task.operator_held() {
1825 task.hold_reason = Some(match task.hold_reason.take() {
1828 Some(reason) => format!("{reason}\n\n{why}"),
1829 None => why,
1830 });
1831 } else {
1832 task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1833 task.hold_machine(Some(why));
1834 }
1835 notices::raise(
1836 Notice::warn(
1837 &format!("action:{}", q.id),
1838 "An answered task action could not be applied; the task stays held.",
1839 )
1840 .link(Link::Task {
1841 id: task.id.clone(),
1842 }),
1843 );
1844 }
1845 }
1846 task.mark_action_applied(&q.id);
1847 if completed {
1848 task.decision_effects.insert(
1849 q.id.clone(),
1850 format!("decision: {}", q.resolution().expect("answered action")),
1851 );
1852 }
1853 record(queue, &mut task);
1856 if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1857 supersede_prior_runs(&task, home);
1858 }
1859 let _ = questions.update_in(&q.id, &ownership, |r| {
1862 r.answer_delivered = true;
1863 Ok(())
1864 });
1865 }
1866}
1867
1868fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1872 let now = Timestamp::now();
1873 if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1874 return true;
1875 }
1876 q.node != crate::conduct::NODE
1877 && RunState::load_under(&q.run, home).is_ok_and(|s| {
1878 s.seats_active()
1879 .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1880 })
1881}
1882
1883fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1894 let tasks = queue.list();
1895 let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
1896 let by_id: std::collections::BTreeMap<&str, &Task> =
1897 tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1898 let referenced: Vec<&str> = tasks
1899 .iter()
1900 .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1901 .collect();
1902
1903 for mut question in questions.list_for_effects_in(&ownership) {
1904 if !question.status.open()
1905 || question.node != crate::conduct::NODE
1906 || questions.held_reply_in(&question.id, &ownership)
1907 {
1908 continue;
1909 }
1910 if referenced
1915 .iter()
1916 .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1917 {
1918 continue;
1919 }
1920 let Some(task) = by_id.get(question.run.as_str()) else {
1921 continue;
1922 };
1923 question.abandon(format!(
1924 "task {} no longer waits for this answer",
1925 task.short()
1926 ));
1927 if let Err(e) = questions.put_in(&mut question, &ownership) {
1928 tracing::warn!(
1929 "could not retire question {} for task {}: {e:#}",
1930 question.short(),
1931 task.short()
1932 );
1933 }
1934 }
1935}
1936
1937#[derive(Debug, Clone, Copy)]
1944pub struct Verdict {
1945 pub status: RunStatus,
1947 pub left_pr: bool,
1949 pub quota_hit: bool,
1951 pub parked: bool,
1953 pub no_viable_candidates: bool,
1960}
1961
1962pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
2021 settle_in(task, verdict, detail, max_attempts, &PHRASES_EN, None)
2022}
2023
2024fn settle_in(
2026 task: &mut Task,
2027 verdict: Verdict,
2028 detail: &str,
2029 max_attempts: usize,
2030 p: &Phrases,
2031 state: Option<&RunState>,
2032) {
2033 if verdict.parked {
2039 task.park(detail);
2040 return;
2041 }
2042 let completion = |task: &Task| match state {
2043 Some(state) => CompletionContext::from_run(
2044 CompletionActor::DaemonSettle,
2045 Some(detail.to_owned()),
2046 task,
2047 state,
2048 ),
2049 None => CompletionContext::new(
2050 CompletionActor::DaemonSettle,
2051 Some(detail.to_owned()),
2052 &crate::run::home(),
2053 task,
2054 ),
2055 };
2056 match verdict.status {
2057 RunStatus::Merged | RunStatus::Ready
2058 if task.pr_recovery.as_ref().is_some_and(|s| {
2059 s.disposition != Some(crate::pr_recovery::Disposition::Review)
2060 }) =>
2061 {
2062 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()));
2063 }
2064 RunStatus::Merged | RunStatus::Ready => task.succeed(completion(task)),
2065 RunStatus::AlreadyInBase => task.already_landed(detail, completion(task)),
2066 RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
2067 RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
2068 task.stall(detail)
2069 }
2070 RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
2071 RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
2072 RunStatus::Blocked => task.fail(detail, max_attempts),
2073 RunStatus::VerifiedNoop if state.is_none_or(RunState::all_candidates_verified_noop) => {
2074 task.handed_off(detail)
2075 }
2076 RunStatus::VerifiedNoop => task.fail(detail, max_attempts),
2077 other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
2078 }
2079}
2080
2081pub fn supersede_prior_runs(task: &Task, home: &Path) {
2130 if task
2131 .completion_history
2132 .last()
2133 .is_some_and(|event| event.discard)
2134 {
2135 return;
2136 }
2137 let now = Timestamp::now();
2138 let last_run_succeeded = task
2145 .runs
2146 .last()
2147 .and_then(|id| RunState::load_under(id, home).ok())
2148 .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
2149 for id in task.superseded_attempts(last_run_succeeded) {
2150 let mut state = match RunState::load_under(id, home) {
2151 Ok(s) => s,
2152 Err(e) => {
2153 tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
2154 continue;
2155 }
2156 };
2157 if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
2158 continue;
2159 }
2160 let daemon_claims = is_working_on(home, id, now);
2161 if state.liveness(daemon_claims) == Liveness::Live {
2162 continue;
2163 }
2164 state.status = RunStatus::Superseded;
2165 if let Err(e) = state.save_under(home) {
2166 tracing::warn!("could not mark run {id} superseded: {e:#}");
2167 }
2168 }
2169}
2170
2171fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
2193 for task in queue.list() {
2194 if task.status != TaskStatus::Done || task.runs.len() < 2 {
2195 continue;
2196 }
2197 supersede_prior_runs(&task, home);
2198 }
2199}
2200
2201fn settle_and_diagnose(
2208 task: &mut Task,
2209 verdict: Verdict,
2210 detail: &str,
2211 max_attempts: usize,
2212 state: &RunState,
2213) {
2214 let mut verdict = verdict;
2215 let mut detail = detail;
2216 if verdict.status == RunStatus::VerifiedNoop && !state.all_candidates_verified_noop() {
2217 verdict.status = RunStatus::Failed;
2221 verdict.quota_hit = false;
2222 detail = "no-change result lacks verified evidence";
2223 }
2224 let p = phrases(&state.config.graph.language);
2225 if let Some(d) = &state.merge_decision {
2228 use crate::merge_decision as md;
2229 if task
2230 .execution_runs()
2231 .last()
2232 .is_some_and(|id| id != &state.id)
2233 {
2234 return;
2235 }
2236 if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
2237 task.succeed(CompletionContext::from_run(
2238 CompletionActor::DaemonSettle,
2239 Some(format!("Owner merge decision {}: {}", d.question, d.choice)),
2240 task,
2241 state,
2242 ));
2243 } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
2244 if state.liveness(false) != Liveness::Dead {
2245 task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
2246 return;
2247 }
2248 let replacement = md::Replacement {
2249 question: d.question.clone(),
2250 run: state.id.clone(),
2251 pr: d.target.pr.clone(),
2252 agent: agent.to_owned(),
2253 context: format!(
2254 "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
2255 d.target.pr,
2256 state.id,
2257 serde_json::to_string(&state.reviews).unwrap_or_default()
2258 ),
2259 };
2260 task.requeue();
2261 task.pr_recovery = None;
2262 task.review_of = None;
2263 task.replacement = Some(replacement);
2264 } else {
2265 task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
2266 format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
2267 } 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())) }));
2268 }
2269 task.mark_action_applied(&d.question);
2270 if d.choice.eq_ignore_ascii_case(land::HOLD) {
2271 task.decision_effects
2272 .insert(d.question.clone(), format!("decision: {}", d.choice));
2273 }
2274 if let Some(pass) = state.passes.last() {
2275 task.record_pass_at(
2276 &state.id,
2277 pass.index,
2278 Some(pass.started_at),
2279 task.attempts,
2280 None,
2281 );
2282 }
2283 return;
2284 }
2285 if let Some(replacement) = &task.replacement
2286 && !state.parked
2287 && state.resource_block.is_none()
2288 && (state.viable().is_empty()
2289 || (state.status == RunStatus::Blocked && state.tally.is_none()))
2290 {
2291 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)));
2292 return;
2293 }
2294 if !verdict.parked && verdict.quota_hit && state.status == RunStatus::Stalled {
2295 let mut agents: Vec<_> = state
2296 .quota
2297 .iter()
2298 .filter(|q| {
2299 q.cause == crate::agent::QuotaCause::Authentication
2300 && state
2301 .passes
2302 .last()
2303 .is_none_or(|pass| q.at >= pass.started_at)
2304 })
2305 .map(|q| q.agent.as_str())
2306 .collect();
2307 agents.sort_unstable();
2308 agents.dedup();
2309 if !agents.is_empty() {
2310 task.stall(detail);
2311 task.notice_cause("agent-authentication", None, None);
2312 task.hold_machine(Some(format!("[authentication] Agents {} cannot authenticate; re-authenticate, then resume the held task. No attempt was spent.", agents.join(", "))));
2313 return;
2314 }
2315 }
2316 let attempts_before = task.attempts;
2317 if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
2324 let disk_checked_at = task.disk_checked_at;
2325 task.notice_cause(
2326 &format!("resource:{}:{}", block.kind, block.node),
2327 None,
2328 None,
2329 );
2330 task.last_error = Some(detail.to_owned());
2331 task.diagnostic = None;
2332 task.attempts = task.attempts.saturating_sub(1);
2333 if block.kind == "agent authentication" {
2334 task.hold_machine(Some(format!(
2335 "[authentication] {}; no attempt was spent",
2336 block.detail
2337 )));
2338 } else if block.kind == "agent usage limit" {
2339 if let Some(agent) = &state.config.graph.selected_implementer {
2341 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.")));
2342 } else {
2343 task.status = TaskStatus::Failed;
2344 task.last_error = Some(block.detail.clone());
2345 }
2346 } else if block.kind == "disk pressure" {
2347 task.hold_machine(Some(format!(
2348 "{}{}",
2349 crate::disk::RUNNING_PRESSURE,
2350 block.detail
2351 )));
2352 } else {
2353 task.hold_machine(Some(format!(
2354 "{}{}; no attempt was spent; resume to retry the affected operation",
2355 crate::cache::RESOURCE_HOLD,
2356 block.description()
2357 )));
2358 }
2359 if matches!(block.kind.as_str(), "disk pressure" | "disk admission")
2360 && matches!(block.cause, crate::run::ResourceBlockCause::Other)
2361 {
2362 task.mark_disk_capacity();
2363 task.disk_checked_at = disk_checked_at;
2364 }
2365 if let Some(pass) = state.passes.last() {
2366 task.record_pass_at(
2367 &state.id,
2368 pass.index,
2369 Some(pass.started_at),
2370 attempts_before,
2371 None,
2372 );
2373 }
2374 return;
2375 }
2376 if let Some(hold) = state.land_unrelated.as_ref().filter(|hold| {
2377 state.parked
2378 && state.status == RunStatus::Landing
2379 && state
2380 .pr_pushed_head
2381 .as_ref()
2382 .is_none_or(|h| h == &hold.head)
2383 && task.execution_runs().last() == Some(&state.id)
2384 }) {
2385 let pass = state.passes.last().map_or(0, |p| p.index);
2388 if !task
2389 .passes
2390 .iter()
2391 .any(|p| p.run == state.id && p.pass_index == pass)
2392 {
2393 task.attempts = task.attempts.saturating_sub(1);
2394 }
2395 task.hold_machine(Some(format!(
2396 "[ci-unrelated] CI failure reproduced on base; owner question {}",
2397 hold.question
2398 )));
2399 task.last_error = Some(detail.to_owned());
2400 task.diagnostic = None;
2401 task.record_pass_at(
2402 &state.id,
2403 pass,
2404 state.passes.last().map(|p| p.started_at),
2405 attempts_before,
2406 Some(crate::run::ParkCause::Question),
2407 );
2408 return;
2409 }
2410 let unresolved = task.hold_notice_cause.clone();
2411 let head_e2e_stop = crate::head_e2e_stop::conclusive(state)
2412 .filter(|_| !verdict.parked && !verdict.quota_hit && task.pr_recovery.is_none());
2413 let mut reconsumed_head_e2e = false;
2414 if state.base_sync_blocked() {
2415 task.hold_machine(Some(detail.to_owned()));
2417 task.last_error = Some(detail.to_owned());
2418 } else if state.land_sync_exhausted() {
2419 task.hold_machine(Some(format!("{detail} {}", state.land_sync_next_action())));
2420 task.last_error = Some(detail.to_owned());
2421 } else if !verdict.parked
2422 && task
2423 .pr_recovery
2424 .as_ref()
2425 .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
2426 && matches!(
2427 verdict.status,
2428 RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
2429 )
2430 {
2431 if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
2432 task.succeed(CompletionContext::from_run(
2433 CompletionActor::DaemonSettle,
2434 Some(detail.to_owned()),
2435 task,
2436 state,
2437 ));
2438 } else {
2439 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()));
2440 }
2441 } else if !verdict.parked
2442 && task.pr_recovery.is_some()
2443 && matches!(
2444 verdict.status,
2445 RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
2446 )
2447 && !verdict.quota_hit
2448 {
2449 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.")));
2450 } else if let Some(stop) = head_e2e_stop.clone() {
2451 if crate::head_e2e_stop::reconsumed_without_new_verification(state, &stop) {
2456 reconsumed_head_e2e = true;
2457 let pass = state.passes.last().map_or(0, |p| p.index);
2458 if !task
2459 .passes
2460 .iter()
2461 .any(|p| p.run == state.id && p.pass_index == pass)
2462 {
2463 task.attempts = task.attempts.saturating_sub(1);
2464 }
2465 }
2466 let reason = crate::head_e2e_stop::hold_reason(task, state, &stop, None);
2467 task.hold_head_e2e(stop, reason, detail.to_owned());
2468 } else {
2469 settle_in(task, verdict, detail, max_attempts, p, Some(state));
2470 }
2471 if !verdict.parked
2472 && !verdict.quota_hit
2473 && !reconsumed_head_e2e
2474 && matches!(
2475 verdict.status,
2476 RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
2477 )
2478 {
2479 task.recovery_failed(state);
2480 }
2481 if state.prep_failure.is_some() {
2482 task.hold_notice_cause = unresolved;
2485 task.startup_notice_cause("startup-candidates");
2486 }
2487 if let Some(pass) = state.passes.last() {
2490 let parked = match &pass.end {
2491 Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2492 _ => None,
2493 };
2494 task.record_pass_at(
2495 &state.id,
2496 pass.index,
2497 Some(pass.started_at),
2498 attempts_before,
2499 parked,
2500 );
2501 }
2502 if task.status == TaskStatus::Held {
2503 if state.base_sync_blocked() {
2504 task.base_sync_notice(state);
2505 } else if state.land_sync_exhausted() {
2506 task.land_sync_notice(state);
2507 } else if let Some(stop) = &head_e2e_stop {
2508 task.head_e2e_notice(stop);
2509 } else if state.prep_failure.is_none() {
2510 task.notice_cause(
2511 label(verdict.status),
2512 Some(&state.id),
2513 state.passes.last().map(|p| p.index),
2514 );
2515 }
2516 task.diagnostic = diagnostic(state);
2517 note_open_question(task, &state.id, p);
2518 }
2519}
2520
2521fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2536 let Some(home) = crate::run::try_home() else {
2537 return;
2538 };
2539 let open = Questions::at(home.join("questions")).open_for(run);
2540 let Some(q) = open.first() else {
2541 return;
2542 };
2543 let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2544 decisions.sort_unstable();
2545 task.notice_cause(
2546 &format!("questions:{}", decisions.join(",")),
2547 Some(run),
2548 None,
2549 );
2550 let base = task.hold_reason.clone().unwrap_or_default();
2551 task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2552}
2553
2554fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2565 if let Some(request) = task.sync_only.clone() {
2566 crate::base_sync_only::settle(task, &request, last_run.as_ref(), None);
2567 return;
2568 }
2569 match last_run {
2570 Some(state) => {
2571 let verdict = Verdict {
2572 status: state.status,
2573 left_pr: state.pr.is_some(),
2574 quota_hit: state.quota.iter().any(|loss| {
2575 state
2576 .passes
2577 .last()
2578 .is_none_or(|pass| loss.at >= pass.started_at)
2579 }),
2580 parked: state.parked,
2581 no_viable_candidates: state.viable().is_empty(),
2582 };
2583 let detail = format!(
2584 "{}{}",
2585 phrases(&state.config.graph.language).recovered_running,
2586 describe(&state)
2587 );
2588 settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2589 }
2590 None => {
2591 let why = phrases(language).no_run_to_recover;
2594 task.last_error = Some(why.to_owned());
2595 task.notice_cause("missing-run", None, None);
2598 task.hold_machine(Some(why.to_owned()));
2599 }
2600 }
2601}
2602
2603fn reclaim_orphaned_running(
2625 queue: &Queue,
2626 max_attempts: usize,
2627 live_workers: &std::collections::BTreeSet<String>,
2628) -> Vec<String> {
2629 let mut reclaimed = Vec::new();
2630 for listed in queue.list() {
2631 if listed.status != TaskStatus::Running || live_workers.contains(&listed.id) {
2632 continue;
2633 }
2634 let Ok(_claim) = queue.claim(&listed.id) else {
2635 continue;
2636 };
2637 let Ok(mut task) = queue.get(&listed.id) else {
2641 continue;
2642 };
2643 if task.status != TaskStatus::Running {
2644 continue;
2645 }
2646 let last_run = task
2647 .execution_runs()
2648 .last()
2649 .and_then(|id| RunState::load(id).ok());
2650 if let Some(state) = &last_run
2660 && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2661 {
2662 tracing::warn!("abandon questions for {}: {e:#}", state.id);
2663 }
2664 let language = if last_run.is_none() {
2665 language_of(&task, Path::new("."))
2666 } else {
2667 String::new()
2668 };
2669 reclaim(&mut task, last_run, max_attempts, &language);
2670 if task.status == TaskStatus::Done {
2671 supersede_prior_runs(&task, &crate::run::home());
2672 }
2673 record(queue, &mut task);
2674 reclaimed.push(task.id.clone());
2675 }
2676 reclaimed
2677}
2678
2679fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2711 reclaim_abandoned_runs_with(
2712 home,
2713 now,
2714 crate::proc::pid_status,
2715 crate::proc::process_started_at,
2716 )
2717}
2718
2719fn reclaim_abandoned_runs_with<F, G>(
2725 home: &Path,
2726 now: Timestamp,
2727 query: F,
2728 identity: G,
2729) -> Vec<String>
2730where
2731 F: Fn(u32) -> Option<bool>,
2732 G: Fn(u32) -> Option<String>,
2733{
2734 let mut abandoned = Vec::new();
2735 for entry in std::fs::read_dir(home.join("runs"))
2736 .into_iter()
2737 .flatten()
2738 .flatten()
2739 {
2740 let id = entry.file_name().to_string_lossy().into_owned();
2741 if !crate::run::is_run_id(&id) {
2742 continue;
2743 }
2744 let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2747 continue;
2748 };
2749 let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2757 continue;
2758 };
2759 let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2760 continue;
2761 };
2762 if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2763 continue;
2764 }
2765 let daemon_claims = is_working_on(home, &id, now);
2777 if state.liveness_under_with(home, daemon_claims, &query, &identity)
2778 != crate::run::Liveness::Dead
2779 {
2780 continue;
2781 }
2782 state.abandon("daemon");
2783 if let Err(e) = state.save_under(home) {
2784 tracing::warn!("could not persist abandoned run {id}: {e:#}");
2785 continue;
2786 }
2787 if let Some(notice) = notices::run_ended(&state) {
2790 notices::raise_in(home, notice);
2791 }
2792 if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2800 tracing::warn!("abandon questions for {id}: {e:#}");
2801 }
2802 abandoned.push(id);
2803 }
2804 abandoned
2805}
2806
2807#[derive(Debug, Clone, Serialize, Deserialize)]
2808struct TaskWorker {
2809 opts: Opts,
2810 queue: PathBuf,
2811 task: String,
2812 #[serde(default)]
2813 lane: PermitKind,
2814 #[serde(default)]
2815 standalone: bool,
2816}
2817
2818#[doc(hidden)]
2819pub struct TaskWorkerLease {
2820 pub job: crate::worker::Job,
2821 dir: PathBuf,
2822 lease: Option<crate::worker::Lease>,
2823}
2824
2825impl TaskWorkerLease {
2826 pub fn release_lease(&mut self) {
2827 self.lease = None;
2828 }
2829}
2830
2831impl Drop for TaskWorkerLease {
2832 fn drop(&mut self) {
2833 self.release_lease();
2834 let _ = std::fs::remove_dir_all(&self.dir);
2835 }
2836}
2837
2838#[doc(hidden)]
2840pub fn live_task_fixture(home: &Path, task: &str) -> Result<TaskWorkerLease> {
2841 let request = TaskWorker {
2842 opts: Opts::default(),
2843 queue: home.join("queue"),
2844 task: task.to_owned(),
2845 lane: PermitKind::default(),
2846 standalone: true,
2847 };
2848 let (job, lease) = crate::worker::running_fixture(
2849 home,
2850 &format!("task:{task}"),
2851 serde_json::to_value(request)?,
2852 )?;
2853 Ok(TaskWorkerLease {
2854 dir: home.join("workers").join("jobs").join(&job.id),
2855 job,
2856 lease: Some(lease),
2857 })
2858}
2859
2860fn task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2861 Ok(crate::worker::active(home)?
2862 .into_iter()
2863 .filter(|job| job.kind == "task")
2864 .collect())
2865}
2866
2867fn owned_task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2868 task_jobs(home)?
2869 .into_iter()
2870 .filter_map(
2871 |job| match serde_json::from_value::<TaskWorker>(job.payload.clone()) {
2872 Ok(request) if !request.standalone => Some(Ok(job)),
2873 Ok(_) => None,
2874 Err(error) => Some(Err(error.into())),
2875 },
2876 )
2877 .collect()
2878}
2879
2880#[must_use]
2882pub fn managed(home: &Path) -> bool {
2883 match crate::worker::active(home) {
2884 Err(error) => {
2885 tracing::error!("cannot determine scheduler ownership: {error:#}");
2886 true
2887 }
2888 Ok(jobs) if jobs.iter().any(|j| j.kind == "scheduler") => true,
2889 Ok(_) => {
2890 read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2891 && crate::worker::try_lease(home, "scheduler").map_or(true, |lease| lease.is_none())
2892 }
2893 }
2894}
2895
2896pub async fn spawn_detached(home: &Path, opts: &Opts) -> Result<crate::worker::Job> {
2898 anyhow::ensure!(
2899 crate::worker::control(home, "scheduler")?.is_none() || !managed(home),
2900 "the scheduler is stopping; wait for retirement before starting it again"
2901 );
2902 crate::worker::spawn(
2903 home,
2904 "scheduler",
2905 "scheduler",
2906 serde_json::to_value(opts.absolute()?)?,
2907 )
2908 .await
2909}
2910
2911fn park_request_path(home: &Path, job: &crate::worker::Job) -> PathBuf {
2912 home.join("worker-parks").join(format!("{}.json", job.id))
2913}
2914
2915fn request_task_park(
2916 home: &Path,
2917 job: &crate::worker::Job,
2918 cause: crate::run::ParkCause,
2919) -> Result<()> {
2920 let path = park_request_path(home, job);
2921 std::fs::create_dir_all(path.parent().context("worker park directory")?)?;
2922 std::fs::write(path, serde_json::to_vec(&cause)?)?;
2923 crate::worker::request(home, &job.key, crate::worker::Control::Park)
2924}
2925
2926pub fn request_control(home: &Path, control: crate::worker::Control) -> Result<()> {
2928 if control == crate::worker::Control::Park {
2929 for job in owned_task_jobs(home)? {
2930 request_task_park(home, &job, crate::run::ParkCause::Operator)?;
2931 }
2932 }
2933 crate::worker::request(home, "scheduler", control)
2934}
2935
2936pub(crate) fn scheduler_restart_options(home: &Path) -> Result<Option<Opts>> {
2938 if let Some(job) = crate::worker::active(home)?
2939 .into_iter()
2940 .find(|job| job.kind == "scheduler")
2941 {
2942 return serde_json::from_value(job.payload)
2943 .context("read detached scheduler options")
2944 .map(Some);
2945 }
2946 if read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2947 && crate::worker::try_lease(home, "scheduler")?.is_none()
2948 {
2949 let path = home.join("scheduler-options.json");
2950 let body = std::fs::read(&path).with_context(|| format!("read {}", path.display()))?;
2951 return serde_json::from_slice(&body)
2952 .context("decode detached scheduler options")
2953 .map(Some);
2954 }
2955 Ok(None)
2956}
2957
2958pub async fn restart_detached(home: &Path) -> Result<()> {
2960 let Some(opts) = scheduler_restart_options(home)? else {
2961 return Ok(());
2962 };
2963 request_control(home, crate::worker::Control::Stop)?;
2964 loop {
2965 let reserved = crate::worker::active(home)?
2966 .iter()
2967 .any(|job| job.kind == "scheduler");
2968 if !reserved && crate::worker::try_lease(home, "scheduler")?.is_some() {
2969 break;
2970 }
2971 tokio::time::sleep(Duration::from_millis(100)).await;
2972 }
2973 spawn_detached(home, &opts).await?;
2974 Ok(())
2975}
2976
2977pub async fn run_scheduler_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2979 let opts: Opts = serde_json::from_value(payload)?;
2980 let _ = home;
2981 serve_until(opts, Stop::new()).await
2982}
2983
2984pub async fn run_task_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2986 let request: TaskWorker = serde_json::from_value(payload)?;
2987 let queue = Queue::at(request.queue);
2988 let key = format!("task:{}", request.task);
2989 let job = task_jobs(home)?
2990 .into_iter()
2991 .find(|job| job.key == key)
2992 .context("task worker reservation is missing")?;
2993 let park_path = park_request_path(home, &job);
2994 let _claim = loop {
2997 match queue.claim(&request.task) {
2998 Ok(claim) => break claim,
2999 Err(e) if e.chain().any(|c| c.is::<std::io::Error>()) => {
3002 return Err(e.context("claim the task for its worker"));
3003 }
3004 Err(_) => {
3005 sweep_stale_claims(&queue, STALE_CLAIM);
3006 tokio::time::sleep(Duration::from_millis(50)).await;
3007 }
3008 }
3009 };
3010 let mut task = queue.get(&request.task)?;
3011 if !task.status.runnable()
3012 || (!request.standalone
3013 && request.lane
3014 != permit_kind(
3015 land_resume_state(&task) == LandResume::Ready,
3016 task.immediate,
3017 task.urgent,
3018 ))
3019 {
3020 return Ok(());
3021 }
3022 let stop = Stop::new();
3023 let watcher = {
3024 let home = home.to_path_buf();
3025 let stop = stop.clone();
3026 let park_path = park_path.clone();
3027 tokio::spawn(async move {
3028 loop {
3029 if crate::worker::control(&home, &key).ok().flatten().is_some() {
3030 let cause = std::fs::read(&park_path)
3031 .ok()
3032 .and_then(|body| serde_json::from_slice(&body).ok())
3033 .unwrap_or(crate::run::ParkCause::Operator);
3034 stop.park(cause);
3035 return;
3036 }
3037 tokio::time::sleep(Duration::from_millis(200)).await;
3038 }
3039 })
3040 };
3041 let quota = if request.standalone {
3042 run_claimed_until(&request.opts, &queue, &mut task, &stop).await
3043 } else {
3044 let status = Arc::new(Mutex::new(Status::new()));
3045 Box::pin(attempt(
3046 &request.opts,
3047 &queue,
3048 &status,
3049 &stop,
3050 crate::graph::Pause::new(),
3051 &mut task,
3052 ))
3053 .await
3054 };
3055 watcher.abort();
3056 let _ = std::fs::remove_file(park_path);
3057 persist_cooldown(home, "a).await?;
3058 Ok(())
3059}
3060
3061pub async fn spawn_claimed(
3064 home: &Path,
3065 opts: &Opts,
3066 queue: &Queue,
3067 task: &Task,
3068 claim: crate::queue::Claim,
3069) -> Result<crate::worker::Job> {
3070 let request = TaskWorker {
3071 opts: opts.absolute()?,
3072 queue: std::path::absolute(queue.root())?,
3073 task: task.id.clone(),
3074 lane: permit_kind(
3075 land_resume_state(task) == LandResume::Ready,
3076 task.immediate,
3077 task.urgent,
3078 ),
3079 standalone: true,
3080 };
3081 let job = crate::worker::spawn(
3082 home,
3083 "task",
3084 &format!("task:{}", task.id),
3085 serde_json::to_value(request)?,
3086 )
3087 .await?;
3088 drop(claim);
3089 Ok(job)
3090}
3091
3092pub async fn run_detached_claimed(
3095 opts: &Opts,
3096 queue: &Queue,
3097 task: &mut Task,
3098 claim: crate::queue::Claim,
3099) -> Result<()> {
3100 let home = crate::run::home();
3101 let job = spawn_claimed(&home, opts, queue, task, claim).await?;
3102 loop {
3103 crate::worker::active(&home)?;
3106 let current = crate::worker::get(&home, &job.id)?;
3107 if matches!(
3108 current.status,
3109 crate::worker::Status::Finished | crate::worker::Status::Failed
3110 ) {
3111 *task = queue.get(&task.id)?;
3112 anyhow::ensure!(
3113 current.status != crate::worker::Status::Failed,
3114 "task worker failed: {}",
3115 current.result.as_deref().unwrap_or("unknown failure")
3116 );
3117 return Ok(());
3118 }
3119 tokio::time::sleep(Duration::from_millis(200)).await;
3120 }
3121}
3122
3123async fn persist_cooldown(home: &Path, quota: &[QuotaLoss]) -> Result<()> {
3124 if let Some(until) = cooldown_until(quota, Timestamp::now()) {
3125 let _lease = loop {
3126 if let Some(lease) = crate::worker::try_lease(home, "task-quota-cooldown")? {
3127 break lease;
3128 }
3129 tokio::time::sleep(Duration::from_millis(10)).await;
3130 };
3131 if read_cooldown(home)?.is_none_or(|previous| previous < until) {
3132 let path = home.join("task-quota-cooldown.json");
3133 let temporary = path.with_extension("json.tmp");
3134 std::fs::write(&temporary, serde_json::to_vec(&until)?)?;
3135 std::fs::rename(temporary, path)?;
3136 }
3137 }
3138 Ok(())
3139}
3140
3141fn read_cooldown(home: &Path) -> Result<Option<Timestamp>> {
3142 match std::fs::read(home.join("task-quota-cooldown.json")) {
3143 Ok(body) => Ok(Some(serde_json::from_slice(&body)?)),
3144 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
3145 Err(error) => Err(error.into()),
3146 }
3147}
3148
3149pub async fn serve(opts: Opts) -> Result<()> {
3155 tracing::info!(
3156 "automatic update and restart requires magi web; standalone serve does not restart"
3157 );
3158 serve_until(opts, Stop::new()).await
3159}
3160
3161pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
3172 let opts = opts.absolute()?;
3173 let home = crate::run::home();
3174 let _scheduler = crate::worker::try_lease(&home, "scheduler")?
3175 .context("another scheduler already owns this home")?;
3176 if let Some(reading) = read_status(&home)
3177 && legacy_scheduler_running(&reading, Timestamp::now(), std::process::id())
3178 {
3179 bail!("a legacy scheduler is still running; stop it before starting independent dispatch");
3180 }
3181 if !crate::worker::active(&home)?
3182 .iter()
3183 .any(|job| job.kind == "scheduler")
3184 {
3185 crate::worker::clear_control(&home, "scheduler")?;
3186 }
3187 std::fs::write(
3188 home.join("scheduler-options.json"),
3189 serde_json::to_vec(&opts)?,
3190 )?;
3191 let control = {
3192 let home = home.clone();
3193 let stop = stop.clone();
3194 tokio::spawn(async move {
3195 loop {
3196 match crate::worker::control(&home, "scheduler").ok().flatten() {
3197 Some(crate::worker::Control::Park) => {
3198 let _ = request_control(&home, crate::worker::Control::Park);
3199 stop.park(crate::run::ParkCause::Operator);
3200 break;
3201 }
3202 Some(crate::worker::Control::Stop) => {
3203 stop.stop();
3204 break;
3205 }
3206 None => {}
3207 }
3208 tokio::time::sleep(Duration::from_millis(100)).await;
3209 }
3210 })
3211 };
3212 let signal = {
3213 let stop = stop.clone();
3214 tokio::spawn(async move {
3215 if tokio::signal::ctrl_c().await.is_ok() {
3216 stop.stop();
3217 tracing::info!("scheduler shutdown requested; independent workers continue");
3218 }
3219 })
3220 };
3221
3222 let worktrees_root = opts
3223 .worktrees_root
3224 .clone()
3225 .unwrap_or_else(crate::run::default_worktree_root);
3226 let outcome = drive(
3227 &opts,
3228 &Queue::open(),
3229 &status_path(),
3230 &crate::run::home(),
3231 &worktrees_root,
3232 &stop,
3233 )
3234 .await;
3235
3236 signal.abort();
3237 control.abort();
3238 outcome
3239}
3240
3241async fn drive(
3254 opts: &Opts,
3255 queue: &Queue,
3256 status_file: &Path,
3257 home: &Path,
3258 worktrees_root: &Path,
3259 stop: &Stop,
3260) -> Result<()> {
3261 let recovery_cfg = prepare(&opts.repo, opts).ok();
3269 let daemon_cfg = recovery_cfg
3270 .as_ref()
3271 .map(|c| c.daemon.clone())
3272 .unwrap_or_default();
3273 let reconciled = crate::driver::reconcile(home);
3274 if !reconciled.is_empty() {
3275 tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
3276 }
3277 let mut initial_status = Status::new();
3278 let owned = owned_task_jobs(home)?;
3279 initial_status.current = current_work(home, Timestamp::now())
3280 .into_iter()
3281 .filter(|current| {
3282 owned
3283 .iter()
3284 .any(|job| job.key.strip_prefix("task:") == Some(current.task.as_str()))
3285 })
3286 .collect();
3287 initial_status.idle = initial_status.current.is_empty();
3288 initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
3289 recovery_cfg.as_ref(),
3290 daemon_cfg.max_deputies,
3291 ));
3292 let status = Arc::new(Mutex::new(initial_status));
3293 write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
3294 let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
3295
3296 let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
3302
3303 tracing::info!(
3304 "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
3305 queue.root().display(),
3306 opts.poll.as_secs(),
3307 opts.max_attempts,
3308 concurrency,
3309 if daemon_cfg.pause_for_interrupts {
3310 ", interrupts enabled"
3311 } else {
3312 ""
3313 }
3314 );
3315
3316 let outcome = tokio::select! {
3317 outcome = poll(opts, queue, &status, home, worktrees_root, stop, DispatchLimits {
3318 max_concurrent: concurrency,
3319 pause_for_interrupts: daemon_cfg.pause_for_interrupts,
3320 recovery_cfg,
3321 }) => outcome,
3322 () = async {
3323 while !stop.stopped() {
3324 tokio::time::sleep(Duration::from_millis(25)).await;
3325 }
3326 } => {
3327 if stop.parking() {
3328 request_control(home, crate::worker::Control::Park)?;
3329 }
3330 Ok(())
3331 }
3332 };
3333
3334 stop.busy.store(0, Ordering::SeqCst);
3335 beat.abort();
3336 clear_status_at(status_file);
3337 outcome
3338}
3339
3340pub(crate) fn release_watch_settings_from_config(
3343 home: &Path,
3344 repo: &Path,
3345 cfg: &Config,
3346) -> (Vec<PathBuf>, u64) {
3347 let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
3348 .into_iter()
3349 .map(|r| r.path)
3350 .collect();
3351 let mut known: Vec<PathBuf> = Queue::at(home.join("queue"))
3354 .list()
3355 .into_iter()
3356 .map(|t| t.repo)
3357 .collect();
3358 let runs = home.join("runs");
3359 for id in crate::run::list_ids_in(&runs) {
3360 let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
3361 .ok()
3362 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
3363 .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
3364 known.extend(repo);
3365 }
3366 for k in known {
3367 let k = k.canonicalize().unwrap_or(k);
3368 if k.join(".git").exists() && !paths.contains(&k) {
3369 paths.push(k);
3370 }
3371 }
3372 let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
3373 if !paths.contains(&own) {
3374 paths.push(own);
3375 }
3376 (paths, cfg.daemon.release_stall_minutes)
3377}
3378
3379const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
3381
3382async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
3388 loop {
3389 tokio::time::sleep(HEARTBEAT).await;
3390 let snapshot = {
3391 let mut guard = lock(&status);
3392 guard.updated_at = Timestamp::now();
3393 guard.clone()
3394 };
3395 if let Err(e) = write_status_to(&path, &snapshot) {
3396 tracing::warn!("could not refresh the daemon status file: {e:#}");
3399 }
3400 }
3401}
3402
3403#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3406enum LandResume {
3407 NotLanding,
3410 StillWaiting,
3415 Ready,
3419}
3420
3421fn land_resume_state(task: &Task) -> LandResume {
3425 if task.sync_only.is_some() {
3426 return LandResume::NotLanding;
3427 }
3428 let Some(run_id) = task.execution_runs().last() else {
3429 return LandResume::NotLanding;
3430 };
3431 let Ok(state) = RunState::load(run_id) else {
3432 return LandResume::NotLanding;
3433 };
3434 if !state.parked {
3435 return LandResume::NotLanding;
3436 }
3437 if state.status == RunStatus::Landing
3438 && state.land_approval.as_ref().is_some_and(|binding| {
3439 ask::Questions::open()
3440 .get_for_effects(&binding.question)
3441 .is_ok_and(|q| {
3442 q.run == state.id
3443 && q.resolution()
3444 .as_deref()
3445 .is_some_and(crate::merge_decision::stops)
3446 })
3447 })
3448 {
3449 return LandResume::Ready;
3450 }
3451 if !implementers_match(task, &state) {
3452 return LandResume::NotLanding;
3453 }
3454 let node = if state.status == RunStatus::Landing {
3458 land::APPROVAL_NODE
3459 } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
3460 crate::github_text::ASK_NODE
3461 } else {
3462 return LandResume::NotLanding;
3463 };
3464 let store = ask::Questions::open();
3465 let waiting = store
3466 .list_for_effects()
3467 .into_iter()
3468 .filter(|q| &q.run == run_id && q.node == node)
3469 .max_by(|a, b| a.id.cmp(&b.id));
3470 let Some(mut q) = waiting else {
3471 return LandResume::Ready;
3472 };
3473 if !q.status.open() {
3474 if q.resolution().as_deref() == Some(land::REPAIR) {
3477 return if state.liveness(false) == Liveness::Live {
3478 LandResume::StillWaiting
3479 } else {
3480 LandResume::NotLanding
3481 };
3482 }
3483 return LandResume::Ready;
3484 }
3485 let timeout = Duration::from_secs(state.config.graph.answer_timeout);
3492 let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
3493 if !store.held_reply(&q.id) && elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
3494 q.abandon(format!(
3495 "no answer within {}s of asking",
3496 timeout.as_secs().max(1)
3497 ));
3498 if store.put(&mut q).is_ok() {
3501 return LandResume::Ready;
3502 }
3503 }
3504 LandResume::StillWaiting
3505}
3506
3507const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
3515
3516const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
3528
3529#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3542enum Interrupt {
3543 Idle,
3545 Parking {
3557 parked: Vec<String>,
3558 interrupt_task: String,
3559 },
3560 Running {
3568 parked: Vec<String>,
3569 interrupt_task: String,
3570 },
3571 Resuming { parked: Vec<String> },
3578}
3579
3580fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
3601 match state {
3602 Interrupt::Idle => {
3603 if in_flight.len() != 1 {
3615 return Interrupt::Idle;
3616 }
3617 match runnable.iter().find(|t| t.interrupt) {
3618 Some(t) => Interrupt::Parking {
3619 parked: in_flight.to_vec(),
3620 interrupt_task: t.id.clone(),
3621 },
3622 None => Interrupt::Idle,
3623 }
3624 }
3625 Interrupt::Parking {
3626 parked,
3627 interrupt_task,
3628 } => {
3629 if in_flight.iter().any(|id| parked.contains(id)) {
3630 Interrupt::Parking {
3632 parked,
3633 interrupt_task,
3634 }
3635 } else if in_flight.contains(&interrupt_task) {
3636 Interrupt::Running {
3637 parked,
3638 interrupt_task,
3639 }
3640 } else if runnable.iter().any(|t| t.id == interrupt_task) {
3641 Interrupt::Parking {
3645 parked,
3646 interrupt_task,
3647 }
3648 } else {
3649 Interrupt::Resuming { parked }
3654 }
3655 }
3656 Interrupt::Running {
3657 parked,
3658 interrupt_task,
3659 } => {
3660 if in_flight.contains(&interrupt_task) {
3661 Interrupt::Running {
3662 parked,
3663 interrupt_task,
3664 }
3665 } else {
3666 Interrupt::Resuming { parked }
3672 }
3673 }
3674 Interrupt::Resuming { parked } => {
3675 if in_flight.iter().any(|id| parked.contains(id)) {
3676 Interrupt::Idle
3682 } else if runnable.iter().any(|t| parked.contains(&t.id)) {
3683 Interrupt::Resuming { parked }
3684 } else {
3685 Interrupt::Idle
3688 }
3689 }
3690 }
3691}
3692
3693fn advance_interrupt_tick(
3699 enabled: bool,
3700 state: Interrupt,
3701 in_flight: &[String],
3702 runnable: &[Task],
3703) -> Interrupt {
3704 if !enabled {
3705 return Interrupt::Idle;
3706 }
3707 advance_interrupt(state, in_flight, runnable)
3708}
3709
3710fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
3715 match state {
3716 Interrupt::Idle => candidates,
3717 Interrupt::Parking {
3718 parked,
3719 interrupt_task,
3720 } => {
3721 if in_flight.iter().any(|id| parked.contains(id)) {
3722 Vec::new()
3723 } else {
3724 candidates
3725 .into_iter()
3726 .filter(|t| &t.id == interrupt_task)
3727 .collect()
3728 }
3729 }
3730 Interrupt::Running { .. } => Vec::new(),
3731 Interrupt::Resuming { parked } => candidates
3739 .into_iter()
3740 .find(|t| parked.contains(&t.id))
3741 .into_iter()
3742 .collect(),
3743 }
3744}
3745
3746struct DispatchLimits {
3750 max_concurrent: usize,
3753 pause_for_interrupts: bool,
3755 recovery_cfg: Option<Config>,
3756}
3757
3758#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3766pub(crate) enum PermitKind {
3767 None,
3772 Immediate,
3779 Urgent,
3786 #[default]
3789 Ordinary,
3790}
3791
3792impl PermitKind {
3793 pub(crate) fn label(self) -> &'static str {
3794 match self {
3795 Self::None => "decision",
3796 Self::Immediate => "immediate",
3797 Self::Urgent => "urgent",
3798 Self::Ordinary => "ordinary",
3799 }
3800 }
3801}
3802
3803fn permit_kind(priority: bool, immediate: bool, urgent: bool) -> PermitKind {
3807 if priority {
3808 PermitKind::None
3809 } else if immediate {
3810 PermitKind::Immediate
3811 } else if urgent {
3812 PermitKind::Urgent
3813 } else {
3814 PermitKind::Ordinary
3815 }
3816}
3817
3818fn available_slots(requests: &[TaskWorker], limit: usize) -> (usize, usize) {
3819 let (ordinary, urgent) = requests.iter().filter(|request| !request.standalone).fold(
3820 (0usize, 0usize),
3821 |(ordinary, urgent), request| match request.lane {
3822 PermitKind::Ordinary => (ordinary + 1, urgent),
3823 PermitKind::Urgent => (ordinary, urgent + 1),
3824 PermitKind::Immediate | PermitKind::None => (ordinary, urgent),
3825 },
3826 );
3827 (
3828 limit.saturating_sub(ordinary),
3829 1usize.saturating_sub(urgent),
3830 )
3831}
3832
3833#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
3835enum SkipReason {
3836 ClaimUnavailable,
3837 RereadFailed,
3838 NoLongerRunnable,
3839 WaitingOnLanding,
3840 CoolingDown,
3841 OrdinaryCapacity,
3842 UrgentCapacity,
3843 InterruptGate,
3844}
3845
3846impl SkipReason {
3847 fn key(self) -> &'static str {
3848 match self {
3849 Self::ClaimUnavailable => "claim_unavailable",
3850 Self::RereadFailed => "reread_failed",
3851 Self::NoLongerRunnable => "no_longer_runnable",
3852 Self::WaitingOnLanding => "waiting_on_landing",
3853 Self::CoolingDown => "cooling_down",
3854 Self::OrdinaryCapacity => "ordinary_capacity",
3855 Self::UrgentCapacity => "urgent_capacity",
3856 Self::InterruptGate => "interrupt_gate",
3857 }
3858 }
3859
3860 fn describe(self) -> &'static str {
3861 match self {
3862 Self::ClaimUnavailable => "could not claim it (held elsewhere or claim failed)",
3863 Self::RereadFailed => "could not re-read it",
3864 Self::NoLongerRunnable => "no longer runnable",
3865 Self::WaitingOnLanding => "waiting on landing",
3866 Self::CoolingDown => "quota cooldown",
3867 Self::OrdinaryCapacity => "no free ordinary slot",
3868 Self::UrgentCapacity => "urgent slot busy",
3869 Self::InterruptGate => "withheld by the interrupt sequence",
3870 }
3871 }
3872}
3873
3874#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3876pub struct DispatchReasonCount {
3877 pub reason: String,
3879 pub count: usize,
3881}
3882
3883#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3885pub struct DispatchWait {
3886 pub runnable: usize,
3888 pub reasons: Vec<DispatchReasonCount>,
3890}
3891
3892type DispatchSkips = std::collections::BTreeSet<(String, SkipReason)>;
3893
3894fn aggregate_dispatch_wait(runnable: usize, skips: &DispatchSkips) -> Option<DispatchWait> {
3895 if runnable == 0 {
3896 return None;
3897 }
3898 let mut counts = std::collections::BTreeMap::new();
3899 for (_, reason) in skips {
3900 *counts.entry(*reason).or_insert(0usize) += 1;
3901 }
3902 let mut counts: Vec<_> = counts.into_iter().collect();
3903 counts.sort_by(|(a, n), (b, m)| m.cmp(n).then(a.cmp(b)));
3904 Some(DispatchWait {
3905 runnable,
3906 reasons: counts
3907 .into_iter()
3908 .map(|(reason, count)| DispatchReasonCount {
3909 reason: reason.key().to_owned(),
3910 count,
3911 })
3912 .collect(),
3913 })
3914}
3915
3916fn interrupt_skips(before: &[String], after: &[Task]) -> DispatchSkips {
3917 before
3918 .iter()
3919 .filter(|id| !after.iter().any(|task| &task.id == *id))
3920 .map(|id| (id.clone(), SkipReason::InterruptGate))
3921 .collect()
3922}
3923
3924fn changed_dispatch_skips(previous: &mut DispatchSkips, current: DispatchSkips) -> bool {
3925 if *previous == current {
3926 return false;
3927 }
3928 *previous = current;
3929 true
3930}
3931
3932#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3936pub struct TaskAdmission {
3937 pub mode: &'static str,
3939 #[serde(default, skip_serializing_if = "Option::is_none")]
3942 pub reservation_lane: Option<&'static str>,
3943 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
3945 pub standalone: bool,
3946 pub state: &'static str,
3948 pub label: String,
3951 #[serde(default, skip_serializing_if = "Option::is_none")]
3953 pub blocker: Option<String>,
3954}
3955
3956#[derive(Debug, Clone)]
3959pub struct AdmissionSnapshot {
3960 now: Timestamp,
3961 daemon: std::result::Result<Option<Reading>, String>,
3962 scheduler_running: bool,
3963 active_workers:
3964 std::result::Result<std::collections::BTreeMap<String, (PermitKind, bool)>, String>,
3965 owned_in_flight: Vec<String>,
3966 owned_ordinary_count: usize,
3967 urgent_busy: bool,
3968 cache_service_active: bool,
3969 cooldown_until: std::result::Result<Option<Timestamp>, String>,
3970 interrupt: std::result::Result<Interrupt, String>,
3971}
3972
3973fn read_status_checked(home: &Path) -> std::result::Result<Option<Reading>, String> {
3974 let path = home.join("daemon.json");
3975 match std::fs::read_to_string(&path) {
3976 Ok(body) => serde_json::from_str(&body)
3977 .map(Some)
3978 .map_err(|e| format!("parse {}: {e}", path.display())),
3979 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
3980 Err(e) => Err(format!("read {}: {e}", path.display())),
3981 }
3982}
3983
3984fn read_interrupt_checked(home: &Path) -> std::result::Result<Interrupt, String> {
3985 let path = home.join("scheduler-interrupt.json");
3986 match std::fs::read(&path) {
3987 Ok(body) => {
3988 serde_json::from_slice(&body).map_err(|e| format!("parse {}: {e}", path.display()))
3989 }
3990 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Interrupt::Idle),
3991 Err(e) => Err(format!("read {}: {e}", path.display())),
3992 }
3993}
3994
3995fn skip_reason_label(key: &str) -> String {
3996 match key {
3997 "claim_unavailable" => "claimed by another process".to_owned(),
3998 "reread_failed" => "could not re-read task".to_owned(),
3999 "no_longer_runnable" => "no longer runnable".to_owned(),
4000 "waiting_on_landing" => "waiting on merge/posting approval".to_owned(),
4001 "cooling_down" => "quota cooldown".to_owned(),
4002 "ordinary_capacity" => "no free ordinary slot".to_owned(),
4003 "urgent_capacity" => "urgent slot busy".to_owned(),
4004 "interrupt_gate" => "withheld by active interrupt sequence".to_owned(),
4005 other => other.replace('_', " "),
4006 }
4007}
4008
4009fn land_resume_state_readonly(task: &Task, home: &Path, now: Timestamp) -> LandResume {
4012 if task.sync_only.is_some() {
4013 return LandResume::NotLanding;
4014 }
4015 let Some(run_id) = task.execution_runs().last() else {
4016 return LandResume::NotLanding;
4017 };
4018 let Ok(state) = RunState::load_under(run_id, home) else {
4019 return LandResume::NotLanding;
4020 };
4021 if !state.parked {
4022 return LandResume::NotLanding;
4023 }
4024 let store = ask::Questions::at(home.join("questions"));
4025 if state.status == RunStatus::Landing
4026 && state.land_approval.as_ref().is_some_and(|binding| {
4027 store.get_for_effects(&binding.question).is_ok_and(|q| {
4028 q.run == state.id
4029 && q.resolution()
4030 .as_deref()
4031 .is_some_and(crate::merge_decision::stops)
4032 })
4033 })
4034 {
4035 return LandResume::Ready;
4036 }
4037 if !implementers_match(task, &state) {
4038 return LandResume::NotLanding;
4039 }
4040 let node = if state.status == RunStatus::Landing {
4041 land::APPROVAL_NODE
4042 } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
4043 crate::github_text::ASK_NODE
4044 } else {
4045 return LandResume::NotLanding;
4046 };
4047 let waiting = store
4048 .list_for_effects()
4049 .into_iter()
4050 .filter(|q| &q.run == run_id && q.node == node)
4051 .max_by(|a, b| a.id.cmp(&b.id));
4052 let Some(q) = waiting else {
4053 return LandResume::Ready;
4054 };
4055 if !q.status.open() {
4056 if q.resolution().as_deref() == Some(land::REPAIR) {
4057 return if is_working_on(home, &state.id, now) {
4058 LandResume::StillWaiting
4059 } else {
4060 LandResume::NotLanding
4061 };
4062 }
4063 return LandResume::Ready;
4064 }
4065 LandResume::StillWaiting
4066}
4067
4068impl AdmissionSnapshot {
4069 #[must_use]
4071 pub fn capture(home: &Path, now: Timestamp) -> Self {
4072 let daemon = read_status_checked(home);
4073 let scheduler_running = daemon
4074 .as_ref()
4075 .ok()
4076 .and_then(Option::as_ref)
4077 .is_some_and(|reading| reading.running(now));
4078 let mut cache_service_active = false;
4079 let mut owned_in_flight = Vec::new();
4080 let mut owned_ordinary_count = 0usize;
4081 let mut urgent_busy = false;
4082 let active_workers = match crate::worker::observe_active_detailed(home) {
4083 Ok(entries) => {
4084 let mut map = std::collections::BTreeMap::new();
4085 let mut parse_err = None;
4086 for entry in entries {
4087 if entry.job.key == "service:daemon-cache" {
4088 cache_service_active = true;
4089 continue;
4090 }
4091 if entry.job.kind != "task" {
4092 continue;
4093 }
4094 match serde_json::from_value::<TaskWorker>(entry.job.payload) {
4095 Ok(request) => {
4096 if !request.standalone {
4097 owned_in_flight.push(request.task.clone());
4098 match request.lane {
4099 PermitKind::Ordinary => owned_ordinary_count += 1,
4100 PermitKind::Urgent => urgent_busy = true,
4101 PermitKind::Immediate | PermitKind::None => {}
4102 }
4103 }
4104 map.entry(request.task)
4105 .and_modify(|existing: &mut (PermitKind, bool)| {
4106 if existing.1 && !request.standalone {
4107 *existing = (request.lane, request.standalone);
4108 }
4109 })
4110 .or_insert((request.lane, request.standalone));
4111 }
4112 Err(e) => {
4113 parse_err = Some(format!(
4114 "invalid task worker payload for {}: {e}",
4115 entry.job.id
4116 ));
4117 break;
4118 }
4119 }
4120 }
4121 match parse_err {
4122 Some(err) => Err(err),
4123 None => Ok(map),
4124 }
4125 }
4126 Err(e) => Err(format!("{e:#}")),
4127 };
4128 let cooldown_until = read_cooldown(home).map_err(|e| format!("{e:#}"));
4129 let interrupt = read_interrupt_checked(home);
4130 Self {
4131 now,
4132 daemon,
4133 scheduler_running,
4134 active_workers,
4135 owned_in_flight,
4136 owned_ordinary_count,
4137 urgent_busy,
4138 cache_service_active,
4139 cooldown_until,
4140 interrupt,
4141 }
4142 }
4143
4144 fn format_waiting(task: &Task, reason: &str) -> String {
4145 if task.immediate {
4146 format!("Immediate: waiting — {reason}")
4147 } else if task.urgent {
4148 format!("Urgent: waiting — {reason}")
4149 } else {
4150 format!("Waiting — {reason}")
4151 }
4152 }
4153
4154 #[must_use]
4157 pub fn evaluate(
4158 &self,
4159 task: &Task,
4160 queue: &Queue,
4161 inv: Option<&crate::blockers::Inventory>,
4162 home: &Path,
4163 ) -> TaskAdmission {
4164 let mode = if task.immediate {
4165 "immediate"
4166 } else if task.urgent {
4167 "urgent"
4168 } else {
4169 "ordinary"
4170 };
4171
4172 if task.status == TaskStatus::Done {
4173 return TaskAdmission {
4174 mode,
4175 reservation_lane: None,
4176 standalone: false,
4177 state: "completed",
4178 label: "Completed".to_owned(),
4179 blocker: None,
4180 };
4181 }
4182
4183 if let Ok(workers) = &self.active_workers
4184 && let Some(&(lane, standalone)) = workers.get(&task.id)
4185 {
4186 let lane_label = lane.label();
4187 let base = if standalone {
4188 format!("Running (standalone, {lane_label} lane)")
4189 } else {
4190 format!("Running ({lane_label} lane)")
4191 };
4192 let resource_blocker = task
4193 .execution_runs()
4194 .last()
4195 .and_then(|run_id| RunState::load_under(run_id, home).ok())
4196 .and_then(|state| state.resource_wait)
4197 .map(|wait| {
4198 if wait.holder.trim().is_empty() {
4199 format!("waiting for {}", wait.kind)
4200 } else {
4201 format!("waiting for {} ({})", wait.kind, wait.holder)
4202 }
4203 });
4204 let label = match &resource_blocker {
4205 Some(reason) => format!("{base} — {reason}"),
4206 None => base,
4207 };
4208 return TaskAdmission {
4209 mode,
4210 reservation_lane: Some(lane_label),
4211 standalone,
4212 state: "running",
4213 label,
4214 blocker: resource_blocker,
4215 };
4216 }
4217
4218 if task.status == TaskStatus::Running {
4219 if self.active_workers.is_err() {
4220 let reason = "worker state unreadable".to_owned();
4221 return TaskAdmission {
4222 mode,
4223 reservation_lane: None,
4224 standalone: false,
4225 state: "unknown",
4226 label: Self::format_waiting(task, &reason),
4227 blocker: Some(reason),
4228 };
4229 }
4230 return TaskAdmission {
4231 mode,
4232 reservation_lane: None,
4233 standalone: false,
4234 state: "running",
4235 label: "Running".to_owned(),
4236 blocker: None,
4237 };
4238 }
4239
4240 if task.status == TaskStatus::Blocked {
4241 let waits = inv.map(|i| i.waits_on(task)).unwrap_or_default();
4242 let reason = if !waits.is_empty() {
4243 format!("waiting on dependencies ({})", waits.join(", "))
4244 } else if let Some(block_reason) = &task.block_reason {
4245 format!("blocked ({block_reason})")
4246 } else if !task.blocked_by.is_empty() {
4247 let ids: Vec<_> = task
4248 .blocked_by
4249 .iter()
4250 .map(|id| crate::run::short_of(id))
4251 .collect();
4252 format!("waiting on dependencies ({})", ids.join(", "))
4253 } else {
4254 "blocked on unresolved dependencies".to_owned()
4255 };
4256 return TaskAdmission {
4257 mode,
4258 reservation_lane: None,
4259 standalone: false,
4260 state: "waiting",
4261 label: Self::format_waiting(task, &reason),
4262 blocker: Some(reason),
4263 };
4264 }
4265
4266 if task.status == TaskStatus::Held {
4267 let reason = match &task.machine_hold_cause {
4268 Some(crate::queue::MachineHoldCause::DiskCapacity { reason, .. }) => {
4269 format!("disk admission ({reason})")
4270 }
4271 Some(crate::queue::MachineHoldCause::HeadE2e { .. }) => {
4272 let detail = task
4273 .hold_reason
4274 .as_deref()
4275 .unwrap_or("current head verify.e2e failed");
4276 format!("head e2e hold ({detail})")
4277 }
4278 None if task.hold_source == Some(crate::queue::HoldSource::Machine) => {
4279 let detail = task.hold_reason.as_deref().unwrap_or("held by daemon");
4280 if let Some(rest) = detail.strip_prefix("[resource] ") {
4281 format!("resource hold ({rest})")
4282 } else if let Some(rest) = detail.strip_prefix("[config] ") {
4283 format!("config hold ({rest})")
4284 } else {
4285 format!("machine hold ({detail})")
4286 }
4287 }
4288 None => match task.hold_reason.as_deref() {
4289 Some(reason) if !reason.trim().is_empty() => format!("held ({reason})"),
4290 _ => "held (release required)".to_owned(),
4291 },
4292 };
4293 return TaskAdmission {
4294 mode,
4295 reservation_lane: None,
4296 standalone: false,
4297 state: "waiting",
4298 label: Self::format_waiting(task, &reason),
4299 blocker: Some(reason),
4300 };
4301 }
4302
4303 if self.active_workers.is_err() {
4307 let reason = "worker state unreadable".to_owned();
4308 return TaskAdmission {
4309 mode,
4310 reservation_lane: None,
4311 standalone: false,
4312 state: "unknown",
4313 label: Self::format_waiting(task, &reason),
4314 blocker: Some(reason),
4315 };
4316 }
4317
4318 if queue.is_claimed(&task.id) {
4319 let reason = "claimed by another process".to_owned();
4320 return TaskAdmission {
4321 mode,
4322 reservation_lane: None,
4323 standalone: false,
4324 state: "waiting",
4325 label: Self::format_waiting(task, &reason),
4326 blocker: Some(reason),
4327 };
4328 }
4329
4330 if let Some(hold) = crate::head_e2e_stop::dispatch_hold(queue, task) {
4331 let reason = format!("head e2e stop ({})", hold.reason);
4332 return TaskAdmission {
4333 mode,
4334 reservation_lane: None,
4335 standalone: false,
4336 state: "waiting",
4337 label: Self::format_waiting(task, &reason),
4338 blocker: Some(reason),
4339 };
4340 }
4341
4342 let resume = land_resume_state_readonly(task, home, self.now);
4343 if resume == LandResume::StillWaiting {
4344 let reason = "waiting on merge/posting approval".to_owned();
4345 return TaskAdmission {
4346 mode,
4347 reservation_lane: None,
4348 standalone: false,
4349 state: "waiting",
4350 label: Self::format_waiting(task, &reason),
4351 blocker: Some(reason),
4352 };
4353 }
4354 let priority = resume == LandResume::Ready;
4355 let effective_lane = permit_kind(priority, task.immediate, task.urgent);
4356
4357 match &self.interrupt {
4358 Err(_) => {
4359 let reason = "interrupt state unreadable".to_owned();
4360 return TaskAdmission {
4361 mode,
4362 reservation_lane: None,
4363 standalone: false,
4364 state: "unknown",
4365 label: Self::format_waiting(task, &reason),
4366 blocker: Some(reason),
4367 };
4368 }
4369 Ok(interrupt)
4370 if *interrupt != Interrupt::Idle
4371 && interrupt_gate(interrupt, &self.owned_in_flight, vec![task.clone()])
4372 .is_empty() =>
4373 {
4374 let reason = "withheld by active interrupt sequence".to_owned();
4375 return TaskAdmission {
4376 mode,
4377 reservation_lane: None,
4378 standalone: false,
4379 state: "waiting",
4380 label: Self::format_waiting(task, &reason),
4381 blocker: Some(reason),
4382 };
4383 }
4384 Ok(_) => {}
4385 }
4386
4387 if effective_lane != PermitKind::None {
4388 match &self.cooldown_until {
4389 Err(_) => {
4390 let reason = "quota cooldown state unreadable".to_owned();
4391 return TaskAdmission {
4392 mode,
4393 reservation_lane: None,
4394 standalone: false,
4395 state: "unknown",
4396 label: Self::format_waiting(task, &reason),
4397 blocker: Some(reason),
4398 };
4399 }
4400 Ok(Some(until)) if self.now < *until => {
4401 let secs = (until.as_second() - self.now.as_second()).max(1);
4402 let reason = format!("quota cooldown ({secs}s remaining)");
4403 return TaskAdmission {
4404 mode,
4405 reservation_lane: None,
4406 standalone: false,
4407 state: "waiting",
4408 label: Self::format_waiting(task, &reason),
4409 blocker: Some(reason),
4410 };
4411 }
4412 Ok(_) => {}
4413 }
4414 }
4415
4416 if self.cache_service_active {
4417 let reason = "waiting for cache maintenance service".to_owned();
4418 return TaskAdmission {
4419 mode,
4420 reservation_lane: None,
4421 standalone: false,
4422 state: "waiting",
4423 label: Self::format_waiting(task, &reason),
4424 blocker: Some(reason),
4425 };
4426 }
4427
4428 if self.daemon.is_err() {
4429 let reason = "scheduler status unreadable".to_owned();
4430 return TaskAdmission {
4431 mode,
4432 reservation_lane: None,
4433 standalone: false,
4434 state: "unknown",
4435 label: Self::format_waiting(task, &reason),
4436 blocker: Some(reason),
4437 };
4438 }
4439
4440 if self.scheduler_running
4441 && let Ok(Some(reading)) = &self.daemon
4442 && let Some(skip_key) = reading.dispatch_skips.get(&task.id)
4443 {
4444 let stale_capacity_skip = match effective_lane {
4445 PermitKind::None | PermitKind::Immediate => {
4446 matches!(skip_key.as_str(), "ordinary_capacity" | "urgent_capacity")
4447 }
4448 PermitKind::Urgent => skip_key == "ordinary_capacity",
4449 PermitKind::Ordinary => skip_key == "urgent_capacity",
4450 };
4451 if !stale_capacity_skip {
4452 let reason = skip_reason_label(skip_key);
4453 return TaskAdmission {
4454 mode,
4455 reservation_lane: None,
4456 standalone: false,
4457 state: "waiting",
4458 label: Self::format_waiting(task, &reason),
4459 blocker: Some(reason),
4460 };
4461 }
4462 }
4463
4464 if !self.scheduler_running {
4465 let reason = "scheduler not running".to_owned();
4466 return TaskAdmission {
4467 mode,
4468 reservation_lane: None,
4469 standalone: false,
4470 state: "waiting",
4471 label: Self::format_waiting(task, &reason),
4472 blocker: Some(reason),
4473 };
4474 }
4475
4476 match effective_lane {
4477 PermitKind::Immediate => TaskAdmission {
4478 mode,
4479 reservation_lane: None,
4480 standalone: false,
4481 state: "next_poll",
4482 label: "Immediate: next poll".to_owned(),
4483 blocker: None,
4484 },
4485 PermitKind::None => TaskAdmission {
4486 mode,
4487 reservation_lane: None,
4488 standalone: false,
4489 state: "next_poll",
4490 label: if task.immediate {
4491 "Immediate: next poll".to_owned()
4492 } else {
4493 "Decision resume: next poll".to_owned()
4494 },
4495 blocker: None,
4496 },
4497 PermitKind::Urgent => {
4498 if self.urgent_busy {
4499 let reason = "urgent slot busy".to_owned();
4500 TaskAdmission {
4501 mode,
4502 reservation_lane: None,
4503 standalone: false,
4504 state: "waiting",
4505 label: Self::format_waiting(task, &reason),
4506 blocker: Some(reason),
4507 }
4508 } else {
4509 TaskAdmission {
4510 mode,
4511 reservation_lane: None,
4512 standalone: false,
4513 state: "next_poll",
4514 label: "Urgent: next poll".to_owned(),
4515 blocker: None,
4516 }
4517 }
4518 }
4519 PermitKind::Ordinary => {
4520 if self.owned_ordinary_count == 0 {
4521 TaskAdmission {
4522 mode,
4523 reservation_lane: None,
4524 standalone: false,
4525 state: "next_poll",
4526 label: "Ordinary: next poll".to_owned(),
4527 blocker: None,
4528 }
4529 } else {
4530 TaskAdmission {
4531 mode,
4532 reservation_lane: None,
4533 standalone: false,
4534 state: "waiting",
4535 label: "Queued (ordinary lane)".to_owned(),
4536 blocker: None,
4537 }
4538 }
4539 }
4540 }
4541 }
4542}
4543
4544struct DispatchClaim {
4545 task: Task,
4546 claim: crate::queue::Claim,
4547 lane: PermitKind,
4548 permit: Option<tokio::sync::OwnedSemaphorePermit>,
4549}
4550
4551fn claim_dispatch(
4555 queue: &Queue,
4556 candidate: &Task,
4557 cooling_down: bool,
4558 ordinary: &Arc<tokio::sync::Semaphore>,
4559 urgent: &Arc<tokio::sync::Semaphore>,
4560) -> std::result::Result<DispatchClaim, SkipReason> {
4561 let claim = queue
4562 .claim(&candidate.id)
4563 .map_err(|_| SkipReason::ClaimUnavailable)?;
4564 let task = match queue.get(&candidate.id) {
4565 Ok(t) if t.status.runnable() => t,
4566 Ok(_) => return Err(SkipReason::NoLongerRunnable),
4567 Err(e) => {
4568 tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
4569 return Err(SkipReason::RereadFailed);
4570 }
4571 };
4572 if let Some(hold) = crate::head_e2e_stop::dispatch_hold(queue, &task) {
4573 let mut held = task;
4574 hold.apply(&mut held);
4575 record(queue, &mut held);
4576 return Err(SkipReason::NoLongerRunnable);
4577 }
4578 let resume = land_resume_state(&task);
4579 if resume == LandResume::StillWaiting {
4580 return Err(SkipReason::WaitingOnLanding);
4581 }
4582 let priority = resume == LandResume::Ready;
4583 if !priority && cooling_down {
4584 return Err(SkipReason::CoolingDown);
4585 }
4586 let lane = permit_kind(priority, task.immediate, task.urgent);
4590 let permit = match lane {
4591 PermitKind::None | PermitKind::Immediate => None,
4592 PermitKind::Urgent => Some(
4593 Arc::clone(urgent)
4594 .try_acquire_owned()
4595 .map_err(|_| SkipReason::UrgentCapacity)?,
4596 ),
4597 PermitKind::Ordinary => Some(
4598 Arc::clone(ordinary)
4599 .try_acquire_owned()
4600 .map_err(|_| SkipReason::OrdinaryCapacity)?,
4601 ),
4602 };
4603 let stamp = Timestamp::now();
4606 let mut task = task;
4607 task.dispatched_at = Some(stamp);
4608 if let Err(e) = queue.modify(&task.id, |t| {
4609 t.dispatched_at = Some(stamp);
4610 true
4611 }) {
4612 tracing::warn!("could not record dispatch order of {}: {e:#}", task.short());
4613 }
4614 Ok(DispatchClaim {
4615 task,
4616 claim,
4617 lane,
4618 permit,
4619 })
4620}
4621
4622#[derive(Serialize, Deserialize)]
4641struct ServiceWorker {
4642 opts: Opts,
4643 queue: PathBuf,
4644 worktrees_root: PathBuf,
4645 operation: String,
4646}
4647
4648fn load_conductor(home: &Path) -> Result<Conductor> {
4649 match std::fs::read(home.join("conductor-state.json")) {
4650 Ok(body) => serde_json::from_slice(&body).context("read conductor state"),
4651 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Conductor::new()),
4652 Err(error) => Err(error.into()),
4653 }
4654}
4655
4656fn conductor_work(queue: &Queue, home: &Path) -> (Vec<Task>, Vec<Task>, Vec<Task>) {
4657 let live: std::collections::BTreeSet<_> = current_work(home, Timestamp::now())
4658 .into_iter()
4659 .map(|c| c.task)
4660 .collect();
4661 let stalled = stalled_tasks(queue, home, Timestamp::now());
4662 let stalled_ids: std::collections::BTreeSet<_> = stalled.iter().map(|t| t.id.clone()).collect();
4663 let finished = finished_tasks(queue)
4664 .into_iter()
4665 .filter(|t| !live.contains(&t.id) && !stalled_ids.contains(&t.id))
4666 .filter(|t| !awaiting_resume_with(t, |id| RunState::load_under(id, home)))
4667 .collect();
4668 let queued = queued_tasks(queue)
4669 .into_iter()
4670 .filter(|t| !live.contains(&t.id))
4671 .collect();
4672 (queued, stalled, finished)
4673}
4674
4675fn retention_service_receipt(
4678 home: &Path,
4679 operation: &str,
4680 phase: &str,
4681 outcome: &str,
4682 detail: &str,
4683 cfg: Option<&Config>,
4684) {
4685 retention_service_receipt_with(
4686 home,
4687 operation,
4688 phase,
4689 outcome,
4690 detail,
4691 cfg,
4692 serde_json::Value::Null,
4693 );
4694}
4695
4696fn retention_service_receipt_with(
4700 home: &Path,
4701 operation: &str,
4702 phase: &str,
4703 outcome: &str,
4704 detail: &str,
4705 cfg: Option<&Config>,
4706 extra: serde_json::Value,
4707) {
4708 if !matches!(operation, "housekeeping" | "disk-pressure" | "fold") {
4709 return;
4710 }
4711 let mut receipt = serde_json::json!({"checked_at": Timestamp::now(),
4712 "version": env!("CARGO_PKG_VERSION"), "pid": std::process::id(),
4713 "operation": operation, "outcome": outcome, "detail": detail,
4714 "auto_fold": cfg.map(|c| c.disk.auto_fold),
4715 "reclaim_free_bytes": cfg.map(|c| c.disk.reclaim_threshold()),
4716 "reclaim_bytes": cfg.map(|c| c.disk.worktree_reclaim_bytes)});
4717 if let (Some(receipt), serde_json::Value::Object(extra)) = (receipt.as_object_mut(), extra) {
4718 receipt.extend(extra);
4719 }
4720 if let Err(error) = crate::fold_evidence::atomic_write(
4721 &home.join(format!("source-eviction-{operation}-{phase}.json")),
4722 &serde_json::to_vec(&receipt).expect("service receipt"),
4723 ) {
4724 tracing::warn!("retention service receipt failed: {error:#}");
4725 }
4726}
4727
4728fn retention_summary(report: &crate::retention::Report) -> serde_json::Value {
4732 let clip = |text: &String| text.chars().take(300).collect::<String>();
4733 serde_json::json!({"retention": {
4734 "checked_at": report.checked_at,
4735 "freed_bytes": report.freed_bytes,
4736 "retired": report.retired,
4737 "retained": report.retained.len(),
4738 "failure_count": report.failures.len(),
4739 "failures": report.failures.iter().take(8).map(clip).collect::<Vec<_>>(),
4740 }})
4741}
4742
4743const FOLD_TURN_INTERVAL_SECS: u64 = 120;
4763
4764fn housekeeping_eligible(busy: bool, runnable: bool) -> bool {
4766 !busy && !runnable
4767}
4768
4769fn fold_turn_eligible(busy: bool, runnable: bool, cfg: Option<&Config>) -> bool {
4774 !housekeeping_eligible(busy, runnable) && cfg.is_some_and(|cfg| cfg.disk.auto_fold)
4775}
4776
4777async fn start_service(
4778 home: &Path,
4779 opts: &Opts,
4780 queue: &Queue,
4781 worktrees_root: &Path,
4782 operation: &str,
4783 cfg: Option<&Config>,
4784 busy: bool,
4785) -> Result<()> {
4786 let fetch_cfg = if operation == "fetch" {
4789 match prepare(&opts.repo, opts) {
4790 Ok(cfg) => Some(cfg),
4791 Err(error) => {
4792 tracing::warn!("could not reload periodic fetch configuration: {error:#}");
4793 return Ok(());
4794 }
4795 }
4796 } else {
4797 None
4798 };
4799 let cfg = fetch_cfg.as_ref().or(cfg);
4800 let ticks = home.join("service-ticks");
4801 std::fs::create_dir_all(&ticks)?;
4802 let receipt = ticks.join(format!("daemon-{operation}"));
4803 let last = std::fs::read(&receipt)
4804 .ok()
4805 .and_then(|body| serde_json::from_slice::<Timestamp>(&body).ok());
4806 let interval = match operation {
4807 "disk-pressure" => 30,
4808 "fold" => FOLD_TURN_INTERVAL_SECS,
4809 "chat-goals" | "decisions" => 60,
4810 "cache" => CACHE_CHECK_INTERVAL_SECS,
4811 "fetch" => cfg.map_or(60, |cfg| cfg.repos.fetch_interval.max(1)),
4812 _ => opts.poll.as_secs().max(1),
4813 };
4814 let now = Timestamp::now();
4815 if !cache_check_due(last, now, interval) {
4816 retention_service_receipt(
4817 home,
4818 operation,
4819 "dispatch",
4820 "skipped",
4821 "cadence not due",
4822 cfg,
4823 );
4824 return Ok(());
4825 }
4826 let key = format!("service:daemon-{operation}");
4827 let active = crate::worker::active(home)?;
4828 if active.iter().any(|job| job.key == key) {
4829 retention_service_receipt(
4830 home,
4831 operation,
4832 "dispatch",
4833 "skipped",
4834 "service worker already active",
4835 cfg,
4836 );
4837 return Ok(());
4838 }
4839 let sibling = match operation {
4842 "housekeeping" => Some("service:daemon-fold"),
4843 "fold" => Some("service:daemon-housekeeping"),
4844 _ => None,
4845 };
4846 if sibling.is_some_and(|sibling| active.iter().any(|job| job.key == sibling)) {
4847 retention_service_receipt(
4848 home,
4849 operation,
4850 "dispatch",
4851 "skipped",
4852 "another finished-run folding service is active",
4853 cfg,
4854 );
4855 return Ok(());
4856 }
4857 let eligible = match operation {
4858 "conductor" => {
4859 let (queued, stalled, finished) = conductor_work(queue, home);
4860 !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
4861 && load_conductor(home)?.worth_a_look(queue, &stalled, &finished)
4862 }
4863 "maintenance" => {
4864 queue.list().iter().any(|task| {
4865 crate::triage::disk_wait_eligible(task)
4866 && task
4867 .disk_checked_at
4868 .is_none_or(|at| now.as_second() - at.as_second() >= 60)
4869 }) || Questions::at(home.join("questions"))
4870 .list_for_effects()
4871 .iter()
4872 .any(|q| {
4873 q.chosen_action().is_some_and(|action| action.maintenance())
4874 && !home
4875 .join("choice-actions")
4876 .join(format!("{}.json", q.id))
4877 .exists()
4878 })
4879 }
4880 "housekeeping" => housekeeping_eligible(busy, !runnable(queue).is_empty()),
4881 "fold" => fold_turn_eligible(busy, !runnable(queue).is_empty(), cfg),
4882 "cache" => {
4883 !busy
4884 && !runnable(queue).is_empty()
4885 && cfg.is_some_and(|cfg| cfg.disk.cache_limit_bytes > 0)
4886 }
4887 "disk-pressure" => busy,
4888 "fetch" => {
4889 cfg.is_some_and(|cfg| cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty())
4890 }
4891 "decisions" => home.join("notifications/task-inquiries").is_dir(),
4892 "chat-goals" => crate::talk::Talks::at(home.join("talks"))
4893 .list()
4894 .iter()
4895 .any(|talk| {
4896 talk.status.open()
4897 && talk.pending.is_empty()
4898 && talk.pending_attachments.is_empty()
4899 && talk.goals.iter().any(|goal| goal.active())
4900 }),
4901 _ => false,
4902 };
4903 if !eligible {
4904 retention_service_receipt(
4905 home,
4906 operation,
4907 "dispatch",
4908 "skipped",
4909 match operation {
4910 "housekeeping" => "active work or runnable task queue",
4911 "fold" if cfg.is_none() => "startup configuration unavailable",
4912 "fold" if cfg.is_some_and(|cfg| !cfg.disk.auto_fold) => "auto_fold disabled",
4913 "fold" => "idle machine; housekeeping owns finished-run folding",
4914 _ => "no active work; idle housekeeping owns scan",
4915 },
4916 cfg,
4917 );
4918 return Ok(());
4919 }
4920 retention_service_receipt(
4921 home,
4922 operation,
4923 "dispatch",
4924 "launching",
4925 "eligible and cadence due",
4926 cfg,
4927 );
4928 let request = ServiceWorker {
4929 opts: opts.absolute()?,
4930 queue: std::path::absolute(queue.root())?,
4931 worktrees_root: std::path::absolute(worktrees_root)?,
4932 operation: operation.to_owned(),
4933 };
4934 if let Err(error) = launch_service(home, &key, request).await {
4935 retention_service_receipt(
4936 home,
4937 operation,
4938 "dispatch",
4939 "error",
4940 &format!("worker launch: {error:#}"),
4941 cfg,
4942 );
4943 tracing::warn!(operation, "could not launch daemon service: {error:#}");
4944 }
4945 std::fs::write(receipt, serde_json::to_vec(&now)?)?;
4946 Ok(())
4947}
4948
4949async fn launch_service(home: &Path, key: &str, request: ServiceWorker) -> Result<()> {
4955 #[cfg(test)]
4956 if INLINE_SERVICES.with(std::cell::Cell::get) {
4957 return run_service_worker(home, serde_json::to_value(request)?).await;
4958 }
4959 crate::worker::spawn(home, "daemon-service", key, serde_json::to_value(request)?).await?;
4960 Ok(())
4961}
4962
4963#[cfg(test)]
4964thread_local! {
4965 static INLINE_SERVICES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
4966}
4967
4968async fn fold_service_turn(home: &Path, opts: &Opts) {
4972 let worker = |outcome: &str, detail: &str, cfg: Option<&Config>, extra| {
4973 retention_service_receipt_with(home, "fold", "worker", outcome, detail, cfg, extra);
4974 };
4975 let cfg = match prepare(&opts.repo, opts) {
4976 Ok(cfg) => cfg,
4977 Err(error) => {
4978 worker(
4979 "error",
4980 &format!("configuration: {error:#}"),
4981 None,
4982 serde_json::Value::Null,
4983 );
4984 return;
4985 }
4986 };
4987 if !cfg.disk.auto_fold {
4988 worker(
4989 "skipped",
4990 "auto_fold disabled",
4991 Some(&cfg),
4992 serde_json::Value::Null,
4993 );
4994 return;
4995 }
4996 worker(
4997 "running",
4998 "finished-run fold turn",
4999 Some(&cfg),
5000 serde_json::Value::Null,
5001 );
5002 let turn = clean::fold_turn(
5003 &home.join("runs"),
5004 home,
5005 &cfg.disk,
5006 Timestamp::now(),
5007 clean::BUSY_FOLD_BOUNDS,
5008 )
5009 .await;
5010 if turn.folded > 0 || turn.failed > 0 || turn.unreadable > 0 {
5011 tracing::info!(
5012 folded = turn.folded,
5013 failed = turn.failed,
5014 unreadable = turn.unreadable,
5015 "housekeep: finished-run fold turn"
5016 );
5017 }
5018 worker(
5019 "completed",
5020 "finished-run fold turn",
5021 Some(&cfg),
5022 serde_json::json!({ "fold": turn }),
5023 );
5024}
5025
5026pub async fn run_service_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
5029 let request: ServiceWorker = serde_json::from_value(payload)?;
5030 let opts = &request.opts;
5031 let queue = Queue::at(request.queue);
5032 let questions = Questions::at(home.join("questions"));
5033 match request.operation.as_str() {
5034 "decisions" => crate::chat_control::retire_obsolete_decisions(&queue, home).await?,
5035 "chat-goals" => {
5036 let talks = crate::talk::Talks::at(home.join("talks"));
5037 crate::chat_goal_runtime::sweep(&talks, false).await;
5038 }
5039 "maintenance" => {
5040 apply_maintenance_choices(&queue, &questions, home).await;
5041 triage::monitor_disk_waits(
5042 &queue,
5043 &questions,
5044 opts.config.as_deref(),
5045 Timestamp::now(),
5046 );
5047 }
5048 "conductor" => {
5049 let path = home.join("conductor-state.json");
5050 let mut conductor = load_conductor(home)?;
5051 let (queued, stalled, finished) = conductor_work(&queue, home);
5052 if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
5053 && conductor.worth_a_look(&queue, &stalled, &finished)
5054 {
5055 let cfg = prepare(&opts.repo, opts)?;
5056 conductor
5057 .maybe_run(
5058 &cfg,
5059 &opts.repo,
5060 &queue,
5061 &questions,
5062 home,
5063 &queued,
5064 &stalled,
5065 &finished,
5066 opts.max_attempts,
5067 )
5068 .await;
5069 let temporary = path.with_extension("json.tmp");
5070 std::fs::write(&temporary, serde_json::to_vec(&conductor)?)?;
5071 std::fs::rename(temporary, path)?;
5072 }
5073 }
5074 "fetch" => {
5075 let cfg = prepare(&opts.repo, opts)?;
5076 if cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty() {
5077 let outcome = clean::fetch_origins(&cfg.repos.roots, FETCH_TIMEOUT, || false).await;
5078 tracing::debug!("fetch origins: {outcome:?}");
5079 }
5080 }
5081 "cache" => {
5082 if task_jobs(home)?.is_empty() {
5083 let mut checked = None;
5084 maybe_prune_cache_between_runs(
5085 &opts.repo,
5086 opts,
5087 home,
5088 &Stop::new(),
5089 &mut checked,
5090 Timestamp::now(),
5091 )
5092 .await;
5093 }
5094 }
5095 "disk-pressure" => {
5096 if let Ok(cfg) = prepare(&opts.repo, opts) {
5097 retention_service_receipt(
5098 home,
5099 "disk-pressure",
5100 "worker",
5101 "running",
5102 "retention sweep",
5103 Some(&cfg),
5104 );
5105 let report = crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
5106 retention_service_receipt_with(
5107 home,
5108 "disk-pressure",
5109 "worker",
5110 "retention swept",
5111 "retention sweep finished; cache cleanup follows",
5112 Some(&cfg),
5113 retention_summary(&report),
5114 );
5115 if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
5116 tracing::warn!("disk pressure cache cleanup failed: {e:#}");
5117 }
5118 if let Err(e) = crate::build_target::prune_registered(home, &cfg.disk) {
5119 tracing::warn!("disk pressure isolated build cleanup failed: {e:#}");
5120 }
5121 for current in current_work(home, Timestamp::now()) {
5122 if let Ok(state) = RunState::load_under(¤t.run, home)
5123 && let Some(reason) = disk_gate(&state.repo, &state.config)
5124 {
5125 for job in owned_task_jobs(home)?.into_iter().filter(|job| {
5126 job.key.strip_prefix("task:") == Some(current.task.as_str())
5127 }) {
5128 request_task_park(
5129 home,
5130 &job,
5131 crate::run::ParkCause::Interrupt {
5132 reason: reason.clone(),
5133 },
5134 )?;
5135 }
5136 notices::raise_in(
5137 home,
5138 Notice::warn(
5139 "disk:pressure",
5140 "Disk pressure persists after cleanup; active workers were asked to checkpoint and park. New starts and resumes wait for free space.",
5141 ),
5142 );
5143 }
5144 }
5145 } else {
5146 retention_service_receipt(
5147 home,
5148 "disk-pressure",
5149 "worker",
5150 "error",
5151 "configuration could not be loaded",
5152 None,
5153 );
5154 }
5155 }
5156 "fold" => fold_service_turn(home, opts).await,
5157 "housekeeping" => {
5158 if task_jobs(home)?.is_empty() {
5159 match prepare(&opts.repo, opts) {
5160 Ok(cfg) => {
5161 retention_service_receipt(
5162 home,
5163 "housekeeping",
5164 "worker",
5165 "running",
5166 "retention sweep",
5167 Some(&cfg),
5168 );
5169 let report =
5170 crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
5171 retention_service_receipt_with(
5172 home,
5173 "housekeeping",
5174 "worker",
5175 "retention swept",
5176 "retention sweep finished; janitor follows",
5177 Some(&cfg),
5178 retention_summary(&report),
5179 );
5180 }
5181 Err(error) => retention_service_receipt(
5182 home,
5183 "housekeeping",
5184 "worker",
5185 "error",
5186 &format!("configuration: {error:#}"),
5187 None,
5188 ),
5189 }
5190 janitor(&opts.repo, opts, home, &request.worktrees_root).await;
5191 resweep_superseded_attempts(&queue, home);
5192 triage_held(&queue, home, opts).await;
5193 } else {
5194 retention_service_receipt(
5195 home,
5196 "housekeeping",
5197 "worker",
5198 "skipped",
5199 "task worker became active",
5200 None,
5201 );
5202 }
5203 }
5204 operation => bail!("unknown daemon service {operation}"),
5205 }
5206 Ok(())
5207}
5208
5209fn task_worker_spawn_error(home: &Path, request: &TaskWorker, error: anyhow::Error) -> Result<()> {
5213 let key = format!("task:{}", request.task);
5214 let payload = serde_json::to_value(request)?;
5215 if crate::worker::active(home)?
5216 .iter()
5217 .any(|job| job.key == key && job.kind == "task" && job.payload != payload)
5218 {
5219 tracing::warn!(
5220 "task {} acquired a competing worker reservation: {error:#}",
5221 crate::run::short_of(&request.task)
5222 );
5223 return Ok(());
5224 }
5225 tracing::error!("task worker startup stopped dispatch: {error:#}");
5226 notices::raise_in(
5227 home,
5228 Notice::error(
5229 "loop:worker-startup",
5230 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),
5233 ).link(Link::Task { id: request.task.clone() }),
5234 );
5235 Err(error).with_context(|| {
5236 format!(
5237 "cannot start task {} worker; dispatcher stopped; any unacknowledged reservation remains occupied",
5238 crate::run::short_of(&request.task)
5239 )
5240 })
5241}
5242
5243async fn poll(
5244 opts: &Opts,
5245 queue: &Queue,
5246 status: &Arc<Mutex<Status>>,
5247 home: &Path,
5248 worktrees_root: &Path,
5249 stop: &Stop,
5250 limits: DispatchLimits,
5251) -> Result<()> {
5252 let mut attempted = Vec::new();
5253 let mut settling_once_services = false;
5254 let interrupt_path = home.join("scheduler-interrupt.json");
5255 let mut interrupt = match std::fs::read(&interrupt_path) {
5256 Ok(body) => serde_json::from_slice(&body).context("read scheduler interrupt state")?,
5257 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Interrupt::Idle,
5258 Err(error) => return Err(error.into()),
5259 };
5260 let mut previous = std::collections::BTreeSet::<String>::new();
5261 let mut previous_skips = DispatchSkips::new();
5262 while !stop.stopped() {
5263 let jobs: Vec<_> = crate::worker::active(home)?
5264 .into_iter()
5265 .filter(|job| job.kind == "task")
5266 .collect();
5267 let requests: Vec<_> = jobs
5268 .iter()
5269 .map(|job| {
5270 serde_json::from_value::<TaskWorker>(job.payload.clone())
5271 .with_context(|| format!("read live task worker {}", job.id))
5272 })
5273 .collect::<Result<_>>()?;
5274 let live: std::collections::BTreeSet<_> = requests.iter().map(|r| r.task.clone()).collect();
5275 let owned: std::collections::BTreeSet<_> = requests
5276 .iter()
5277 .filter(|r| !r.standalone)
5278 .map(|r| r.task.clone())
5279 .collect();
5280 let current: Vec<_> = requests
5281 .iter()
5282 .zip(&jobs)
5283 .filter(|(request, _)| !request.standalone)
5284 .map(|(request, job)| Current {
5285 worker: Some(job.id.clone()),
5286 task: request.task.clone(),
5287 run: queue
5288 .get(&request.task)
5289 .ok()
5290 .and_then(|task| task.execution_runs().last().cloned())
5291 .unwrap_or_default(),
5292 })
5293 .collect();
5294 {
5295 let mut snapshot = lock(status);
5296 snapshot.polls += 1;
5297 snapshot.completed += previous.difference(&owned).count();
5298 snapshot.current = current;
5299 snapshot.idle = owned.is_empty();
5300 snapshot.dispatch_wait = None;
5301 }
5302 previous = owned.clone();
5303 stop.busy.store(owned.len(), Ordering::SeqCst);
5304
5305 let (ordinary, urgent) = available_slots(&requests, limits.max_concurrent);
5308 let sem = Arc::new(tokio::sync::Semaphore::new(ordinary));
5309 let urgent_sem = Arc::new(tokio::sync::Semaphore::new(urgent));
5310 let mut permits = Vec::new();
5311 sweep_stale_claims(queue, STALE_CLAIM);
5312 reclaim_orphaned_running(queue, opts.max_attempts, &live);
5313 reclaim_abandoned_runs(home, Timestamp::now());
5314 let questions = Questions::at(home.join("questions"));
5315
5316 crate::task_chat::sweep(
5319 queue,
5320 &crate::talk::Talks::at(home.join("talks")),
5321 &questions,
5322 home,
5323 );
5324 if let Err(error) = crate::task_inquiry::Outbox::at(home)
5325 .sweep(queue, &crate::talk::Talks::at(home.join("talks")))
5326 {
5327 tracing::warn!("task inquiry delivery remains pending: {error:#}");
5328 }
5329 repair_choice_offers(&questions);
5330 resolve_blockers(queue, &questions);
5331 apply_task_choice_actions(queue, &questions, home);
5332 triage::apply_answers(queue, &questions);
5333 reconcile_task_questions(queue, &questions);
5334 let talks = crate::talk::Talks::at(home.join("talks"));
5335 crate::chat_notify::sweep(queue, &talks, home);
5336 crate::notice_delivery::sweep(queue, &talks, home, &opts.repo);
5337 crate::chat_watch::sweep(home, &talks);
5338 if let Err(error) = crate::chat_control::reconcile_decisions(queue, home) {
5339 tracing::warn!("decision receipt reconciliation remains pending: {error:#}");
5340 }
5341 let mut turns = tokio::task::JoinSet::new();
5342 crate::chat_notify::start_turns(&talks, stop.parking(), &mut turns);
5343 while turns.join_next().await.is_some() {}
5345
5346 crate::consult::start_services(
5347 home,
5348 &opts.repo,
5349 limits.recovery_cfg.as_ref(),
5350 opts.config.as_deref(),
5351 )
5352 .await?;
5353 for operation in [
5354 "conductor",
5355 "maintenance",
5356 "housekeeping",
5357 "disk-pressure",
5358 "fold",
5359 "cache",
5360 "fetch",
5361 "chat-goals",
5362 "decisions",
5363 ] {
5364 if settling_once_services {
5368 break;
5369 }
5370 if operation == "chat-goals" && stop.parking() {
5371 continue;
5372 }
5373 start_service(
5374 home,
5375 opts,
5376 queue,
5377 worktrees_root,
5378 operation,
5379 limits.recovery_cfg.as_ref(),
5380 !live.is_empty(),
5381 )
5382 .await?;
5383 }
5384 let latest = crate::worker::active(home)?;
5385 if latest.iter().any(|job| job.key == "service:daemon-cache")
5386 || latest
5387 .iter()
5388 .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
5389 {
5390 stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
5391 continue;
5392 }
5393 let candidates: Vec<Task> = runnable(queue)
5394 .into_iter()
5395 .filter(|task| !live.contains(&task.id))
5396 .filter(|task| !opts.once || !attempted.contains(&task.id))
5397 .collect();
5398 let in_flight: Vec<_> = owned.iter().cloned().collect();
5399 let prior_interrupt = std::mem::discriminant(&interrupt);
5400 interrupt = advance_interrupt_tick(
5401 limits.pause_for_interrupts,
5402 interrupt,
5403 &in_flight,
5404 &candidates,
5405 );
5406 if prior_interrupt != std::mem::discriminant(&interrupt) {
5409 let temporary = interrupt_path.with_extension("json.tmp");
5410 std::fs::write(&temporary, serde_json::to_vec(&interrupt)?)?;
5411 std::fs::rename(temporary, &interrupt_path)?;
5412 }
5413 if let Interrupt::Parking {
5414 parked,
5415 interrupt_task,
5416 } = &interrupt
5417 {
5418 for job in jobs.iter().filter(|job| {
5419 parked
5420 .iter()
5421 .any(|id| job.key.strip_prefix("task:") == Some(id.as_str()))
5422 }) {
5423 if crate::worker::control(home, &job.key)?.is_none() {
5424 request_task_park(
5425 home,
5426 job,
5427 crate::run::ParkCause::Interrupt {
5428 reason: format!(
5429 "task {} asked to run first",
5430 crate::run::short_of(interrupt_task)
5431 ),
5432 },
5433 )?;
5434 }
5435 }
5436 }
5437 let candidate_ids: Vec<_> = candidates.iter().map(|task| task.id.clone()).collect();
5438 let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
5439 let mut skips = interrupt_skips(&candidate_ids, &candidates);
5440 let (mut immediate_candidates, other_candidates): (Vec<Task>, Vec<Task>) =
5444 candidates.into_iter().partition(|task| task.immediate);
5445 immediate_candidates.extend(other_candidates);
5446 let candidates = immediate_candidates;
5447 let cooling = read_cooldown(home)?.is_some_and(|until| Timestamp::now() < until);
5448 let mut known_jobs: std::collections::BTreeSet<String> =
5449 jobs.iter().map(|job| job.id.clone()).collect();
5450 let mut started = false;
5451 let mut resync = false;
5452 for candidate in candidates {
5453 if stop.stopped() {
5454 break;
5455 }
5456 let DispatchClaim {
5457 task,
5458 claim,
5459 lane,
5460 permit,
5461 } = match claim_dispatch(queue, &candidate, cooling, &sem, &urgent_sem) {
5462 Ok(claim) => claim,
5463 Err(reason) => {
5464 skips.insert((candidate.id, reason));
5465 continue;
5466 }
5467 };
5468 if crate::worker::active(home)?
5469 .iter()
5470 .any(|job| job.kind == "task" && !known_jobs.contains(&job.id))
5471 {
5472 drop(claim);
5473 resync = true;
5474 break;
5475 }
5476 let request = TaskWorker {
5477 opts: opts.absolute()?,
5478 queue: std::path::absolute(queue.root())?,
5479 task: task.id.clone(),
5480 lane,
5481 standalone: false,
5482 };
5483 let job = match crate::worker::spawn(
5486 home,
5487 "task",
5488 &format!("task:{}", task.id),
5489 serde_json::to_value(&request)?,
5490 )
5491 .await
5492 {
5493 Ok(job) => job,
5494 Err(error) => {
5495 task_worker_spawn_error(home, &request, error)?;
5496 drop(claim);
5497 resync = true;
5498 break;
5499 }
5500 };
5501 known_jobs.insert(job.id);
5502 drop(claim);
5503 permits.extend(permit);
5504 attempted.push(task.id);
5505 started = true;
5506 if limits.pause_for_interrupts || lane != PermitKind::Immediate {
5510 break;
5511 }
5512 }
5513 if !resync && !stop.stopped() {
5514 let per_task_skips: std::collections::BTreeMap<String, String> = skips
5515 .iter()
5516 .map(|(id, reason)| (id.clone(), reason.key().to_owned()))
5517 .collect();
5518 {
5519 let mut snapshot = lock(status);
5520 snapshot.dispatch_skips = per_task_skips;
5521 if !started {
5522 snapshot.dispatch_wait = aggregate_dispatch_wait(candidate_ids.len(), &skips);
5523 }
5524 }
5525 if changed_dispatch_skips(&mut previous_skips, skips) {
5526 if previous_skips.is_empty() {
5527 tracing::info!("dispatch skips cleared");
5528 }
5529 for (task, reason) in &previous_skips {
5530 tracing::info!(
5531 task,
5532 reason = reason.key(),
5533 "task {} skipped: {}",
5534 crate::run::short_of(task),
5535 reason.describe()
5536 );
5537 }
5538 }
5539 }
5540 if started || resync {
5541 continue;
5542 }
5543 if owned.is_empty() && opts.once {
5544 settling_once_services = true;
5545 if crate::worker::active(home)?.iter().any(|job| {
5549 job.kind == "daemon-service"
5550 && matches!(
5551 job.key.as_str(),
5552 "service:daemon-housekeeping"
5553 | "service:daemon-conductor"
5554 | "service:daemon-maintenance"
5555 )
5556 }) {
5557 stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
5558 continue;
5559 }
5560 break;
5561 }
5562 stop.idle(if live.is_empty() {
5563 opts.poll
5564 } else {
5565 RECHECK_WHILE_BUSY.min(opts.poll)
5566 })
5567 .await;
5568 }
5569 stop.busy.store(0, Ordering::SeqCst);
5572 {
5573 let mut snapshot = lock(status);
5574 snapshot.dispatch_wait = None;
5575 snapshot.dispatch_skips.clear();
5576 }
5577 Ok(())
5578}
5579
5580async fn resume_owner_lock(home: &Path, id: &str) -> Result<crate::pr_head::OwnerLock> {
5584 let busy = |error: &anyhow::Error| {
5585 error.downcast_ref::<std::io::Error>().is_some_and(|error| {
5586 error.kind() == std::io::ErrorKind::WouldBlock
5587 || cfg!(windows) && error.raw_os_error() == Some(33)
5588 })
5589 };
5590 match crate::pr_head::owner_lock(home, id) {
5591 Ok(lock) => return Ok(lock),
5592 Err(error) if busy(&error) => {}
5593 Err(error) => return Err(error),
5594 }
5595 let wait = RunState::load_under(id, home)?
5596 .config
5597 .graph
5598 .timeout_resource_wait;
5599 crate::pr_head::owner_lock_wait(home, id, Duration::from_secs(wait)).await
5600}
5601
5602pub(crate) async fn public_resume_owner(
5606 home: &Path,
5607 runs: &[String],
5608 repo: &Path,
5609) -> Result<Option<RunState>> {
5610 let mut owner = None;
5611 for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
5612 let _lock = resume_owner_lock(home, id).await?;
5613 let state = RunState::load_under(id, home)?;
5614 if state.released()
5615 || state.retired_to.is_some()
5616 || state.pr_taken_over_by.is_some()
5617 || !crate::handover::landing_checkpoint(&state)
5618 {
5619 continue;
5620 }
5621 anyhow::ensure!(
5622 crate::git::toplevel(&state.repo).await?.canonicalize()?
5623 == crate::git::toplevel(repo).await?.canonicalize()?,
5624 "public owner repository differs; inspect run lineage"
5625 );
5626 anyhow::ensure!(
5627 owner.is_none(),
5628 "multiple retained public owners; inspect run lineage"
5629 );
5630 if let Some(reason) = crate::handover::resume_refusal_under(&state, Some(home)) {
5631 anyhow::bail!(reason.diagnostic(&state));
5632 }
5633 let claimed = is_working_on_other(home, id, Timestamp::now())?;
5634 anyhow::ensure!(
5635 state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
5636 "public owner's driver is live or unknown; wait before retrying"
5637 );
5638 owner = Some(state);
5639 }
5640 Ok(owner)
5641}
5642
5643async fn attempt(
5649 opts: &Opts,
5650 queue: &Queue,
5651 status: &Arc<Mutex<Status>>,
5652 stop: &Stop,
5653 interrupt_pause: crate::graph::Pause,
5654 task: &mut Task,
5655) -> Vec<QuotaLoss> {
5656 if let Some(request) = task.sync_only.clone() {
5657 Box::pin(attempt_sync_only(
5658 queue,
5659 status,
5660 stop,
5661 interrupt_pause,
5662 task,
5663 request,
5664 ))
5665 .await;
5666 return Vec::new();
5667 }
5668 let repo = repo_for(task, &opts.repo);
5669 tracing::info!(
5670 "task {} — {} (repo {})",
5671 task.short(),
5672 task.title,
5673 repo.display()
5674 );
5675
5676 let public_owner = match public_resume_owner(&crate::run::home(), &task.runs, &repo).await {
5677 Ok(owner) => owner,
5678 Err(e) => {
5679 task.hold_machine(Some(format!(
5680 "Cannot verify existing public owner: {e:#}; no attempt started."
5681 )));
5682 record(queue, task);
5683 return Vec::new();
5684 }
5685 };
5686 let resume_runs = public_owner
5687 .as_ref()
5688 .map(|s| vec![s.id.clone()])
5689 .unwrap_or_else(|| task.execution_runs().to_vec());
5690
5691 if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
5695 && previous
5696 .merge_decision
5697 .as_ref()
5698 .is_some_and(|decision| !decision.closed)
5699 && previous.status != RunStatus::Landing
5700 && !crate::merge_decision::resumable_hold(&previous)
5701 {
5702 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)));
5703 record(queue, task);
5704 return Vec::new();
5705 }
5706 let stop_owner = resume_runs
5707 .last()
5708 .and_then(|id| RunState::load(id).ok())
5709 .filter(|state| {
5710 crate::merge_decision::resumable_hold(state)
5711 || state.status == RunStatus::Landing
5712 && state.land_approval.as_ref().is_some_and(|binding| {
5713 Questions::open()
5714 .get_for_effects(&binding.question)
5715 .is_ok_and(|q| {
5716 q.run == state.id
5717 && q.resolution()
5718 .as_deref()
5719 .is_some_and(crate::merge_decision::stops)
5720 })
5721 })
5722 });
5723 if let Some(owner) = stop_owner {
5724 let mut runner = match Runner::resume(&owner.id) {
5725 Ok(runner) => runner,
5726 Err(e) => {
5727 task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
5728 record(queue, task);
5729 return Vec::new();
5730 }
5731 };
5732 runner.on_pause(stop.pause());
5733 runner.watch_interrupt(interrupt_pause);
5734 let quota_before = runner.state.quota.clone();
5735 let before_start = task.clone();
5736 task.start(owner.id.clone());
5737 if let Err(error) = queue.put(task) {
5738 *task = before_start;
5739 let error = runner.fail_startup("task-start", error);
5740 if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5741 task.record_startup_failure(failure.clone());
5742 }
5743 task.hold_manual(Some(format!(
5744 "Could not persist task start; no agents dispatched: {error:#}"
5745 )));
5746 record(queue, task);
5747 return Vec::new();
5748 }
5749 lock(status).current.push(Current {
5750 worker: None,
5751 task: task.id.clone(),
5752 run: owner.id,
5753 });
5754 runner.state.carry_dispatched_resumes(task);
5755 runner.state.next_pass_task_entry = true;
5756 let result = runner.execute().await;
5757 return finish_attempt(
5758 opts.max_attempts,
5759 queue,
5760 task,
5761 &runner.state,
5762 "a_before,
5763 result,
5764 );
5765 }
5766
5767 if let Some(owner) = &public_owner
5768 && (task.fresh_start || !may_resume_run(owner, task))
5769 {
5770 task.hold_machine(Some(format!("Existing PR belongs to run {}; resume its authorized instructions or explicitly resolve its owner decision before starting a successor. For a closed unmerged PR with a cancelled approval and selected replacement, use magi task recover-pr {} --retire-closed-run {} --cancelled-decision <inquiry-id>. No attempt started.", owner.id, task.id, owner.id)));
5771 record(queue, task);
5772 return Vec::new();
5773 }
5774
5775 if let Some(state) = task
5776 .execution_runs()
5777 .last()
5778 .and_then(|id| RunState::load(id).ok())
5779 && let Some(reason) = crate::repair_budget::conflict_failure(task, &state)
5780 {
5781 task.hold_machine(Some(reason));
5782 record(queue, task);
5783 return Vec::new();
5784 }
5785
5786 if let Some(held) = crate::base_sync_recovery::held_run(queue, task)
5787 && !task.fresh_start
5788 && task.pr_recovery.is_none()
5789 {
5790 let sequencer_resume = crate::repair_budget::legacy::resumable_sequencer_stop(&held)
5793 && task.review_branch.is_none()
5794 && task.assignment_accepts(&held)
5795 && compatible_run_instruction(&held, task)
5796 && task
5797 .resume_override
5798 .as_ref()
5799 .is_some_and(|pin| pin.pinned_run.as_ref() == Some(&held.id));
5800 let authorized = if sequencer_resume || crate::repair_budget::conflict_pending(task, &held)
5803 {
5804 true
5805 } else if task.resumption.is_some() && compatible_run_instruction(&held, task) {
5806 let home = queue.root().parent().expect("queue has a home");
5807 match Runner::authorize_base_recovery_from_resumption(home, &held.id, &task.id).await {
5808 Ok(()) => true,
5809 Err(error) => {
5810 tracing::debug!(run = %held.id, %error, "base recovery resumption refused");
5811 false
5812 }
5813 }
5814 } else {
5815 false
5816 };
5817 if !authorized {
5818 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())));
5819 task.base_sync_notice(&held);
5821 task.resume_override = None;
5822 record(queue, task);
5823 return Vec::new();
5824 }
5825 }
5826 if !task.fresh_start && task.pr_recovery.is_none() {
5827 let home = queue.root().parent().expect("queue has a home");
5828 if let crate::land_sync_recovery::DispatchDecision::Hold { reason, state } =
5829 crate::land_sync_recovery::dispatch_check(queue, home, task).await
5830 {
5831 task.hold_machine(Some(reason));
5832 task.land_sync_notice(state.as_ref());
5833 task.resume_override = None;
5834 record(queue, task);
5835 return Vec::new();
5836 }
5837 }
5838 let head_e2e_approval = match crate::head_e2e_stop::check_attempt(queue, task) {
5839 Some(crate::head_e2e_stop::AttemptGate::Hold(hold)) => {
5840 hold.apply(task);
5841 record(queue, task);
5842 return Vec::new();
5843 }
5844 Some(crate::head_e2e_stop::AttemptGate::ConsumeOwnerApproval {
5845 run,
5846 stop_id,
5847 generation,
5848 approval_at,
5849 }) => Some((run, stop_id, generation, approval_at)),
5850 None => None,
5851 };
5852 let unfinished = (!task.fresh_start)
5853 .then(|| unfinished_run(&resume_runs, task.short()))
5854 .flatten()
5855 .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
5856 let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
5857 if task.repair_grants.last().is_some_and(|receipt| {
5858 task.execution_runs().last() == Some(&receipt.request.run)
5859 && task.operator_decided_at == receipt.decision
5860 && previous
5861 .as_ref()
5862 .is_none_or(|run| run.id != receipt.request.run)
5863 }) {
5864 task.hold_unrequested_retry(Some(
5865 "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(),
5866 ));
5867 record(queue, task);
5868 return Vec::new();
5869 }
5870 if let Some(id) = &task.disk_resume_run
5871 && unfinished.as_ref() != Some(id)
5872 {
5873 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()));
5874 record(queue, task);
5875 return Vec::new();
5876 }
5877
5878 if !task.fresh_start
5879 && task.pr_recovery.is_none()
5880 && task.review_branch.is_none()
5881 && task.resume_override.is_none()
5882 && previous
5883 .as_ref()
5884 .is_some_and(|run| run.retired_to.is_some())
5885 && unfinished.is_none()
5886 {
5887 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()));
5888 record(queue, task);
5889 return Vec::new();
5890 }
5891
5892 let saved_recovery = previous.as_ref().filter(|run| {
5893 task.replacement.is_none()
5894 && task.pr_recovery.as_ref().is_some_and(|selected| {
5895 selected
5896 .check_retained_task(task, &crate::run::home())
5897 .is_ok()
5898 && selected_starter(selected, Some(run), unfinished.as_deref())
5899 == Starter::Resume(run.id.clone())
5900 })
5901 });
5902
5903 let explicit = match &task.overrides {
5907 Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
5908 Some(_) => opts.config.as_deref(),
5909 None => opts.config.as_deref(),
5910 };
5911 let (mut config, layers) = if let Some(run) = saved_recovery {
5912 let mut saved = run.clone();
5915 if let Err(e) = saved.configure_recovery_resume() {
5916 task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
5917 record(queue, task);
5918 return Vec::new();
5919 }
5920 (saved.config, Vec::new())
5921 } else {
5922 let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
5923 Ok(loaded) => loaded,
5924 Err(e) => {
5925 let reason = format!("[config] {e:#}");
5926 record_config_failure(task, &e);
5927 task.last_error = Some(reason.clone());
5928 task.hold_machine(Some(reason));
5929 record(queue, task);
5930 return Vec::new();
5931 }
5932 };
5933 if let Err(e) = apply_options(&mut config, opts, task) {
5934 task.hold_manual(Some(format!(
5935 "[config] {e:#}; correct the merge override before releasing the task"
5936 )));
5937 record(queue, task);
5938 return Vec::new();
5939 }
5940 if let Some(selected) = &task.pr_recovery
5941 && let Err(e) = selected.configure(&mut config)
5942 {
5943 task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
5944 record(queue, task);
5945 return Vec::new();
5946 }
5947 (config, layers)
5948 };
5949 let config_evidence = crate::pr_recovery::ConfigEvidence {
5950 layers,
5951 overrides: task.overrides.clone(),
5952 daemon_merge: task
5953 .overrides
5954 .as_ref()
5955 .is_none_or(|o| o.inherit_daemon_options)
5956 .then(|| opts.merge.clone())
5957 .flatten(),
5958 };
5959 apply_task_implementers(&mut config, task);
5960 if let Some(replacement) = &task.replacement {
5961 let safe = RunState::load(&replacement.run).is_ok_and(|old| {
5962 old.liveness(false) == Liveness::Dead
5963 && old.merge_decision.as_ref().is_some_and(|d| {
5964 d.closed
5965 && d.question == replacement.question
5966 && d.replacement_run.as_ref().is_none_or(|run| {
5967 task.execution_runs().last() == Some(run)
5968 && RunState::load(run).is_ok_and(|current| {
5969 current.replaces.as_ref().is_some_and(|pin| {
5970 pin.question == replacement.question
5971 && pin.agent == replacement.agent
5972 })
5973 })
5974 })
5975 })
5976 });
5977 if !safe {
5978 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()));
5979 record(queue, task);
5980 return Vec::new();
5981 }
5982 match config.agent(&replacement.agent) {
5983 Ok(agent) if crate::agent::installed(agent) => {}
5984 _ => {
5985 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)));
5986 record(queue, task);
5987 return Vec::new();
5988 }
5989 }
5990 config.graph.implementers = 1;
5991 config.graph.land_approval = true;
5992 config.merge.mode = MergeMode::Pr;
5993 config.graph.selected_implementer = Some(replacement.agent.clone());
5994 }
5995 let p = phrases(&config.graph.language);
5996 let start_failed = p.could_not_start;
5997 if let Ok(base) =
6002 crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
6003 .await
6004 && let Ok(head) =
6005 crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
6006 {
6007 let mut inputs = crate::queue::recovery_inputs(&task.sources);
6008 if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
6009 let source = crate::git::rev_parse(&repo, branch)
6010 .await
6011 .unwrap_or_default();
6012 inputs.push_str(&format!(";review:{branch}:{source}"));
6013 }
6014 if let Some(reason) = task
6015 .recovery_exhausted(
6016 &head,
6017 &inputs,
6018 task.attempt_limit
6019 .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
6020 )
6021 .filter(|_| {
6022 !task.repair_grants.last().is_some_and(|receipt| {
6023 RunState::load(&receipt.request.run)
6024 .is_ok_and(|run| crate::repair_budget::pending(task, &run))
6025 })
6026 })
6027 {
6028 task.hold_recovery_budget(
6029 reason,
6030 crate::queue::RecoveryAdmission { base: head, inputs },
6031 );
6032 record(queue, task);
6033 return Vec::new();
6034 }
6035 task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
6036 }
6037
6038 let consume_review = !previous
6059 .as_ref()
6060 .is_some_and(|state| crate::repair_budget::pending(task, state));
6061 let review_branch = consume_review
6062 .then(|| review_branch_for(task, previous.as_ref()))
6063 .flatten();
6064 let branch_exists = match review_branch {
6065 Some(branch) => crate::git::branch_exists(&repo, branch)
6066 .await
6067 .unwrap_or(false),
6068 None => false,
6069 };
6070 let proposed = review_retry_starter(
6074 task,
6075 previous.as_ref(),
6076 review_branch,
6077 branch_exists,
6078 unfinished.as_deref(),
6079 );
6080 let retry_selected = task.replacement.is_some()
6081 && task.resumption.is_some()
6082 && !task.fresh_start
6083 && previous.as_ref().is_some_and(|run| {
6084 run.replaces.is_some()
6085 && ((run.status == RunStatus::Failed && run.viable().is_empty())
6086 || (run.status == RunStatus::Blocked && run.tally.is_none()))
6087 });
6088 let stop_pin = task
6089 .resume_override
6090 .as_ref()
6091 .filter(|pin| {
6092 Questions::open()
6093 .get_for_effects(&pin.question_id)
6094 .is_ok_and(|q| {
6095 q.node == land::APPROVAL_NODE
6096 && q.resolution()
6097 .as_deref()
6098 .is_some_and(crate::merge_decision::stops)
6099 })
6100 })
6101 .and_then(|pin| pin.pinned_run.clone());
6102 let granted_run = task.repair_grants.last().and_then(|receipt| {
6103 let state = RunState::load(&receipt.request.run).ok()?;
6104 crate::repair_budget::pending(task, &state).then(|| receipt.request.run.clone())
6105 });
6106 let starter = if let Some(run) = granted_run {
6107 Starter::Resume(run)
6108 } else if let Some(owner) = &public_owner {
6109 Starter::Resume(owner.id.clone())
6110 } else if let Some(run) = stop_pin {
6111 Starter::Resume(run)
6114 } else if retry_selected {
6115 Starter::Resume(previous.as_ref().unwrap().id.clone())
6116 } else if let Some(selected) = &task.pr_recovery {
6117 if selected
6118 .check_retained_task(task, &crate::run::home())
6119 .is_ok()
6120 {
6121 selected_starter(selected, previous.as_ref(), unfinished.as_deref())
6122 } else {
6123 Starter::Review(selected.branch.clone())
6124 }
6125 } else {
6126 starter_with_implementers(task, previous.as_ref(), proposed)
6127 };
6128 let disk_reason = match &starter {
6131 Starter::Resume(id) => previous.as_ref().filter(|run| &run.id == id).map_or_else(
6132 || {
6133 RunState::load(id)
6134 .ok()
6135 .and_then(|run| disk_gate(&run.repo, &run.config))
6136 },
6137 |run| disk_gate(&run.repo, &run.config),
6138 ),
6139 _ => disk_gate(&repo, &config),
6140 };
6141 if let Some(reason) = disk_reason {
6142 task.notice_cause("disk-space", None, None);
6143 task.last_error = Some(reason.clone());
6144 let disk_checked_at = task.disk_checked_at;
6145 task.hold_machine(Some(reason.clone()));
6146 if matches!(starter, Starter::Resume(_)) {
6147 task.mark_disk_capacity();
6148 } else {
6149 task.mark_startup_disk_capacity();
6150 }
6151 task.disk_checked_at = disk_checked_at;
6152 record(queue, task);
6153 tracing::warn!("holding {} for want of disk space: {reason}", task.short());
6154 notices::raise(
6155 Notice::warn(
6156 &format!("disk:{}", repo.display()),
6157 format!("Task {} is waiting for disk space. It will resume automatically when disk and output admission checks succeed.", task.id),
6158 )
6159 .link(Link::Task {
6160 id: task.id.clone(),
6161 }),
6162 );
6163 return Vec::new();
6164 }
6165 let review_branch = if consume_review {
6166 let valid = review_branch.is_some();
6167 task.review_instruction = None;
6168 task.review_branch.take().filter(|_| valid)
6169 } else {
6170 None
6171 };
6172 if let Some(pin) = &task.resume_override
6175 && let Some(run) = &pin.pinned_run
6176 && starter != Starter::Resume(run.clone())
6177 {
6178 let run = run.clone();
6179 task.notice_cause("resume-owner", Some(&run), None);
6180 task.hold_machine(Some(format!(
6181 "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
6182 task.id
6183 )));
6184 record(queue, task);
6185 return Vec::new();
6186 }
6187 if let Some(run) = &task.disk_resume_run
6191 && starter != Starter::Resume(run.clone())
6192 {
6193 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()));
6194 record(queue, task);
6195 return Vec::new();
6196 }
6197 if task.replacement.is_some()
6198 && previous.as_ref().is_some_and(|run| run.replaces.is_some())
6199 && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
6200 {
6201 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()));
6202 record(queue, task);
6203 return Vec::new();
6204 }
6205 if let Some((ref run, ..)) = head_e2e_approval
6206 && starter != Starter::Resume(run.clone())
6207 {
6208 task.hold_machine(Some(format!(
6209 "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."
6210 )));
6211 record(queue, task);
6212 return Vec::new();
6213 }
6214 if let Some(reason) = retained_attempt_hold(
6215 task,
6216 &starter,
6217 config.disk.retained_attempt_limit,
6218 RunState::load,
6219 ) {
6220 if let Starter::Review(branch) = &starter {
6223 task.review_branch = Some(branch.clone());
6224 }
6225 task.hold_unrequested_retry(Some(reason));
6226 record(queue, task);
6227 return Vec::new();
6228 }
6229 let attachments = match task_attachments(queue, task) {
6234 Ok(a) => a,
6235 Err(e) => {
6236 task.attempts += 1;
6237 task.fail_startup_target(
6238 "startup-attachments",
6239 e.name.clone(),
6240 format!("{start_failed}{e:#}"),
6241 opts.max_attempts,
6242 );
6243 record(queue, task);
6244 return Vec::new();
6245 }
6246 };
6247 let startup_pause = stop.pause();
6248 let startup_interrupt = interrupt_pause.clone();
6249 let wait = crate::repo_lock::WaitPolicy::new(
6250 Duration::from_secs(config.graph.timeout_resource_wait),
6251 move || startup_pause.parked() || startup_interrupt.parked(),
6252 );
6253 let started = wait.scope(Box::pin(async { match &starter {
6256 Starter::Review(_) if task.pr_recovery.is_some() => {
6257 let selected = task.pr_recovery.clone().expect("selected recovery");
6258 match selected.check_retained_task(task, &crate::run::home()) {
6259 Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
6260 .await
6261 .map(|mut r| {
6262 r.state.attachments = attachments.clone();
6263 r
6264 }),
6265 Err(e) => Err(e),
6266 }
6267 }
6268 Starter::Review(branch) => {
6269 tracing::info!(
6270 "task {} reopens `{branch}` as a review-only pass",
6271 task.short()
6272 );
6273 let takeover = crate::handover::Takeover {
6276 earlier: task.earlier_attempts().to_vec(),
6277 home: crate::run::home(),
6278 choice: take_divergence_answer(branch, &config.merge.remote, task),
6279 task_instruction: Some(instruction_for(task)),
6280 };
6281 Runner::review_taking_over(
6282 &repo,
6283 branch,
6284 config,
6285 Some(takeover),
6286 crate::run::Origin::queue(&task.id),
6287 )
6288 .await
6289 }
6290 Starter::Resume(id) => {
6291 tracing::info!("resuming run {id} rather than competing again");
6292 Runner::resume(id).and_then(|mut r| {
6293 if retry_selected {
6294 for candidate in &mut r.state.candidates {
6297 candidate.failed = None;
6298 candidate.empty = false;
6299 candidate.commits = 0;
6300 }
6301 r.state.status = RunStatus::Implementing;
6302 r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
6303 }
6304 if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
6305 r.state.sources = task.sources.clone();
6306 }
6307 if r.state.prep_failure.is_some() {
6308 let approval = task
6309 .resumption
6310 .as_ref()
6311 .context("preparation retry requires an explicit task release")?;
6312 r.retry_preparation(approval.at)?;
6313 }
6314 if let Some(instruction) =
6315 prepare_instruction(&starter, Some(&r.state.instruction), task)
6316 {
6317 r.state.instruction = instruction;
6318 }
6319 r.state.attachments = attachments.clone();
6320 if task.replacement.is_some() {
6321 r.state.config.merge.mode = MergeMode::Pr;
6322 r.state.config.graph.land_approval = true;
6323 }
6324 if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
6328 .overrides
6329 .as_ref()
6330 .and_then(|o| o.merge.as_deref())
6331 .and_then(|m| merge_mode(m).ok())
6332 {
6333 r.state.config.merge.mode = mode;
6334 }
6335 Ok(r)
6336 })
6337 }
6338 Starter::Start => {
6339 if let Some(branch) = &review_branch {
6340 tracing::warn!(
6341 "conductor chose review for task {} but branch `{branch}` no longer \
6342 exists; requeuing as a fresh competition instead",
6343 task.short()
6344 );
6345 }
6346 let instruction = prepare_instruction(&starter, None, task)
6347 .unwrap_or_else(|| task.instruction.clone());
6348 Runner::start_naming(
6349 &repo,
6350 instruction,
6351 &task.title,
6352 config,
6353 crate::run::Origin::queue(&task.id),
6354 )
6355 .await
6356 .map(|mut r| {
6357 r.state.attachments = attachments.clone();
6358 r.state.sources = task.sources.clone();
6359 r
6360 })
6361 }
6362 }})).await;
6363 if let Err(error) = &started
6364 && let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>()
6365 {
6366 task.record_startup_failure(failure.clone());
6367 }
6368 let mut runner = match started {
6369 Ok(r) => r,
6370 Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
6371 let detail = format!("{e:#}");
6372 task.last_error = Some(detail.clone());
6373 if e.is::<crate::build_target::AdmissionDiskWait>()
6374 && let Starter::Review(branch) = &starter
6375 && review_branch.is_some()
6376 {
6377 task.review_branch = Some(branch.clone());
6378 task.review_instruction = Some(task.instruction.clone());
6379 }
6380 if stop.parking() || interrupt_pause.parked() {
6381 let attempts = task.attempts;
6382 task.park(e.to_string());
6383 task.attempts = attempts;
6385 } else if e.is::<crate::build_target::AdmissionDiskWait>() {
6386 let disk_checked_at = task.disk_checked_at;
6387 task.hold_machine(Some(detail));
6388 task.mark_startup_disk_capacity();
6389 task.disk_checked_at = disk_checked_at;
6390 } else {
6391 task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
6392 }
6393 record(queue, task);
6394 return Vec::new();
6395 }
6396 Err(e) if task.pr_recovery.is_some() => {
6400 task.startup_notice_cause("startup-public-head");
6401 task.attempts += 1;
6402 task.last_error = Some(format!("{start_failed}{e:#}"));
6403 task.hold_unrequested_retry(Some(format!(
6404 "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."
6405 )));
6406 record(queue, task);
6407 return Vec::new();
6408 }
6409 Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
6410 let detail = match e.downcast_ref::<crate::handover::Refused>() {
6411 Some(r) => (p.handover_refused)(r),
6412 None => format!("{e:#}"),
6413 };
6414 task.startup_notice_cause("startup-handover");
6415 let reason = format!("{start_failed}{detail}");
6416 task.last_error = Some(reason.clone());
6417 let branch = match &starter {
6420 Starter::Review(branch) => Some(branch.clone()),
6421 _ => None,
6422 };
6423 task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
6427 record(queue, task);
6428 tracing::warn!(
6429 "holding {} for a branch it cannot take over: {e:#}",
6430 task.short()
6431 );
6432 return Vec::new();
6433 }
6434 Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
6439 let d = e
6440 .downcast_ref::<crate::reconcile::Diverged>()
6441 .expect("checked by the guard");
6442 let mut q = ask::Question::new(
6443 task.id.clone(),
6444 crate::reconcile::NODE.to_owned(),
6445 crate::reconcile::SEAT.to_owned(),
6446 d.summary(),
6447 d.detail(),
6448 d.choices(),
6449 );
6450 match Questions::open().put(&mut q) {
6451 Ok(()) => {
6452 task.last_error = Some(format!("{e:#}"));
6453 task.review_branch = Some(d.branch.clone());
6456 task.review_instruction = Some(task.instruction.clone());
6457 task.block(vec![q.id.clone()], Some(d.summary()));
6458 }
6459 Err(put) => {
6460 tracing::warn!("could not file the divergence question: {put:#}");
6461 task.attempts += 1;
6462 task.fail_startup(
6463 "startup-question-store",
6464 format!("{start_failed}{e:#}"),
6465 opts.max_attempts,
6466 );
6467 }
6468 }
6469 record(queue, task);
6470 return Vec::new();
6471 }
6472 Err(e) => {
6473 if e.downcast_ref::<crate::reconcile::Stale>().is_some()
6479 && let Starter::Review(branch) = &starter
6480 {
6481 task.review_branch = Some(branch.clone());
6482 task.review_instruction = Some(task.instruction.clone());
6483 task.last_error = Some(format!("{start_failed}{e:#}"));
6484 task.status = crate::queue::TaskStatus::Failed;
6485 record(queue, task);
6486 return Vec::new();
6487 }
6488 task.attempts += 1;
6489 task.last_error = Some(format!("{start_failed}{e:#}"));
6490 task.startup_notice_cause("startup-source");
6491 task.hold_unrequested_retry(Some(format!(
6492 "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
6493 )));
6494 record(queue, task);
6495 return Vec::new();
6496 }
6497 };
6498 if !matches!(starter, Starter::Resume(_))
6499 && let Some((mode, source)) = task.build_cache_override(&runner.state.config)
6500 {
6501 runner
6502 .state
6503 .event("build-cache", format!("{mode} selected by {source}"));
6504 }
6505 if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
6506 runner.state.recovery_config = Some(config_evidence);
6507 }
6508 if let Some(replacement) = &task.replacement {
6509 if matches!(starter, Starter::Start) {
6510 runner.state.instruction.push_str(&format!(
6511 "\n\n# Replacement review context\n{}",
6512 replacement.context
6513 ));
6514 }
6515 runner.state.replaces = Some(replacement.clone());
6516 runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
6517 if let Ok(mut old) = RunState::load(&replacement.run)
6518 && let Some(d) = &mut old.merge_decision
6519 {
6520 d.replacement_run = Some(runner.state.id.clone());
6521 old.event(
6522 "replacement",
6523 format!(
6524 "replacement run {} owns the next attempt; old PR remains closed",
6525 runner.state.id
6526 ),
6527 );
6528 if let Err(e) = old.save() {
6529 let error = runner.fail_startup("replacement-history", e);
6530 if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
6531 task.record_startup_failure(failure.clone());
6532 }
6533 task.hold_manual(Some(format!(
6534 "Could not link replacement history: {error:#}; no agents dispatched"
6535 )));
6536 record(queue, task);
6537 return Vec::new();
6538 }
6539 }
6540 }
6541 runner.state.task_instruction = Some(task.instruction.clone());
6542 runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
6545 if runner.state.origin_chat.is_none() {
6546 runner.state.origin_chat = task.chat_talk().map(str::to_owned);
6547 }
6548 runner.on_pause(stop.pause());
6550 runner.watch_interrupt(interrupt_pause);
6554
6555 let run = runner.state.id.clone();
6558 let before_start = task.clone();
6559 task.start(run.clone());
6560 if let Err(error) = queue.put(task) {
6561 *task = before_start;
6562 let error = runner.fail_startup("task-start", error);
6563 if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
6564 task.record_startup_failure(failure.clone());
6565 }
6566 task.hold_manual(Some(format!(
6567 "Could not persist task start; no agents dispatched: {error:#}"
6568 )));
6569 record(queue, task);
6570 return Vec::new();
6571 }
6572 if task.status != TaskStatus::Running {
6573 return Vec::new();
6575 }
6576 lock(status).current.push(Current {
6577 worker: None,
6578 task: task.id.clone(),
6579 run,
6580 });
6581
6582 let quota_before = runner.state.quota.clone();
6585 runner.state.carry_dispatched_resumes(task);
6586 runner.state.entry_resumption_generation =
6587 Some(task.resumption.as_ref().map_or(0, |r| r.generation));
6588 if let Some((run, stop_id, generation, approval_at)) = head_e2e_approval
6589 && runner.state.id == run
6590 {
6591 crate::head_e2e_stop::record_consumed_approval(
6592 &mut runner.state,
6593 &task.id,
6594 &stop_id,
6595 generation,
6596 approval_at,
6597 );
6598 }
6599 runner.state.next_pass_task_entry = true;
6600 let result = runner.execute().await;
6601 finish_attempt(
6602 opts.max_attempts,
6603 queue,
6604 task,
6605 &runner.state,
6606 "a_before,
6607 result,
6608 )
6609}
6610
6611async fn attempt_sync_only(
6612 queue: &Queue,
6613 status: &Arc<Mutex<Status>>,
6614 stop: &Stop,
6615 interrupt: crate::graph::Pause,
6616 task: &mut Task,
6617 request: crate::base_sync_only::Request,
6618) {
6619 let result = async {
6620 anyhow::ensure!(
6621 task.status == TaskStatus::Queued
6622 && task.execution_runs().last() == Some(&request.run)
6623 && task.resume_override.as_ref().is_some_and(
6624 |pin| pin.at == request.at && pin.pinned_run.as_ref() == Some(&request.run)
6625 ),
6626 "sync-base-only request no longer owns the exact queued run"
6627 );
6628 let mut runner = Runner::resume(&request.run)?;
6629 anyhow::ensure!(
6630 public_resume_owner(&crate::run::home(), &task.runs, &runner.state.repo)
6631 .await?
6632 .is_none(),
6633 "the task still has a public execution owner"
6634 );
6635 anyhow::ensure!(
6636 !stop.parking() && !interrupt.parked(),
6637 "paused before base synchronization"
6638 );
6639 let original = task.clone();
6640 task.start(request.run.clone());
6641 task.attempts = original.attempts;
6642 if let Err(error) = queue.put(task) {
6643 *task = original;
6644 return Err(error);
6645 }
6646 if task.status != TaskStatus::Running || task.sync_only.as_ref() != Some(&request) {
6647 return Ok(());
6648 }
6649 lock(status).current.push(Current {
6650 worker: None,
6651 task: task.id.clone(),
6652 run: request.run.clone(),
6653 });
6654 runner.on_pause(stop.pause());
6655 runner.watch_interrupt(interrupt);
6656 runner.execute_sync_only(request.clone()).await
6657 }
6658 .await;
6659 if task.sync_only.as_ref() == Some(&request) {
6660 let saved = RunState::load(&request.run).ok();
6661 let detail = result.err().map(|error| {
6662 format!("Base synchronization only: {error:#}; verification was not allowed")
6663 });
6664 crate::base_sync_only::settle(task, &request, saved.as_ref(), detail);
6665 record(queue, task);
6666 }
6667}
6668
6669pub fn finish_attempt(
6674 max_attempts: usize,
6675 queue: &Queue,
6676 task: &mut Task,
6677 state: &RunState,
6678 quota_before: &[QuotaLoss],
6679 result: Result<()>,
6680) -> Vec<QuotaLoss> {
6681 let detail = match result {
6682 Ok(()) => describe(state),
6683 Err(e) => format!("{e:#}"),
6684 };
6685 let fresh = losses_this_attempt(quota_before, &state.quota);
6686 let verdict = Verdict {
6687 status: state.status,
6688 left_pr: state.pr.is_some(),
6691 quota_hit: !fresh.is_empty(),
6697 parked: state.parked,
6701 no_viable_candidates: state.viable().is_empty(),
6704 };
6705 if let Some(replacement) = &state.replaces
6706 && let Some(pr) = &state.pr
6707 && let Ok(mut old) = RunState::load(&replacement.run)
6708 && let Some(d) = &mut old.merge_decision
6709 {
6710 d.replacement_pr = Some(pr.url.clone());
6711 let _ = old.save();
6712 }
6713 settle_and_diagnose(task, verdict, &detail, max_attempts, state);
6714 if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
6715 task.hold_unrequested_retry(Some(format!(
6716 "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.",
6717 task.short()
6718 )));
6719 }
6720 if task.status == TaskStatus::Done {
6721 supersede_prior_runs(task, &crate::run::home());
6722 }
6723 record(queue, task);
6724 tracing::info!(
6725 "task {} is {} after run {} ({})",
6726 task.short(),
6727 task.status.as_str(),
6728 state.short(),
6729 label(state.status)
6730 );
6731 fresh
6732}
6733
6734pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
6738 if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
6741 && !awaiting_resume_with(task, RunState::load)
6742 && withheld_text_wait(task).is_none()
6746 && !(task.fresh_start && task.replacement.is_some())
6747 {
6748 let why = task.last_error.clone().map_or_else(
6749 || "the run did not finish".to_owned(),
6750 |e| format!("the run did not finish: {e}"),
6751 );
6752 task.hold_unrequested_retry(Some(format!(
6753 "{why}. It was started by hand, so it is not retried \
6754 automatically; `magi task release` retries it."
6755 )));
6756 record(queue, task);
6757 }
6758}
6759
6760#[must_use]
6764pub fn loop_would_resume(run: &str) -> bool {
6765 unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
6766}
6767
6768#[must_use]
6778pub fn foreign_loop(
6779 reading: Option<&Reading>,
6780 now: Timestamp,
6781 own_pid: u32,
6782) -> Option<Option<u32>> {
6783 let reading = reading.filter(|r| r.running(now))?;
6784 match reading.pid {
6785 Some(pid) if pid == own_pid => None,
6786 pid => Some(pid),
6787 }
6788}
6789
6790fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
6791 reading.worker_protocol != Some(1)
6792 && (foreign_loop(Some(reading), now, own_pid).is_some()
6793 || reading
6794 .pid
6795 .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
6796}
6797
6798pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
6809 run_claimed_until(opts, queue, task, &Stop::new()).await;
6810}
6811
6812async fn run_claimed_until(
6813 opts: &Opts,
6814 queue: &Queue,
6815 task: &mut Task,
6816 stop: &Stop,
6817) -> Vec<QuotaLoss> {
6818 let status = Arc::new(Mutex::new(Status::new()));
6819 let mut quota = Box::pin(attempt(
6822 opts,
6823 queue,
6824 &status,
6825 stop,
6826 crate::graph::Pause::new(),
6827 task,
6828 ))
6829 .await;
6830 let mut resumes = 0;
6839 while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
6840 let Some(timeout) = withheld_text_wait(task) else {
6841 break;
6842 };
6843 eprintln!(
6844 "waiting for the owner's answer on a withheld pull request text \
6845 (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
6846 );
6847 let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
6850 let ready = loop {
6851 match land_resume_state(task) {
6852 LandResume::StillWaiting
6853 if !stop.parking() && std::time::Instant::now() < limit =>
6854 {
6855 tokio::time::sleep(WITHHELD_POLL).await;
6856 }
6857 LandResume::Ready => break true,
6858 _ => break false,
6859 }
6860 };
6861 if !ready || stop.parking() {
6862 break;
6863 }
6864 resumes += 1;
6865 quota.extend(
6866 Box::pin(attempt(
6867 opts,
6868 queue,
6869 &status,
6870 stop,
6871 crate::graph::Pause::new(),
6872 task,
6873 ))
6874 .await,
6875 );
6876 }
6877 hold_if_runnable(queue, task);
6878 quota
6879}
6880
6881const MAX_WITHHELD_RESUMES: u32 = 3;
6884
6885const WITHHELD_POLL: Duration = Duration::from_secs(15);
6887
6888fn withheld_text_wait(task: &Task) -> Option<u64> {
6891 let id = task.execution_runs().last()?;
6892 let s = RunState::load(id).ok()?;
6893 (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
6894 .then_some(s.config.graph.answer_timeout)
6895}
6896
6897fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
6907 after
6908 .iter()
6909 .filter(|q| !before.contains(q))
6910 .cloned()
6911 .collect()
6912}
6913
6914fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
6917 let quota: Vec<_> = quota
6918 .iter()
6919 .filter(|q| q.cause == crate::agent::QuotaCause::UsageLimit)
6920 .collect();
6921 if quota.is_empty() {
6922 return None;
6923 }
6924 let with_hint = quota.iter().find(|q| q.reset.is_some());
6925 let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
6926 let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
6927 let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
6928 Some(
6929 now.checked_add(jiff::SignedDuration::from_secs(secs))
6930 .unwrap_or(Timestamp::MAX),
6931 )
6932}
6933
6934fn implementers_match(task: &Task, state: &RunState) -> bool {
6936 task.replacement.as_ref().map_or_else(
6937 || {
6938 task.implementers()
6939 .is_none_or(|n| n == state.config.graph.implementers)
6940 },
6941 |replacement| {
6942 state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
6943 && state.config.graph.implementers == 1
6944 },
6945 )
6946}
6947
6948fn starter_with_implementers(
6950 task: &Task,
6951 previous: Option<&RunState>,
6952 proposed: Starter,
6953) -> Starter {
6954 if previous.is_some_and(|s| !implementers_match(task, s)) {
6955 task.review_of
6956 .as_ref()
6957 .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
6958 } else {
6959 proposed
6960 }
6961}
6962
6963fn apply_task_implementers(config: &mut Config, task: &Task) {
6965 if let Some(n) = task.implementers() {
6966 config.graph.implementers = n;
6967 }
6968}
6969
6970#[cfg(test)]
6975fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
6976 let explicit = match &task.overrides {
6977 Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
6978 _ => opts.config.as_deref(),
6979 };
6980 let (mut config, _) = Config::discover(repo, explicit)?;
6981 apply_options(&mut config, opts, task)?;
6982 Ok(config)
6983}
6984
6985fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
6986 if task
6987 .overrides
6988 .as_ref()
6989 .is_none_or(|o| o.inherit_daemon_options)
6990 && let Some(mode) = opts.merge.as_deref()
6991 {
6992 config.merge.mode = merge_mode(mode)?;
6993 }
6994 if let Some(o) = &task.overrides {
6995 o.apply(config);
6996 }
6997 if let Some((mode, _)) = task.build_cache_override(config) {
6998 config.verify.build_cache = mode;
6999 }
7000 Ok(())
7001}
7002
7003fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
7005 let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
7006 if let Some(mode) = &opts.merge {
7007 config.merge.mode = merge_mode(mode)?;
7008 }
7009 Ok(config)
7010}
7011
7012async fn maybe_prune_cache_between_runs(
7017 repo: &Path,
7018 opts: &Opts,
7019 home: &Path,
7020 stop: &Stop,
7021 last_checked: &mut Option<Timestamp>,
7022 now: Timestamp,
7023) {
7024 if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
7025 return;
7026 }
7027 *last_checked = Some(now);
7028 let cfg = match prepare(repo, opts) {
7029 Ok(cfg) => cfg,
7030 Err(e) => {
7031 tracing::warn!("cache check: no config: {e:#}");
7032 return;
7033 }
7034 };
7035 match clean::prune_cache_if_over_limit(&cfg, home) {
7036 Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
7037 "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
7038 pruned.files,
7039 pruned.freed
7040 ),
7041 Ok(_) => {}
7042 Err(e) => {
7043 tracing::warn!("housekeep: prune cache: {e:#}");
7044 notices::raise_in(
7045 home,
7046 Notice::warn(
7047 "housekeep:cache",
7048 format!(
7049 "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
7050 e.to_string()
7051 .lines()
7052 .next()
7053 .unwrap_or("unknown cleanup error")
7054 ),
7055 ),
7056 );
7057 }
7058 }
7059}
7060
7061fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
7065 last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
7066}
7067
7068async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
7087 let cfg = match prepare(repo, opts) {
7088 Ok(cfg) => cfg,
7089 Err(e) => {
7090 tracing::warn!("housekeep: no config: {e:#}");
7091 return;
7092 }
7093 };
7094 let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
7103 let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
7104 if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
7109 let mut extra = Vec::new();
7110 if out.unreadable > 0 {
7111 extra.push(format!("{} unreadable", out.unreadable));
7112 }
7113 if out.orphaned_worktrees > 0 {
7114 extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
7115 }
7116 let detail = if extra.is_empty() {
7117 String::new()
7118 } else {
7119 format!(" ({})", extra.join(", "))
7120 };
7121 tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
7122 }
7123 if out.external_merges_recorded > 0 {
7124 tracing::info!(
7125 "housekeep: recorded {} run(s) as merged externally",
7126 out.external_merges_recorded
7127 );
7128 }
7129 if out.stale_pr_states_repaired > 0 {
7130 tracing::info!(
7131 "housekeep: updated {} run record(s) from the current pull request state",
7132 out.stale_pr_states_repaired
7133 );
7134 }
7135 if out.cache_files > 0 {
7136 tracing::info!(
7137 "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
7138 out.cache_files,
7139 out.cache_freed
7140 );
7141 }
7142 if out.questions_abandoned > 0 {
7143 tracing::info!(
7144 "housekeep: abandoned {} question(s) left open by a finished run",
7145 out.questions_abandoned
7146 );
7147 }
7148}
7149
7150async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
7159 let questions = Questions::at(home.join("questions"));
7160 let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
7161 if report.is_empty() {
7162 return;
7163 }
7164 if !report.quarantined.is_empty() {
7165 tracing::info!(
7166 "triage: held {} blocked task(s) whose blocked-on task or \
7167 question no longer exists: {}",
7168 report.quarantined.len(),
7169 report.quarantined.join(", ")
7170 );
7171 }
7172 if !report.resumed.is_empty() {
7173 tracing::info!(
7174 "triage: resumed {} held task(s) whose machine hold had resolved: {}",
7175 report.resumed.len(),
7176 report.resumed.join(", ")
7177 );
7178 }
7179 if !report.asked.is_empty() {
7180 tracing::info!(
7181 "triage: asked about {} held task(s): {}",
7182 report.asked.len(),
7183 report.asked.join(", ")
7184 );
7185 }
7186 if !report.answered.is_empty() {
7187 tracing::info!(
7188 "triage: applied {} operator answer(s): {}",
7189 report.answered.len(),
7190 report.answered.join(", ")
7191 );
7192 }
7193}
7194
7195pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
7202 disk_gate_at(repo, config, crate::run::home)
7203}
7204
7205pub(crate) fn disk_gate_at(
7206 repo: &Path,
7207 config: &Config,
7208 home: impl FnOnce() -> PathBuf,
7209) -> Option<String> {
7210 let measure = if crate::build_target::isolated(config) {
7211 crate::disk::managed_free_bytes
7212 } else {
7213 crate::disk::free_bytes
7214 };
7215 disk_gate_with(repo, config, home, measure)
7216}
7217
7218fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
7222 repo: &Path,
7223 config: &Config,
7224 home: impl FnOnce() -> PathBuf,
7225 free_bytes: F,
7226) -> Option<String> {
7227 let min = config.disk.min_free_bytes;
7228 if min == 0 {
7229 return None;
7230 }
7231 let output = match config.verify.build_cache {
7232 BuildCache::Shared => config.cache_dir(),
7233 BuildCache::Isolated => Some(home()),
7234 };
7235 let default_worktree_root;
7236 let worktree_root = match config.graph.worktree_root.as_deref() {
7237 Some(root) => root,
7238 None => {
7239 default_worktree_root = crate::run::default_worktree_root();
7240 &default_worktree_root
7241 }
7242 };
7243 for path in [Some(repo), output.as_deref(), Some(worktree_root)]
7244 .into_iter()
7245 .flatten()
7246 {
7247 let probe = if path == repo {
7248 path
7249 } else {
7250 path.ancestors().find(|p| p.exists()).unwrap_or(path)
7251 };
7252 let reason = match free_bytes(probe) {
7253 Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
7254 Err(e) => Some(crate::disk::unmeasured_in(
7255 probe,
7256 &e,
7257 &config.graph.language,
7258 )),
7259 };
7260 if reason.is_some() {
7261 return reason;
7262 }
7263 }
7264 None
7265}
7266
7267const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
7274
7275const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
7279
7280fn quota_wait(
7289 reset_at: Option<Timestamp>,
7290 now: Timestamp,
7291 fallback: Duration,
7292 cap: Duration,
7293) -> Duration {
7294 match reset_at {
7295 Some(at) if at > now => {
7296 let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
7297 Duration::from_secs(secs).min(cap)
7298 }
7299 _ => fallback,
7300 }
7301}
7302
7303fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
7317 parse_reset_hint_zoned(text, now)
7318 .or_else(|| parse_reset_hint_dated(text))
7319 .or_else(|| parse_reset_hint_relative(text, recorded))
7320}
7321
7322fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
7326 let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
7327 let mut rest = rest.trim();
7328 if rest.is_empty() {
7329 return None;
7330 }
7331 let mut total: i64 = 0;
7332 let mut matched = false;
7333 for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
7334 if let Some((digits, tail)) = rest.split_once(unit)
7335 && !digits.is_empty()
7336 && digits.bytes().all(|b| b.is_ascii_digit())
7337 {
7338 total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
7339 rest = tail;
7340 matched = true;
7341 }
7342 }
7343 if !rest.is_empty() || !matched {
7344 return None;
7345 }
7346 recorded
7347 .checked_add(jiff::SignedDuration::from_secs(total))
7348 .ok()
7349}
7350
7351fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
7355 let clock = clock.trim().to_lowercase();
7356 let (digits, pm) = clock
7357 .strip_suffix("am")
7358 .map(|d| (d, false))
7359 .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
7360 let (h, m) = digits.trim().split_once(':')?;
7361 let mut hour: i8 = h.trim().parse().ok()?;
7362 let minute: i8 = m.trim().parse().ok()?;
7363 if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
7364 return None;
7365 }
7366 if pm && hour != 12 {
7367 hour += 12;
7368 } else if !pm && hour == 12 {
7369 hour = 0;
7370 }
7371 Some((hour, minute))
7372}
7373
7374fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
7379 let open = text.find('(')?;
7380 let close = text.rfind(')')?;
7381 if close <= open {
7382 return None;
7383 }
7384 let zone = text[open + 1..close].trim();
7385 let (hour, minute) = parse_12h_clock(&text[..open])?;
7386 let tz = jiff::tz::TimeZone::get(zone).ok()?;
7387 let candidate = now
7388 .to_zoned(tz)
7389 .with()
7390 .hour(hour)
7391 .minute(minute)
7392 .second(0)
7393 .millisecond(0)
7394 .microsecond(0)
7395 .nanosecond(0)
7396 .build()
7397 .ok()?;
7398 let mut at = candidate.timestamp();
7399 if at <= now {
7400 at += jiff::SignedDuration::from_hours(24);
7401 }
7402 Some(at)
7403}
7404
7405fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
7414 let words: Vec<&str> = text.split_whitespace().collect();
7415 if words.len() < 5 {
7416 return None;
7417 }
7418 (0..=words.len() - 5)
7419 .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
7420}
7421
7422fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
7428 if trailing.is_some_and(|next| next.starts_with('(')) {
7429 return None;
7430 }
7431 let month = month_number(window[0])?;
7432 let day_token = window[1].strip_suffix(',')?.to_lowercase();
7433 let day_digits = ["st", "nd", "rd", "th"]
7434 .iter()
7435 .find_map(|suffix| day_token.strip_suffix(*suffix))?;
7436 let day: i8 = day_digits.parse().ok()?;
7437 let year_token = window[2];
7438 if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
7439 return None;
7440 }
7441 let year: i16 = year_token.parse().ok()?;
7442 let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
7446 let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
7447 let date = jiff::civil::Date::new(year, month, day).ok()?;
7448 let candidate = date
7449 .at(hour, minute, 0, 0)
7450 .to_zoned(jiff::tz::TimeZone::UTC)
7451 .ok()?;
7452 Some(candidate.timestamp())
7453}
7454
7455fn month_number(name: &str) -> Option<i8> {
7458 const NAMES: [&str; 12] = [
7459 "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
7460 ];
7461 let lower = name.to_lowercase();
7462 NAMES
7463 .iter()
7464 .position(|n| *n == lower.as_str())
7465 .map(|i| i as i8 + 1)
7466}
7467
7468#[cfg(test)]
7470fn exhausted_review_budget(state: &RunState) -> bool {
7471 !crate::handover::can_resume(state)
7474 && state.status == RunStatus::Blocked
7475 && !state.released()
7476 && state.retired_to.is_none()
7477}
7478
7479fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
7516 unfinished_run_with(runs, short, RunState::load)
7517}
7518
7519pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
7522where
7523 F: FnMut(&str) -> Result<RunState>,
7524{
7525 let mut id = runs.last()?.clone();
7526 let mut visited = std::collections::BTreeSet::new();
7527 let mut repo = None;
7528 loop {
7529 if !runs.contains(&id) || !visited.insert(id.clone()) {
7530 tracing::warn!("invalid or cyclic recovery authority for task {short}");
7531 return None;
7532 }
7533 let state = match load(&id) {
7534 Ok(state) if state.id == id => state,
7535 Ok(_) => return None,
7536 Err(e) => {
7537 tracing::warn!("could not read run {id} for task {short}: {e:#}");
7538 return None;
7539 }
7540 };
7541 if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
7542 return None;
7543 }
7544 repo = Some(state.repo.clone());
7545 if let Some(authority) = state.retired_to {
7546 id = authority;
7547 continue;
7548 }
7549 return (crate::handover::can_resume(&state)
7550 && state.liveness(false) != crate::run::Liveness::Live)
7551 .then_some(id);
7552 }
7553}
7554
7555fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
7563where
7564 F: FnOnce(&str) -> Result<RunState>,
7565{
7566 if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
7568 || task.fresh_start
7569 || task.review_branch.is_some()
7570 {
7571 return false;
7572 }
7573 let Some(id) = task.execution_runs().last() else {
7574 return false;
7575 };
7576 load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
7577}
7578
7579#[derive(Debug, Clone, PartialEq, Eq)]
7582enum Starter {
7583 Review(String),
7586 Resume(String),
7588 Start,
7590}
7591
7592fn retained_attempt_hold(
7597 task: &Task,
7598 starter: &Starter,
7599 limit: usize,
7600 mut load: impl FnMut(&str) -> Result<RunState>,
7601) -> Option<String> {
7602 if limit == 0 || matches!(starter, Starter::Resume(_)) {
7603 return None;
7604 }
7605 let mut retained = 0;
7606 for id in task
7607 .runs
7608 .iter()
7609 .chain(task.startup_failures.iter().map(|failure| &failure.run))
7610 .collect::<std::collections::BTreeSet<_>>()
7611 {
7612 let state = match load(id) {
7613 Ok(state) if state.id == *id => state,
7614 _ => {
7615 return Some(format!(
7616 "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
7617 ));
7618 }
7619 };
7620 if state.retired_to.is_some() || state.released() {
7621 continue;
7622 }
7623 retained += 1;
7626 }
7627 (retained >= limit).then(|| format!(
7628 "[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."
7629 ))
7630}
7631
7632fn selected_starter(
7634 selected: &crate::pr_recovery::Selection,
7635 previous: Option<&RunState>,
7636 unfinished: Option<&str>,
7637) -> Starter {
7638 if let Some(id) = unfinished
7639 && previous.is_some_and(|r| {
7640 r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
7641 })
7642 {
7643 Starter::Resume(id.to_owned())
7644 } else {
7645 Starter::Review(selected.branch.clone())
7646 }
7647}
7648
7649fn take_divergence_answer(
7653 branch: &str,
7654 remote: &str,
7655 task: &mut Task,
7656) -> Option<crate::reconcile::Choice> {
7657 let summary = crate::reconcile::summary_for(branch, remote);
7658 let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
7659 (a.question == summary)
7660 .then(|| crate::reconcile::Choice::from_answer(&a.answer))
7661 .flatten()
7662 .map(|c| (i, c))
7663 })?;
7664 task.answers.remove(idx);
7665 Some(choice)
7666}
7667
7668fn choose_starter(
7680 review_branch: Option<&str>,
7681 branch_exists: bool,
7682 unfinished: Option<&str>,
7683) -> Starter {
7684 match review_branch {
7685 Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
7686 Some(_) => Starter::Start,
7687 None => match unfinished {
7688 Some(id) => Starter::Resume(id.to_owned()),
7689 None => Starter::Start,
7690 },
7691 }
7692}
7693
7694fn review_retry_starter(
7698 task: &Task,
7699 previous: Option<&RunState>,
7700 branch: Option<&str>,
7701 exists: bool,
7702 unfinished: Option<&str>,
7703) -> Starter {
7704 if let Some(run) = previous
7705 && unfinished == Some(run.id.as_str())
7706 && run.reviewed_commits.is_some()
7707 && branch.is_some_and(|branch| {
7708 exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
7709 })
7710 && may_resume_run(run, task)
7711 {
7712 return Starter::Resume(run.id.clone());
7713 }
7714 match (branch, unfinished, &task.review_of) {
7715 (None, None, Some(branch)) => Starter::Review(branch.clone()),
7716 _ => choose_starter(branch, exists, unfinished),
7717 }
7718}
7719
7720fn review_branch_for<'a>(task: &'a Task, previous: Option<&RunState>) -> Option<&'a str> {
7722 task.review_branch
7723 .as_deref()
7724 .filter(|&branch| match &task.review_instruction {
7725 Some(authored) => *authored == task.instruction,
7726 None => previous.map_or_else(
7729 || task.review_of.as_deref() == Some(branch),
7730 |run| compatible_run_instruction(run, task),
7731 ),
7732 })
7733}
7734
7735fn may_resume_run(run: &RunState, task: &Task) -> bool {
7738 if !task.assignment_accepts(run) {
7739 return false;
7740 }
7741 task.resume_override
7742 .as_ref()
7743 .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
7744 || compatible_run_instruction(run, task)
7745}
7746
7747pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
7749 if let Some(authored) = &run.task_instruction {
7750 return compatible_instruction(authored, task);
7751 }
7752 if compatible_instruction(&run.instruction, task) {
7753 return true;
7754 }
7755 if run.reviewed_commits.is_some() {
7758 if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
7759 return strip_answers_block(authored, task).trim() == task.instruction.trim();
7760 }
7761 if let Some(branch) = &task.review_of {
7762 let canonical = format!(
7763 "Review the branch `{branch}` (review-only: no implementation, no judging)."
7764 );
7765 let generated = format!(
7766 "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"
7767 );
7768 return task.instruction == canonical && run.instruction.starts_with(&generated);
7769 }
7770 }
7771 false
7772}
7773
7774pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
7776 strip_answers_block(old, task) == task.instruction
7777}
7778
7779fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
7782 if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
7783 return fallback.to_path_buf();
7784 }
7785 task.repo.clone()
7786}
7787
7788const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
7792
7793fn answers_block(task: &Task, count: usize) -> String {
7795 let mut s = ANSWERS_HEADER.to_owned();
7796 for a in &task.answers[..count] {
7797 s.push_str(&format!("- {}: {}\n", a.question, a.answer));
7798 }
7799 s
7800}
7801
7802fn resumption_block(r: &crate::queue::Resumption) -> String {
7805 format!(
7806 "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
7807 Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
7808 r.generation, r.at, r.instruction, r.answers_through,
7809 )
7810}
7811
7812fn append_answers(base: &str, task: &Task) -> String {
7814 let mut s = base.to_owned();
7815 if !task.answers.is_empty() {
7816 s.push_str(&answers_block(task, task.answers.len()));
7817 }
7818 if let Some(r) = &task.resumption {
7819 s.push_str(&resumption_block(r));
7820 }
7821 s
7822}
7823
7824fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
7828 let mut instruction = instruction;
7829 for approval in task
7830 .resumption
7831 .iter()
7832 .chain(task.resumption_history.iter().rev())
7833 {
7834 if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
7835 instruction = base;
7836 break;
7837 }
7838 }
7839 for count in (1..=task.answers.len()).rev() {
7840 let block = answers_block(task, count);
7841 if let Some(base) = instruction.strip_suffix(&block) {
7842 return base;
7843 }
7844 }
7845 instruction
7846}
7847
7848fn instruction_for(task: &Task) -> String {
7856 append_answers(&task.instruction, task)
7857}
7858
7859fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
7871 append_answers(strip_answers_block(old_instruction, task), task)
7872}
7873
7874fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
7876 let failure = error.downcast_ref::<crate::config::ConfigFailure>();
7877 task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
7878 if let Some(cause) = task.hold_notice_cause.as_mut() {
7879 cause.target = failure.map(|f| f.target.clone());
7880 }
7881}
7882
7883#[derive(Debug, thiserror::Error)]
7884#[error("attachment `{name}` is recorded on the task but {path} is missing")]
7885struct MissingAttachment {
7886 name: String,
7887 path: PathBuf,
7888}
7889
7890fn task_attachments(
7892 queue: &Queue,
7893 task: &Task,
7894) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
7895 let paths = queue.attachment_paths(task);
7896 for (name, path) in task.attachments.iter().zip(&paths) {
7897 if !path.is_file() {
7898 return Err(MissingAttachment {
7899 name: name.clone(),
7900 path: path.clone(),
7901 });
7902 }
7903 }
7904 Ok(paths)
7905}
7906
7907fn prepare_instruction(
7918 starter: &Starter,
7919 old_instruction: Option<&str>,
7920 task: &Task,
7921) -> Option<String> {
7922 match starter {
7923 Starter::Start => Some(instruction_for(task)),
7924 Starter::Resume(_) => Some(resumed_instruction(
7925 old_instruction.expect("a resumed run always has a prior instruction"),
7926 task,
7927 )),
7928 Starter::Review(_) => None,
7929 }
7930}
7931
7932fn record(queue: &Queue, task: &mut Task) {
7936 if let Err(e) = queue.put(task) {
7937 tracing::error!("could not record task {}: {e:#}", task.short());
7938 let notice = Notice::error(
7939 "loop:record",
7940 format!(
7941 "Task {} state could not be saved: {}. Check the disk.",
7942 task.id,
7943 e.to_string().lines().next().unwrap_or("unknown save error")
7944 ),
7945 )
7946 .link(Link::Task {
7947 id: task.id.clone(),
7948 });
7949 match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
7951 Some(home) => notices::raise_in(home, notice),
7952 None => notices::raise(notice),
7953 }
7954 }
7955}
7956
7957fn runnable(queue: &Queue) -> Vec<Task> {
7963 let mut tasks: Vec<Task> = queue
7964 .list()
7965 .into_iter()
7966 .filter(|t| t.status.runnable())
7967 .collect();
7968 tasks.sort_unstable_by(crate::queue::dispatch_order);
7969 tasks
7970}
7971
7972fn describe(state: &RunState) -> String {
7986 let p = phrases(&state.config.graph.language);
7987 let mut detail = if state.status == RunStatus::Stalled {
7988 let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
7989 seats.sort_unstable();
7990 seats.dedup();
7991 if seats.is_empty() {
7992 p.quorum_lost.to_owned()
7993 } else {
7994 format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
7995 }
7996 } else {
7997 format!("{}{}", p.run_ended, state.status.display_label())
7998 };
7999 if let Some(cause) = state.verification_blocking_cause() {
8000 detail.push_str(&format!(" ({cause})"));
8001 } else if let Some(last) = state.events.last() {
8002 let unanswered = state
8006 .reviews
8007 .last()
8008 .filter(|r| {
8009 state.status == RunStatus::Blocked
8010 && last.node == "review"
8011 && r.incomplete()
8012 && r.blocking == 0
8013 && r.round == state.config.graph.review_rounds
8014 && r.e2e.iter().all(crate::run::CommandOutcome::ok)
8015 })
8016 .map(|r| (r.expected - r.answered, r.round));
8017 match unanswered {
8018 Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
8019 detail.push_str(&format!(
8020 " ({}: {})",
8021 last.node,
8022 (p.reviewers_never_answered)(missing, rounds)
8023 ));
8024 }
8025 _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
8026 }
8027 }
8028 detail.push_str(&format!(" [run {}]", state.id));
8029 detail
8030}
8031
8032const DIAGNOSTIC_MAX: usize = 4_000;
8038
8039const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
8044
8045pub(crate) fn diagnostic_for(state: &RunState) -> Option<String> {
8059 diagnostic(state)
8060}
8061
8062fn diagnostic(state: &RunState) -> Option<String> {
8063 let mut parts: Vec<String> = Vec::new();
8064
8065 if let Some(e2e) = &state.head_e2e
8066 && !e2e.passed
8067 {
8068 for o in e2e
8069 .outcomes
8070 .iter()
8071 .filter(|o| !o.ok() && !o.resource_blocked)
8072 {
8073 parts.push(format!(
8074 "head_e2e `{}` failed on {} ({}):\n{}",
8075 o.command,
8076 e2e.head.chars().take(7).collect::<String>(),
8077 notices::exit_status(o.code),
8078 crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
8079 ));
8080 }
8081 }
8082
8083 for o in state.gate.iter().filter(|o| !o.ok()) {
8085 parts.push(format!(
8086 "gate `{}` failed ({}):\n{}",
8087 o.command,
8088 notices::exit_status(o.code),
8089 crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
8090 ));
8091 }
8092
8093 if let Some(last) = state
8096 .events
8097 .iter()
8098 .rev()
8099 .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
8100 {
8101 parts.push(last.message.clone());
8102 }
8103
8104 if state.viable().is_empty() {
8111 for c in &state.candidates {
8112 if c.has_valid_verified_noop()
8113 && let Some(evidence) = c.verified_noop_display()
8114 {
8115 parts.push(format!(
8116 "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
8117 c.label
8118 ));
8119 } else if !c.summary.trim().is_empty() {
8120 if let Some(why) = &c.failed {
8121 parts.push(format!(
8122 "candidate {} ({why}): {}",
8123 c.label,
8124 c.summary.trim()
8125 ));
8126 } else {
8127 parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
8128 }
8129 } else if let Some(why) = &c.failed {
8130 parts.push(format!("candidate {}: {why}", c.label));
8131 }
8132 }
8133 }
8134
8135 if parts.is_empty() {
8136 return None;
8137 }
8138 Some(crate::run::tail(
8143 &parts.join("\n\n"),
8144 DIAGNOSTIC_MAX.saturating_sub(100),
8145 ))
8146}
8147
8148fn label(status: RunStatus) -> &'static str {
8156 status.as_str()
8157}
8158
8159pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
8161 match mode {
8162 "none" => Ok(MergeMode::None),
8163 "local" => Ok(MergeMode::Local),
8164 "pr" => Ok(MergeMode::Pr),
8165 other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
8166 }
8167}
8168
8169fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
8174 mutex
8175 .lock()
8176 .unwrap_or_else(std::sync::PoisonError::into_inner)
8177}
8178
8179#[cfg(test)]
8180mod tests {
8181 use super::*;
8182 use crate::queue::{Source, TaskStatus};
8183 use crate::run::{Candidate, CommandOutcome};
8184 use pretty_assertions::assert_eq;
8185
8186 fn task() -> Task {
8187 Task::new(
8188 "add retries".to_owned(),
8189 "add retries".to_owned(),
8190 PathBuf::from("/repo"),
8191 Source::Human,
8192 )
8193 }
8194
8195 #[test]
8196 fn dispatch_wait_aggregates_unique_skips_in_stable_count_order() {
8197 let skips = DispatchSkips::from([
8198 ("a".into(), SkipReason::CoolingDown),
8199 ("b".into(), SkipReason::WaitingOnLanding),
8200 ("c".into(), SkipReason::WaitingOnLanding),
8201 ("d".into(), SkipReason::OrdinaryCapacity),
8202 ]);
8203 let wait = aggregate_dispatch_wait(4, &skips).unwrap();
8204 assert_eq!(wait.runnable, 4);
8205 assert_eq!(
8206 wait.reasons
8207 .iter()
8208 .map(|r| (r.reason.as_str(), r.count))
8209 .collect::<Vec<_>>(),
8210 [
8211 ("waiting_on_landing", 2),
8212 ("cooling_down", 1),
8213 ("ordinary_capacity", 1)
8214 ]
8215 );
8216 assert_eq!(aggregate_dispatch_wait(0, &DispatchSkips::new()), None);
8217 assert!(
8218 aggregate_dispatch_wait(2, &DispatchSkips::new())
8219 .unwrap()
8220 .reasons
8221 .is_empty()
8222 );
8223 }
8224
8225 #[test]
8226 fn dispatch_wait_tracks_interrupt_withholding_and_set_changes() {
8227 let before = vec!["a".into(), "b".into(), "c".into()];
8228 let allowed = vec![task_with_id("b")];
8229 let skips = interrupt_skips(&before, &allowed);
8230 assert_eq!(
8231 skips,
8232 DispatchSkips::from([
8233 ("a".into(), SkipReason::InterruptGate),
8234 ("c".into(), SkipReason::InterruptGate),
8235 ])
8236 );
8237 let mut previous = DispatchSkips::new();
8238 assert!(!changed_dispatch_skips(&mut previous, DispatchSkips::new()));
8239 assert!(changed_dispatch_skips(&mut previous, skips.clone()));
8240 assert!(!changed_dispatch_skips(&mut previous, skips));
8241 assert!(changed_dispatch_skips(
8242 &mut previous,
8243 DispatchSkips::from([("a".into(), SkipReason::CoolingDown),])
8244 ));
8245 assert!(changed_dispatch_skips(&mut previous, DispatchSkips::new()));
8246 }
8247
8248 #[test]
8249 fn dispatch_wait_status_reads_legacy_and_future_reason_keys() {
8250 let mut value = serde_json::to_value(Status::new()).unwrap();
8251 value.as_object_mut().unwrap().remove("dispatch_wait");
8252 assert!(
8253 serde_json::from_value::<Status>(value.clone())
8254 .unwrap()
8255 .dispatch_wait
8256 .is_none()
8257 );
8258 assert!(
8259 serde_json::from_value::<Reading>(value.clone())
8260 .unwrap()
8261 .dispatch_wait
8262 .is_none()
8263 );
8264 value["dispatch_wait"] = serde_json::json!({
8265 "runnable": 3, "reasons": [{"reason": "future_reason", "count": 3}]
8266 });
8267 let reading = serde_json::from_value::<Reading>(value).unwrap();
8268 assert_eq!(
8269 reading.dispatch_wait.unwrap().reasons[0].reason,
8270 "future_reason"
8271 );
8272 }
8273
8274 fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
8275 let job = crate::worker::Job {
8276 id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
8277 sequence: 1,
8278 kind: "task".into(),
8279 key: format!("task:{}", request.task),
8280 payload: serde_json::to_value(request).unwrap(),
8281 generation: "a".repeat(64),
8282 version: None,
8283 status: crate::worker::Status::Starting,
8284 result: None,
8285 pid: None,
8286 created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
8287 finished_at: None,
8288 };
8289 let dir = home.join("workers/jobs").join(&job.id);
8290 std::fs::create_dir_all(&dir).unwrap();
8291 std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
8292 job
8293 }
8294
8295 #[test]
8296 fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
8297 let home = tempfile::tempdir().unwrap();
8298 let request = TaskWorker {
8299 opts: Opts::default(),
8300 queue: home.path().join("queue"),
8301 task: "startup".into(),
8302 lane: PermitKind::Ordinary,
8303 standalone: false,
8304 };
8305 let job = starting_task_reservation(home.path(), &request);
8306 let error = task_worker_spawn_error(
8307 home.path(),
8308 &request,
8309 anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
8310 )
8311 .expect_err("our own reservation must not turn a failed spawn into a resync");
8312 let active = crate::worker::active(home.path()).unwrap();
8313 assert_eq!(active.len(), 1);
8314 assert_eq!(active[0].id, job.id);
8315 assert_eq!(active[0].status, crate::worker::Status::Starting);
8316 assert!(
8317 crate::worker::control(home.path(), &job.key)
8318 .unwrap()
8319 .is_none()
8320 );
8321 let notices = notices::Notices::at(home.path().join("notifications")).list();
8322 assert_eq!(notices.len(), 1);
8323 assert_eq!(notices[0].key, "loop:worker-startup");
8324 assert!(!notices[0].message.contains("private-error-detail"));
8325 assert!(notices[0].message.contains(&request.task));
8326 assert!(
8327 notices[0]
8328 .message
8329 .contains("could not be started or acknowledged")
8330 );
8331 assert!(notices[0].message.contains("worker.log"));
8332 assert_eq!(
8333 notices[0].link,
8334 Some(Link::Task {
8335 id: request.task.clone()
8336 })
8337 );
8338 assert!(format!("{error:#}").contains("private-error-detail"));
8339 }
8340
8341 #[test]
8342 fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
8343 let home = tempfile::tempdir().unwrap();
8344 let mut request = TaskWorker {
8345 opts: Opts::default(),
8346 queue: home.path().join("queue"),
8347 task: "handoff".into(),
8348 lane: PermitKind::Ordinary,
8349 standalone: true,
8350 };
8351 let job = starting_task_reservation(home.path(), &request);
8352 request.standalone = false;
8353 task_worker_spawn_error(
8354 home.path(),
8355 &request,
8356 anyhow::anyhow!("operation key is already reserved for a different request"),
8357 )
8358 .expect("a different standalone request is the handoff race, not our startup failure");
8359 let active = crate::worker::active(home.path()).unwrap();
8360 assert_eq!(active.len(), 1);
8361 assert_eq!(active[0].id, job.id);
8362 assert_eq!(active[0].payload, job.payload);
8363 assert!(
8364 notices::Notices::at(home.path().join("notifications"))
8365 .list()
8366 .is_empty()
8367 );
8368 }
8369
8370 #[test]
8371 fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
8372 let home = tempfile::tempdir().unwrap();
8373 let queue = Queue::at(home.path().join("queue"));
8374 let mut task = task();
8375 task.runs = vec!["previous".into()];
8376 queue.put(&mut task).unwrap();
8377 let request = TaskWorker {
8378 opts: Opts::default(),
8379 queue: home.path().join("queue"),
8380 task: task.id.clone(),
8381 lane: PermitKind::Ordinary,
8382 standalone: false,
8383 };
8384 let job = starting_task_reservation(home.path(), &request);
8385 let claims = current_work(home.path(), Timestamp::now());
8386 assert_eq!(claims.len(), 1);
8387 assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
8388 assert_eq!(claims[0].run, "previous");
8389 assert!(other_claims_run(&claims, "previous", None));
8390 assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
8393 assert!(is_working_on(home.path(), "previous", Timestamp::now()));
8394 }
8395
8396 #[test]
8397 fn admission_excludes_only_the_callers_exact_reservation() {
8398 let own = Current {
8399 worker: Some("own".into()),
8400 task: "same-task".into(),
8401 run: "previous".into(),
8402 };
8403 assert!(!other_claims_run(
8404 std::slice::from_ref(&own),
8405 "previous",
8406 Some("own")
8407 ));
8408 assert!(other_claims_run(
8409 std::slice::from_ref(&own),
8410 "previous",
8411 None
8412 ));
8413 for worker in [None, Some("other".into())] {
8414 let other = Current {
8415 worker,
8416 ..own.clone()
8417 };
8418 assert!(other_claims_run(
8419 &[own.clone(), other],
8420 "previous",
8421 Some("own")
8422 ));
8423 }
8424 let legacy: Current =
8425 serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
8426 assert!(other_claims_run(&[legacy], "previous", Some("own")));
8427 }
8428
8429 #[test]
8430 fn os_leased_task_worker_survives_wall_clock_advance() {
8431 let home = tempfile::tempdir().unwrap();
8432 let queue = Queue::at(home.path().join("queue"));
8433 let mut task = task();
8434 let run = "20260903-100000-abcd";
8435 task.start(run.into());
8436 queue.put(&mut task).unwrap();
8437 let mut worker = live_task_fixture(home.path(), &task.id).unwrap();
8438 let future = Timestamp::now() + jiff::SignedDuration::from_secs(3600);
8439 assert!(
8440 current_work(home.path(), future)
8441 .iter()
8442 .any(
8443 |claim| claim.worker.as_deref() == Some(worker.job.id.as_str())
8444 && claim.run == run
8445 )
8446 );
8447 worker.release_lease();
8448 assert!(worker.dir.join("job.json").is_file());
8449 assert!(!is_working_on(home.path(), run, future));
8450 let dir = worker.dir.clone();
8451 drop(worker);
8452 assert!(!dir.exists());
8453 }
8454
8455 #[test]
8456 fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
8457 let mut task = task();
8458 let mut run = run_state(RunStatus::Reviewing);
8459 run.task_instruction = Some(task.instruction.clone());
8460 run.reviewed_commits = Some(vec!["committed-fix".into()]);
8461 let branch = "magi/test/B";
8462 run.candidates.push(crate::run::Candidate {
8463 branch: branch.into(),
8464 ..candidate('B', "preserved work", false, None)
8465 });
8466 task.runs = vec![run.id.clone()];
8467 let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
8468 assert_eq!(
8469 review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
8470 Starter::Resume(run.id.clone())
8471 );
8472 assert!(matches!(
8473 review_retry_starter(
8474 &task,
8475 Some(&run),
8476 Some("different"),
8477 true,
8478 unfinished.as_deref()
8479 ),
8480 Starter::Review(_)
8481 ));
8482 assert_eq!(
8483 review_retry_starter(
8484 &task,
8485 Some(&run),
8486 Some(branch),
8487 false,
8488 unfinished.as_deref()
8489 ),
8490 Starter::Start
8491 );
8492 task.instruction.push_str(" changed criteria");
8493 assert!(matches!(
8494 review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
8495 Starter::Review(_)
8496 ));
8497 assert!(matches!(
8498 review_retry_starter(&task, Some(&run), Some(branch), true, None),
8499 Starter::Review(_)
8500 ));
8501 }
8502
8503 #[test]
8504 fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
8505 let dir = tempfile::tempdir().unwrap();
8506 let queue = Queue::at(dir.path().join("queue"));
8507 let mut task = task();
8508 task.status = TaskStatus::Running;
8509 task.attempts = 1;
8510 queue.put(&mut task).unwrap();
8511 let live = std::collections::BTreeSet::from([task.id.clone()]);
8512 assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
8513 drop(queue.claim(&task.id).unwrap());
8514 let saved = queue.get(&task.id).unwrap();
8515 assert_eq!(saved.status, TaskStatus::Running);
8516 assert_eq!(saved.attempts, 1);
8517 assert!(saved.last_error.is_none());
8518 }
8519
8520 #[test]
8521 fn standalone_workers_do_not_consume_scheduler_lanes() {
8522 let request = |task: &str, lane, standalone| TaskWorker {
8523 opts: Opts::default(),
8524 queue: PathBuf::from("/queue"),
8525 task: task.to_owned(),
8526 lane,
8527 standalone,
8528 };
8529 let mut jobs = vec![
8530 request("ordinary", PermitKind::Ordinary, false),
8531 request("standalone-urgent", PermitKind::Urgent, true),
8532 request("standalone-ordinary", PermitKind::Ordinary, true),
8533 request("decision", PermitKind::None, false),
8534 ];
8535 assert_eq!(available_slots(&jobs, 2), (1, 1));
8536 jobs.push(request("urgent", PermitKind::Urgent, false));
8537 assert_eq!(available_slots(&jobs, 2), (1, 0));
8538 assert_eq!(available_slots(&jobs, 0), (0, 0));
8539 }
8540
8541 #[test]
8542 fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
8543 let now = Timestamp::now();
8544 let mut reading = Reading {
8545 pid: Some(std::process::id()),
8546 updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
8547 ..Reading::default()
8548 };
8549 assert!(!reading.running(now));
8550 assert!(legacy_scheduler_running(&reading, now, 0));
8551 reading.worker_protocol = Some(1);
8552 assert!(!legacy_scheduler_running(&reading, now, 0));
8553 }
8554
8555 #[test]
8556 fn selected_public_head_overrides_historical_resume_and_pin() {
8557 let mut t = task();
8558 let mut old = run_state(RunStatus::Blocked);
8559 let selection = crate::pr_recovery::Selection {
8560 url: "url".into(),
8561 branch: format!("magi/task-{}", t.id),
8562 head: "a".repeat(40),
8563 source_head: None,
8564 source_run: None,
8565 source_proof: None,
8566 disposition: Some(crate::pr_recovery::Disposition::Review),
8567 instruction: t.instruction.clone(),
8568 approved_at: Timestamp::now(),
8569 };
8570 t.resume_override = Some(crate::queue::OperatorResume {
8571 pinned_run: Some(old.id.clone()),
8572 question_id: "choice".into(),
8573 at: Timestamp::now(),
8574 conductor_rehold: None,
8575 forced: false,
8576 });
8577 assert_eq!(
8578 selected_starter(&selection, Some(&old), Some(&old.id)),
8579 Starter::Review(selection.branch.clone())
8580 );
8581 old.pr_recovery = Some(selection.clone());
8582 assert_eq!(
8583 selected_starter(&selection, Some(&old), Some(&old.id)),
8584 Starter::Review(selection.branch.clone())
8585 );
8586 old.reviewed_commits = Some(vec!["implementation".into()]);
8587 assert_eq!(
8588 selected_starter(&selection, Some(&old), Some(&old.id)),
8589 Starter::Resume(old.id.clone())
8590 );
8591 let mut changed = selection.clone();
8592 changed.head = "b".repeat(40);
8593 assert_eq!(
8594 selected_starter(&changed, Some(&old), Some(&old.id)),
8595 Starter::Review(changed.branch)
8596 );
8597 }
8598
8599 #[test]
8600 fn candidate_transplant_failure_is_one_actionable_hold() {
8601 let dir = tempfile::tempdir().unwrap();
8602 let q = Queue::at(dir.path().join("queue"));
8603 let mut t = task();
8604 let mut state = run_state(RunStatus::Blocked);
8605 state.event("prep", "cannot apply referenced commit: conflict");
8606 state.prep_failure = Some("conflict".into());
8607 t.start(state.id.clone());
8608 finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
8609 assert_eq!(t.attempts, 1);
8610 assert_eq!(t.status, TaskStatus::Held);
8611 assert!(t.operator_held());
8612 assert!(!t.status.runnable());
8613 assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
8614 let first = t.chat_notice_key().unwrap();
8615 t.chat_notices.push(first.clone());
8616 t.release_operator("test", None);
8617 state.id = "another-unprepared-run".into();
8618 t.start(state.id.clone());
8619 finish_attempt(
8620 3,
8621 &q,
8622 &mut t,
8623 &state,
8624 &[],
8625 Err(anyhow::anyhow!("still conflicts")),
8626 );
8627 assert_eq!(
8628 t.chat_notice_key().as_ref(),
8629 Some(&first),
8630 "no work happened"
8631 );
8632 t.release_operator("test", None);
8633 state.prep_failure = None;
8634 state.status = RunStatus::Failed;
8635 state.begin_pass();
8636 t.start(state.id.clone());
8637 finish_attempt(
8638 1,
8639 &q,
8640 &mut t,
8641 &state,
8642 &[],
8643 Err(anyhow::anyhow!("new gate failure")),
8644 );
8645 let failure = t.chat_notice_key().unwrap();
8646 assert_ne!(failure, first, "approved recovery reached a real failure");
8647 t.release_operator("test", None);
8648 state.begin_pass();
8649 t.start(state.id.clone());
8650 finish_attempt(
8651 1,
8652 &q,
8653 &mut t,
8654 &state,
8655 &[],
8656 Err(anyhow::anyhow!("new failure on resume")),
8657 );
8658 assert_ne!(
8659 t.chat_notice_key().as_ref(),
8660 Some(&failure),
8661 "a new settled pass"
8662 );
8663 }
8664
8665 #[test]
8666 fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
8667 for source in ["cli", "web"] {
8668 let mut t = task();
8669 let mut run = run_state(RunStatus::Blocked);
8670 run.instruction = "Run A original criteria".into();
8671 run.task_instruction = Some(run.instruction.clone());
8672 t.start(run.id.clone());
8673 t.release_operator("choice", Some("resume-question"));
8674 t.resume_override = Some(crate::queue::OperatorResume {
8675 question_id: "resume-question".into(),
8676 at: Timestamp::now(),
8677 conductor_rehold: None,
8678 forced: true,
8679 pinned_run: Some(run.id.clone()),
8680 });
8681 t.hold_machine(Some("not enough free space to start a run".into()));
8682 let mut unchanged = t.clone();
8683 unchanged
8684 .edit("title changed".into(), unchanged.instruction.clone())
8685 .unwrap();
8686 unchanged.release_operator(source, None);
8687 assert_eq!(
8688 unchanged
8689 .resume_override
8690 .as_ref()
8691 .unwrap()
8692 .pinned_run
8693 .as_deref(),
8694 Some(run.id.as_str())
8695 );
8696 assert!(!compatible_run_instruction(&run, &unchanged));
8697 assert!(may_resume_run(&run, &unchanged));
8698
8699 t.edit(
8700 "approved recovery".into(),
8701 "Reuse measured PR head B; fix Clippy; review".into(),
8702 )
8703 .unwrap();
8704 assert!(t.resume_override.is_none());
8705 t.release_operator(source, None);
8706 let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
8707 assert!(reloaded.resume_override.is_none());
8708 assert!(!may_resume_run(&run, &reloaded));
8709 let unfinished =
8710 unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
8711 .filter(|_| may_resume_run(&run, &reloaded));
8712 assert_eq!(
8713 choose_starter(None, false, unfinished.as_deref()),
8714 Starter::Start
8715 );
8716 assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
8717 assert_eq!(
8718 reloaded.resumption_history[0].question_id.as_deref(),
8719 Some("resume-question")
8720 );
8721
8722 unchanged.instruction = "Reuse measured PR head B".into();
8725 unchanged.hold_machine(Some("disk hold".into()));
8726 unchanged.release_operator(source, None);
8727 assert!(unchanged.resume_override.is_none());
8728 assert!(!may_resume_run(&run, &unchanged));
8729 }
8730 }
8731
8732 #[test]
8733 fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
8734 let mut t = task();
8735 let mut run = run_state(RunStatus::Blocked);
8736 t.review_of = Some("approved-head".into());
8737 t.instruction =
8738 "Review the branch `approved-head` (review-only: no implementation, no judging)."
8739 .into();
8740 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();
8741 run.reviewed_commits = Some(vec!["Commit log".into()]);
8742 t.start(run.id.clone());
8743 t.hold_machine(Some("interrupted review".into()));
8744 t.release_operator("cli", None);
8745 assert!(
8746 compatible_run_instruction(&run, &t),
8747 "legacy explicit review remains resumable"
8748 );
8749 let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
8750 .filter(|_| compatible_run_instruction(&run, &t));
8751 assert_eq!(
8752 choose_starter(None, false, unfinished.as_deref()),
8753 Starter::Resume(run.id.clone())
8754 );
8755 run.task_instruction = Some(t.instruction.clone());
8756 assert!(compatible_run_instruction(&run, &t));
8757 let reloaded: RunState =
8758 serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
8759 assert!(compatible_run_instruction(&reloaded, &t));
8760 t.edit(
8761 "new approved head".into(),
8762 "Reuse measured PR head B".into(),
8763 )
8764 .unwrap();
8765 assert!(!compatible_run_instruction(&run, &t));
8766
8767 t.review_of = None;
8769 t.instruction = "Fix Clippy on approved head".into();
8770 run.task_instruction = None;
8771 run.instruction = format!(
8772 "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
8773 t.instruction
8774 );
8775 assert!(compatible_run_instruction(&run, &t));
8776 t.instruction.push('\n');
8777 assert!(
8778 compatible_run_instruction(&run, &t),
8779 "legacy generated review trimmed the original criteria"
8780 );
8781 t.hold_for_handover(Some("approved-head".into()), "refused".into());
8782 assert_eq!(review_branch_for(&t, Some(&run)), Some("approved-head"));
8783 t.edit("new plan".into(), "Reuse measured PR head B".into())
8784 .unwrap();
8785 assert!(review_branch_for(&t, Some(&run)).is_none());
8786 assert!(!compatible_run_instruction(&run, &t));
8787 t.review_branch = Some("approved-head".into());
8788 t.review_instruction = None;
8789 assert!(
8790 review_branch_for(&t, Some(&run)).is_none(),
8791 "legacy retained candidate cannot replace a revised approved head"
8792 );
8793 }
8794
8795 #[test]
8796 fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
8797 let home = crate::run::test_home();
8798 crate::run::pin_test_home();
8799 let dir = tempfile::tempdir().unwrap();
8800 let queue = Queue::at(dir.path().join("queue"));
8801 for resume in [true, false] {
8802 let state = run_state(RunStatus::Blocked);
8803 let mut t = task();
8804 t.start(state.id.clone());
8805 let action = if resume {
8806 ask::ChoiceAction::Resume {
8807 run: state.id.clone(),
8808 }
8809 } else {
8810 ask::ChoiceAction::Requeue
8811 };
8812 let mut q = action_question(&state.id, action);
8813 q.status = ask::QuestionStatus::Open;
8814 q.answer = None;
8815 q.answered_at = None;
8816 t.fail("run stopped with a question", 3);
8817 hold_if_runnable(&queue, &mut t);
8818 assert!(t.operator_decided_at.is_none());
8819 assert!(t.operator_held());
8820 q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
8821 let expected = if resume {
8822 ActionDecision::Resume(state.id.clone())
8823 } else {
8824 ActionDecision::Requeue
8825 };
8826 assert_eq!(
8827 decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
8828 expected
8829 );
8830 t.hold_manual(Some("later explicit hold".into()));
8831 assert_eq!(
8832 decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
8833 ActionDecision::Stale
8834 );
8835 }
8836 }
8837
8838 #[test]
8839 fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
8840 let mut t = task();
8841 t.answers.push(crate::queue::AnsweredQuestion {
8842 question: "Inspect the remote?".into(),
8843 answer: "Inspect then wait".into(),
8844 });
8845 let old = instruction_for(&t);
8846 assert!(compatible_instruction(&old, &t));
8847 t.instruction = "Reuse approved PR head and review".into();
8848 t.release_operator("cli", None);
8849 assert!(!compatible_instruction(&old, &t));
8850 let approved = instruction_for(&t);
8851 assert!(approved.contains("waiting premises are superseded"));
8852 assert!(compatible_instruction(&approved, &t));
8853 assert_eq!(resumed_instruction(&approved, &t), approved);
8854 t.release_operator("web", None);
8855 assert!(compatible_instruction(&approved, &t));
8856 assert_eq!(t.resumption_history.len(), 1);
8857 t.start("run".into());
8858 assert!(instruction_for(&t).contains("Explicit operator resumption"));
8859 }
8860
8861 #[test]
8865 fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
8866 let mut state = RunState::new(
8867 PathBuf::from("/repo"),
8868 "main".into(),
8869 "base".into(),
8870 "task".into(),
8871 Config::default(),
8872 );
8873 state.status = RunStatus::Landing;
8874 state.parked = true;
8875 state.pr_pushed_head = Some("head".into());
8876 state.land_unrelated = Some(
8877 serde_json::from_value(serde_json::json!({
8878 "head": "head", "question": "ci-question",
8879 "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
8880 }))
8881 .unwrap(),
8882 );
8883 let mut t = task();
8884 t.start(state.id.clone());
8885 let verdict = Verdict {
8886 status: RunStatus::Landing,
8887 left_pr: true,
8888 quota_hit: false,
8889 parked: true,
8890 no_viable_candidates: false,
8891 };
8892 settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
8893 assert_eq!(t.attempts, 0);
8894 assert_eq!(t.status, TaskStatus::Held);
8895 assert!(!t.operator_held());
8896 assert!(
8897 t.hold_reason
8898 .as_deref()
8899 .unwrap()
8900 .starts_with("[ci-unrelated]")
8901 );
8902 t.attempts = 1;
8904 settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
8905 assert_eq!(t.attempts, 1);
8906 assert_eq!(t.passes.len(), 1);
8907 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
8908 state.pr_pushed_head = Some("new-head".into());
8909 state.parked = false;
8910 state.status = RunStatus::Blocked;
8911 let stale = Verdict {
8912 status: RunStatus::Blocked,
8913 parked: false,
8914 ..verdict
8915 };
8916 settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
8917 assert_eq!(t.attempts, 1);
8918 state.begin_pass();
8920 state.begin_pass();
8921 state.status = RunStatus::Landing;
8922 state.parked = true;
8923 state.pr_pushed_head = Some("head".into());
8924 settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
8925 assert_eq!(t.attempts, 0);
8926 assert_eq!(t.passes.len(), 2);
8927 }
8928
8929 #[test]
8930 fn orphan_recovery_does_not_refund_a_previous_pass_loss() {
8931 let mut state = run_state(RunStatus::Failed);
8932 state
8933 .quota
8934 .push(loss("advisor-1", "2026-10-22T14:38:00Z", None));
8935 state.begin_pass();
8936 let mut t = task();
8937 t.start(state.id.clone());
8938 reclaim(&mut t, Some(state), 2, "en");
8939 assert_eq!(t.attempts, 1);
8940 }
8941
8942 #[test]
8943 fn an_all_seats_unauthenticated_node_refunds_and_holds_without_retry() {
8944 let mut state = run_state(RunStatus::Blocked);
8945 let losses: Vec<_> = ["alpha", "beta"]
8946 .into_iter()
8947 .enumerate()
8948 .map(|(i, agent)| {
8949 QuotaLoss::from_report(
8950 format!("advisor-{i}"),
8951 "advise",
8952 Some(&crate::agent::Quota {
8953 cause: crate::agent::QuotaCause::Authentication,
8954 agent: agent.to_owned(),
8955 reset: None,
8956 }),
8957 )
8958 })
8959 .collect();
8960 crate::graph::block_machine_outage(&mut state, "advise", &losses);
8961 state.quota = losses;
8962 let mut t = task();
8963 t.start(state.id.clone());
8964 let verdict = Verdict {
8965 status: state.status,
8966 left_pr: false,
8967 quota_hit: true,
8968 parked: false,
8969 no_viable_candidates: true,
8970 };
8971 settle_and_diagnose(&mut t, verdict, "authentication unavailable", 2, &state);
8972 assert_eq!(t.attempts, 0);
8973 assert_eq!(t.status, TaskStatus::Held);
8974 assert!(!t.operator_held());
8975 let reason = t.hold_reason.as_deref().unwrap();
8976 assert!(reason.starts_with("[authentication]"));
8977 assert!(
8978 reason.contains("alpha")
8979 && reason.contains("beta")
8980 && reason.contains("re-authenticate")
8981 );
8982 assert!(cooldown_until(&state.quota, Timestamp::now()).is_none());
8983 let mut orphan = task();
8985 orphan.start(state.id.clone());
8986 reclaim(&mut orphan, Some(state), 2, "en");
8987 assert_eq!(orphan.attempts, 0);
8988 assert_eq!(orphan.status, TaskStatus::Held);
8989 }
8990
8991 #[test]
8992 fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
8993 let mut state = RunState::new(
8994 PathBuf::from("/repo"),
8995 "main".to_owned(),
8996 "abc1234".to_owned(),
8997 "task".to_owned(),
8998 Config::default(),
8999 );
9000 state.status = RunStatus::Blocked;
9001 state.resource_block = Some(crate::run::ResourceBlock {
9002 cause: crate::run::ResourceBlockCause::Other,
9003 node: "graft".to_owned(),
9004 kind: "shared build cache".to_owned(),
9005 detail: "timed out".to_owned(),
9006 at: jiff::Timestamp::now(),
9007 });
9008 let mut t = task();
9009 t.start("20260902-000000-aaaa".to_owned());
9010 assert_eq!(t.attempts, 1);
9011 let verdict = Verdict {
9012 status: RunStatus::Blocked,
9013 left_pr: false,
9014 quota_hit: false,
9015 parked: false,
9016 no_viable_candidates: false,
9017 };
9018 settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
9019 assert_eq!(t.status, TaskStatus::Held);
9020 assert_eq!(t.attempts, 0, "the attempt is refunded");
9021 assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
9022 assert!(
9023 !t.operator_held(),
9024 "a machine hold, released without a human"
9025 );
9026
9027 let mut selected = task();
9028 selected.start("20260902-000000-cccc".into());
9029 selected.replacement = Some(crate::merge_decision::Replacement {
9030 question: "fixture".into(),
9031 run: "earlier".into(),
9032 pr: "https://example.invalid/pr/1".into(),
9033 agent: "selected".into(),
9034 context: "fixture".into(),
9035 });
9036 state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
9037 settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
9038 assert_eq!(selected.attempts, 0);
9039 assert!(
9040 !selected.operator_held(),
9041 "a selected agent also retains a machine resource hold"
9042 );
9043 assert!(
9044 selected
9045 .hold_reason
9046 .as_deref()
9047 .unwrap()
9048 .starts_with("[resource] ")
9049 );
9050
9051 let mut p = task();
9053 p.start("20260902-000000-bbbb".to_owned());
9054 settle_and_diagnose(
9055 &mut p,
9056 Verdict {
9057 parked: true,
9058 ..verdict
9059 },
9060 "parked",
9061 2,
9062 &state,
9063 );
9064 assert_eq!(p.status, TaskStatus::Parked);
9065 assert_eq!(
9066 p.attempts, 0,
9067 "parking refunds once rather than also settling the resource hold"
9068 );
9069 }
9070
9071 #[test]
9072 fn record_failure_notice_links_the_task() {
9073 let dir = tempfile::tempdir().unwrap();
9074 std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
9077 let queue = Queue::at(dir.path().join("queue"));
9078 let mut t = interrupt_task("rec-fail-1");
9079 record(&queue, &mut t);
9080
9081 let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
9082 assert_eq!(found.len(), 1);
9083 assert_eq!(found[0].key, "loop:record");
9084 assert_eq!(
9085 found[0].link,
9086 Some(Link::Task {
9087 id: "rec-fail-1".to_owned()
9088 })
9089 );
9090 }
9091
9092 fn interrupt_task(id: &str) -> Task {
9095 let mut t = task();
9096 t.id = id.to_owned();
9097 t.interrupt = true;
9098 t
9099 }
9100
9101 fn task_with_id(id: &str) -> Task {
9103 let mut t = task();
9104 t.id = id.to_owned();
9105 t
9106 }
9107
9108 fn urgent_task(id: &str) -> Task {
9110 let mut t = task();
9111 t.id = id.to_owned();
9112 t.urgent = true;
9113 t
9114 }
9115
9116 #[test]
9117 fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
9118 let dir = tempfile::tempdir().unwrap();
9119 let queue = Queue::at(dir.path().join("queue"));
9120 let mut parked = task_with_id("parked");
9121 parked.start("run".into());
9122 parked.park("upgrade");
9123 parked.record_pass_at(
9124 "run",
9125 0,
9126 Some(Timestamp::now()),
9127 1,
9128 Some(crate::run::ParkCause::Upgrade {
9129 from: "old".into(),
9130 to: None,
9131 }),
9132 );
9133 let mut fresh = task_with_id("fresh");
9134 fresh.priority = 100;
9135 let mut urgent_task = urgent_task("urgent");
9136 for t in [&mut parked, &mut fresh, &mut urgent_task] {
9137 queue.put(t).unwrap();
9138 }
9139 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
9140 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
9141 let candidates = runnable(&queue);
9142 assert_eq!(candidates[0].id, parked.id);
9143 let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
9144 assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_err());
9145 assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_ok());
9146 drop(first);
9147 let claimed_elsewhere = queue.claim(&parked.id).unwrap();
9148 let next = runnable(&queue)
9149 .into_iter()
9150 .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent).ok())
9151 .unwrap();
9152 assert_eq!(next.task.id, fresh.id);
9153 assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
9154 drop(claimed_elsewhere);
9155 drop(next);
9156 assert!(matches!(
9157 claim_dispatch(&queue, &parked, true, &ordinary, &urgent),
9158 Err(SkipReason::CoolingDown)
9159 ));
9160 }
9161
9162 #[test]
9163 fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
9164 let dir = tempfile::tempdir().unwrap();
9165 let queue = Queue::at(dir.path().join("queue"));
9166 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
9167 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
9168 let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
9169 let mut first = task();
9170 queue.put(&mut first).unwrap();
9171 let stale_plain = queue.get(&first.id).unwrap();
9172 first.set_urgent(true).unwrap();
9173 queue.put(&mut first).unwrap();
9174 let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
9175 let mut second = urgent_task("second");
9176 queue.put(&mut second).unwrap();
9177 assert!(matches!(
9178 claim_dispatch(&queue, &second, false, &ordinary, &urgent),
9179 Err(SkipReason::UrgentCapacity)
9180 ));
9181 drop(queue.claim(&second.id).unwrap());
9182 assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
9183 drop(dispatched);
9184 let stale_urgent = queue.get(&first.id).unwrap();
9185 first.set_urgent(false).unwrap();
9186 queue.put(&mut first).unwrap();
9187 assert!(matches!(
9188 claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent),
9189 Err(SkipReason::OrdinaryCapacity)
9190 ));
9191 assert_eq!(urgent.available_permits(), 1);
9192 drop(queue.claim(&first.id).unwrap());
9193 drop(occupied);
9194 }
9195
9196 #[test]
9197 fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
9198 let dir = tempfile::tempdir().unwrap();
9199 let queue = Queue::at(dir.path().join("queue"));
9200 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
9201 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
9202 let mut t = task();
9203 queue.put(&mut t).unwrap();
9204 for enabled in [true, false] {
9205 let stale = queue.get(&t.id).unwrap();
9206 t.set_urgent(enabled).unwrap();
9207 queue.put(&mut t).unwrap();
9208 assert_ne!(stale.urgent, enabled);
9209 let DispatchClaim {
9210 task: fresh,
9211 claim,
9212 lane,
9213 permit,
9214 } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
9215 assert_eq!(fresh.urgent, enabled);
9216 assert_eq!(
9217 lane,
9218 if enabled {
9219 PermitKind::Urgent
9220 } else {
9221 PermitKind::Ordinary
9222 }
9223 );
9224 assert_eq!(ordinary.available_permits(), usize::from(enabled));
9225 assert_eq!(urgent.available_permits(), usize::from(!enabled));
9226 assert!(queue.claim(&t.id).is_err());
9227 assert_eq!(fresh.attempts, stale.attempts);
9228 drop((claim, permit));
9229 assert_eq!(ordinary.available_permits(), 1);
9230 assert_eq!(urgent.available_permits(), 1);
9231 }
9232 t.set_urgent(true).unwrap();
9233 queue.put(&mut t).unwrap();
9234 let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
9235 assert!(matches!(
9236 claim_dispatch(&queue, &t, false, &ordinary, &urgent),
9237 Err(SkipReason::UrgentCapacity)
9238 ));
9239 assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
9240 drop(queue.claim(&t.id).unwrap());
9241 assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
9242 drop(occupied);
9243 assert!(matches!(
9244 claim_dispatch(&queue, &t, true, &ordinary, &urgent),
9245 Err(SkipReason::CoolingDown)
9246 ));
9247 drop(queue.claim(&t.id).unwrap());
9248 let held = queue.claim(&t.id).unwrap();
9249 assert!(matches!(
9250 claim_dispatch(&queue, &t, false, &ordinary, &urgent),
9251 Err(SkipReason::ClaimUnavailable)
9252 ));
9253 drop(held);
9254 t.status = TaskStatus::Held;
9255 queue.put(&mut t).unwrap();
9256 assert!(matches!(
9257 claim_dispatch(&queue, &t, false, &ordinary, &urgent),
9258 Err(SkipReason::NoLongerRunnable)
9259 ));
9260 drop(queue.claim(&t.id).unwrap());
9261 std::fs::remove_file(queue.path_of(&t.id)).unwrap();
9262 assert!(matches!(
9263 claim_dispatch(&queue, &t, false, &ordinary, &urgent),
9264 Err(SkipReason::RereadFailed)
9265 ));
9266 drop(queue.claim(&t.id).unwrap());
9267 assert_eq!(urgent.available_permits(), 1);
9268 }
9269
9270 #[test]
9275 fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
9276 assert_eq!(permit_kind(true, false, false), PermitKind::None);
9277 assert_eq!(permit_kind(true, false, true), PermitKind::None);
9278 assert_eq!(permit_kind(true, true, false), PermitKind::None);
9279 assert_eq!(permit_kind(true, true, true), PermitKind::None);
9280 }
9281
9282 #[test]
9287 fn permit_kind_separates_urgent_from_ordinary() {
9288 assert_eq!(permit_kind(false, false, true), PermitKind::Urgent);
9289 assert_eq!(permit_kind(false, false, false), PermitKind::Ordinary);
9290 assert_eq!(permit_kind(false, true, false), PermitKind::Immediate);
9291 assert_eq!(permit_kind(false, true, true), PermitKind::Immediate);
9292 }
9293
9294 #[test]
9295 fn immediate_lane_does_not_consume_ordinary_or_urgent_slots() {
9296 let request = |task: &str, lane, standalone| TaskWorker {
9297 opts: Opts::default(),
9298 queue: PathBuf::from("/queue"),
9299 task: task.to_owned(),
9300 lane,
9301 standalone,
9302 };
9303 let jobs = vec![
9304 request("ordinary", PermitKind::Ordinary, false),
9305 request("urgent", PermitKind::Urgent, false),
9306 request("immediate-1", PermitKind::Immediate, false),
9307 request("immediate-2", PermitKind::Immediate, false),
9308 request("decision", PermitKind::None, false),
9309 ];
9310 assert_eq!(available_slots(&jobs, 1), (0, 0));
9311 assert_eq!(available_slots(&jobs, 2), (1, 0));
9312 let immediate_only = vec![
9313 request("immediate-1", PermitKind::Immediate, false),
9314 request("immediate-2", PermitKind::Immediate, false),
9315 ];
9316 assert_eq!(available_slots(&immediate_only, 1), (1, 1));
9317 }
9318
9319 #[test]
9320 fn immediate_dispatch_bypasses_saturated_lanes_and_preserves_non_concurrency_gates() {
9321 let dir = tempfile::tempdir().unwrap();
9322 let queue = Queue::at(dir.path().join("queue"));
9323 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
9324 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
9325 let _ord_permit = Arc::clone(&ordinary).try_acquire_owned().unwrap();
9326 let _urg_permit = Arc::clone(&urgent).try_acquire_owned().unwrap();
9327
9328 let mut imm1 = task_with_id("imm-1");
9330 imm1.immediate = true;
9331 let mut imm2 = task_with_id("imm-2");
9332 imm2.immediate = true;
9333 imm2.urgent = true;
9334 queue.put(&mut imm1).unwrap();
9335 queue.put(&mut imm2).unwrap();
9336
9337 let mut stale = imm1.clone();
9339 stale.immediate = false;
9340 let claim1 = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
9341 assert_eq!(claim1.lane, PermitKind::Immediate);
9342 assert!(claim1.permit.is_none());
9343
9344 let claim2 = claim_dispatch(&queue, &imm2, false, &ordinary, &urgent).unwrap();
9346 assert_eq!(claim2.lane, PermitKind::Immediate);
9347 assert!(claim2.permit.is_none());
9348 assert_eq!(ordinary.available_permits(), 0);
9349 assert_eq!(urgent.available_permits(), 0);
9350
9351 assert_eq!(
9353 claim_dispatch(&queue, &imm1, false, &ordinary, &urgent).err(),
9354 Some(SkipReason::ClaimUnavailable)
9355 );
9356 drop((claim1, claim2));
9357
9358 assert_eq!(
9360 claim_dispatch(&queue, &imm1, true, &ordinary, &urgent).err(),
9361 Some(SkipReason::CoolingDown)
9362 );
9363
9364 imm2.set_immediate(false).unwrap();
9366 queue.put(&mut imm2).unwrap();
9367 assert_eq!(
9368 claim_dispatch(&queue, &imm2, false, &ordinary, &urgent).err(),
9369 Some(SkipReason::UrgentCapacity)
9370 );
9371
9372 let interrupt = Interrupt::Parking {
9374 parked: vec!["in-flight".into()],
9375 interrupt_task: "other".into(),
9376 };
9377 assert!(
9378 interrupt_gate(&interrupt, &["in-flight".into()], vec![imm1.clone()]).is_empty(),
9379 "an active interrupt sequence must withhold immediate tasks too"
9380 );
9381 }
9382
9383 #[test]
9384 fn admission_snapshot_distinguishes_mode_lane_blockers_and_unknown_state() {
9385 let dir = tempfile::tempdir().unwrap();
9386 let home = dir.path();
9387 let queue = Queue::at(home.join("queue"));
9388 let now = Timestamp::now();
9389
9390 let mut imm = task_with_id("imm-ready");
9391 imm.immediate = true;
9392 queue.put(&mut imm).unwrap();
9393
9394 let snap = AdmissionSnapshot::capture(home, now);
9396 let adm = snap.evaluate(&imm, &queue, None, home);
9397 assert_eq!(adm.mode, "immediate");
9398 assert_eq!(adm.state, "waiting");
9399 assert_eq!(adm.label, "Immediate: waiting — scheduler not running");
9400
9401 let mut status = Status::new();
9403 status.updated_at = now;
9404 status
9405 .dispatch_skips
9406 .insert(imm.id.clone(), SkipReason::UrgentCapacity.key().to_owned());
9407 write_status_to(&home.join("daemon.json"), &status).unwrap();
9408
9409 let mut ord = task_with_id("ord-running");
9410 ord.status = TaskStatus::Running;
9411 queue.put(&mut ord).unwrap();
9412 let ord_req = TaskWorker {
9413 opts: Opts::default(),
9414 queue: queue.root().to_path_buf(),
9415 task: ord.id.clone(),
9416 lane: PermitKind::Ordinary,
9417 standalone: false,
9418 };
9419 let (_ord_job, _ord_lease) = crate::worker::running_fixture(
9420 home,
9421 &format!("task:{}", ord.id),
9422 serde_json::to_value(&ord_req).unwrap(),
9423 )
9424 .unwrap();
9425
9426 let mut urg = task_with_id("urg-running");
9427 urg.urgent = true;
9428 urg.status = TaskStatus::Running;
9429 queue.put(&mut urg).unwrap();
9430 let urg_req = TaskWorker {
9431 opts: Opts::default(),
9432 queue: queue.root().to_path_buf(),
9433 task: urg.id.clone(),
9434 lane: PermitKind::Urgent,
9435 standalone: false,
9436 };
9437 let (_urg_job, _urg_lease) = crate::worker::running_fixture(
9438 home,
9439 &format!("task:{}", urg.id),
9440 serde_json::to_value(&urg_req).unwrap(),
9441 )
9442 .unwrap();
9443
9444 let snap = AdmissionSnapshot::capture(home, now);
9445 let adm = snap.evaluate(&imm, &queue, None, home);
9446 assert_eq!(adm.state, "next_poll");
9447 assert_eq!(adm.label, "Immediate: next poll");
9448 assert_eq!(adm.reservation_lane, None);
9449
9450 let ord_adm = snap.evaluate(&ord, &queue, None, home);
9452 assert_eq!(ord_adm.state, "running");
9453 assert_eq!(ord_adm.reservation_lane, Some("ordinary"));
9454 assert_eq!(ord_adm.label, "Running (ordinary lane)");
9455
9456 let mut held = task_with_id("imm-held");
9458 held.immediate = true;
9459 held.hold_manual(Some("awaiting signoff".into()));
9460 queue.put(&mut held).unwrap();
9461 let held_adm = snap.evaluate(&held, &queue, None, home);
9462 assert_eq!(held_adm.state, "waiting");
9463 assert_eq!(
9464 held_adm.label,
9465 "Immediate: waiting — held (awaiting signoff)"
9466 );
9467
9468 let mut disk_held = task_with_id("imm-disk");
9469 disk_held.immediate = true;
9470 disk_held.hold_machine(Some("only 1 GiB free".into()));
9471 disk_held.mark_startup_disk_capacity();
9472 queue.put(&mut disk_held).unwrap();
9473 let disk_adm = snap.evaluate(&disk_held, &queue, None, home);
9474 assert_eq!(disk_adm.state, "waiting");
9475 assert!(disk_adm.label.contains("disk admission"), "{disk_adm:?}");
9476
9477 let mut blocked = task_with_id("imm-blocked");
9478 blocked.immediate = true;
9479 blocked.block(vec![held.id.clone()], Some("needs held task".into()));
9480 queue.put(&mut blocked).unwrap();
9481 let questions = Questions::at(home.join("questions"));
9482 let inv = crate::blockers::Inventory::load(&queue, &questions);
9483 let blocked_adm = snap.evaluate(&blocked, &queue, Some(&inv), home);
9484 assert_eq!(blocked_adm.state, "waiting");
9485 assert!(
9486 blocked_adm
9487 .label
9488 .starts_with("Immediate: waiting — waiting on dependencies"),
9489 "{blocked_adm:?}"
9490 );
9491
9492 let _claim = queue.claim(&imm.id).unwrap();
9494 let claimed_adm = snap.evaluate(&imm, &queue, None, home);
9495 assert_eq!(claimed_adm.state, "waiting");
9496 assert_eq!(
9497 claimed_adm.label,
9498 "Immediate: waiting — claimed by another process"
9499 );
9500 drop(_claim);
9501
9502 let until = now + jiff::SignedDuration::from_secs(120);
9504 std::fs::write(
9505 home.join("task-quota-cooldown.json"),
9506 serde_json::to_vec(&until).unwrap(),
9507 )
9508 .unwrap();
9509 let cool_snap = AdmissionSnapshot::capture(home, now);
9510 let cool_adm = cool_snap.evaluate(&imm, &queue, None, home);
9511 assert_eq!(cool_adm.state, "waiting");
9512 assert!(cool_adm.label.contains("quota cooldown"), "{cool_adm:?}");
9513 std::fs::remove_file(home.join("task-quota-cooldown.json")).unwrap();
9514
9515 std::fs::write(home.join("scheduler-interrupt.json"), "{broken").unwrap();
9517 let bad_snap = AdmissionSnapshot::capture(home, now);
9518 let bad_adm = bad_snap.evaluate(&imm, &queue, None, home);
9519 assert_eq!(bad_adm.state, "unknown");
9520 assert_ne!(bad_adm.label, "Immediate: next poll");
9521 }
9522
9523 #[test]
9530 fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
9531 let cfg = Config::default();
9532 let repo = Path::new("/any/repo/path");
9533
9534 let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(1024))
9535 .expect("must hold below the threshold");
9536 assert!(reason.contains("1024"), "{reason}");
9537 assert!(
9538 reason.contains(&cfg.disk.min_free_bytes.to_string()),
9539 "{reason}"
9540 );
9541
9542 assert_eq!(
9543 disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(cfg.disk.min_free_bytes)),
9544 None,
9545 "exactly at the floor is open"
9546 );
9547 assert_eq!(
9548 disk_gate_with(
9549 repo,
9550 &cfg,
9551 PathBuf::new,
9552 |_| Ok(cfg.disk.min_free_bytes + 1)
9553 ),
9554 None,
9555 "comfortably above the floor is open"
9556 );
9557 }
9558
9559 #[test]
9563 fn disk_gate_ignores_the_collection_threshold() {
9564 let mut cfg = Config::default();
9565 cfg.disk.reclaim_free_bytes = Some(cfg.disk.min_free_bytes * 100);
9566 let repo = Path::new("/any/repo/path");
9567 assert_eq!(
9568 disk_gate_with(
9569 repo,
9570 &cfg,
9571 PathBuf::new,
9572 |_| Ok(cfg.disk.min_free_bytes + 1)
9573 ),
9574 None
9575 );
9576 assert!(
9577 disk_gate_with(
9578 repo,
9579 &cfg,
9580 PathBuf::new,
9581 |_| Ok(cfg.disk.min_free_bytes - 1)
9582 )
9583 .is_some(),
9584 "below the admission floor still holds"
9585 );
9586 }
9587
9588 #[test]
9589 fn disk_gate_with_checks_cache_and_worktree_volumes_and_measurement_errors() {
9590 let dir = tempfile::tempdir().unwrap();
9591 let repo = dir.path().join("repo");
9592 let cache = dir.path().join("cache");
9593 let worktrees = dir.path().join("worktrees");
9594 for path in [&repo, &cache, &worktrees] {
9595 std::fs::create_dir(path).unwrap();
9596 }
9597 let mut cfg = Config::default();
9598 cfg.graph.worktree_root = Some(worktrees.clone());
9599 cfg.verify.gate = vec![format!(
9600 "CARGO_TARGET_DIR='{}' cargo build",
9601 cache.display()
9602 )];
9603 for blocked in [&cache, &worktrees] {
9604 for unmeasured in [false, true] {
9605 assert!(
9606 disk_gate_with(&repo, &cfg, PathBuf::new, |path| {
9607 if path == blocked {
9608 if unmeasured {
9609 Err(anyhow::anyhow!("measurement failed"))
9610 } else {
9611 Ok(0)
9612 }
9613 } else {
9614 Ok(u64::MAX)
9615 }
9616 })
9617 .is_some(),
9618 "a blocked secondary output volume must close admission"
9619 );
9620 }
9621 }
9622 assert!(disk_gate_with(&repo, &cfg, PathBuf::new, |_| Ok(u64::MAX)).is_none());
9623 }
9624
9625 #[test]
9626 fn isolated_admission_measures_the_run_home_instead_of_the_shared_cache() {
9627 let dir = tempfile::tempdir().unwrap();
9628 let repo = dir.path().join("repo");
9629 let cache = dir.path().join("cache");
9630 let home_parent = dir.path().join("run-volume");
9631 let home = home_parent.join("new-home");
9632 for path in [&repo, &cache, &home_parent] {
9633 std::fs::create_dir(path).unwrap();
9634 }
9635 let mut cfg = Config::default();
9636 cfg.graph.worktree_root = Some(repo.clone());
9637 cfg.verify.gate = vec![format!(
9638 "CARGO_TARGET_DIR='{}' cargo build",
9639 cache.display()
9640 )];
9641 cfg.verify.build_cache = BuildCache::Isolated;
9642 let denied = |blocked: &Path| {
9643 disk_gate_with(
9644 &repo,
9645 &cfg,
9646 || home.clone(),
9647 |path| Ok(if path == blocked { 0 } else { u64::MAX }),
9648 )
9649 .is_some()
9650 };
9651 assert!(!denied(&cache));
9652 assert!(denied(&home_parent));
9653 }
9654
9655 #[test]
9656 fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
9657 let mut cfg = Config::default();
9658 cfg.disk.min_free_bytes = 0;
9659 let repo = Path::new("/any/repo/path");
9660 assert_eq!(
9661 disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(0)),
9662 None,
9663 "a zero floor never measures at all"
9664 );
9665 }
9666
9667 #[test]
9668 fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
9669 let cfg = Config::default();
9670 let repo = Path::new("/any/repo/path");
9671 let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| {
9672 Err(anyhow::anyhow!("no df on this box"))
9673 })
9674 .expect("a measurement failure must close the gate, not open it");
9675 assert!(reason.contains("could not measure"), "{reason}");
9676 }
9677
9678 #[test]
9679 fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
9680 let ordinary = task();
9681 let next = advance_interrupt(
9682 Interrupt::Idle,
9683 std::slice::from_ref(&ordinary.id),
9684 std::slice::from_ref(&ordinary),
9685 );
9686 assert_eq!(next, Interrupt::Idle);
9687 }
9688
9689 #[test]
9690 fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
9691 let marked = interrupt_task("marked");
9694 let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
9695 assert_eq!(next, Interrupt::Idle);
9696 }
9697
9698 #[test]
9699 fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
9700 let marked = interrupt_task("marked");
9701 let next = advance_interrupt(
9702 Interrupt::Idle,
9703 &["running".to_owned()],
9704 std::slice::from_ref(&marked),
9705 );
9706 assert_eq!(
9707 next,
9708 Interrupt::Parking {
9709 parked: vec!["running".to_owned()],
9710 interrupt_task: "marked".to_owned(),
9711 }
9712 );
9713 }
9714
9715 #[test]
9724 fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
9725 let marked = interrupt_task("marked");
9726
9727 let two = advance_interrupt(
9728 Interrupt::Idle,
9729 &["a".to_owned(), "b".to_owned()],
9730 std::slice::from_ref(&marked),
9731 );
9732 assert_eq!(two, Interrupt::Idle);
9733
9734 let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
9735 assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
9736 }
9737
9738 #[test]
9739 fn parking_holds_until_every_parked_id_has_actually_left_flight() {
9740 let state = Interrupt::Parking {
9741 parked: vec!["running".to_owned()],
9742 interrupt_task: "marked".to_owned(),
9743 };
9744 let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
9746 assert_eq!(still_going, state);
9747
9748 let stopped_but_not_yet_dispatched =
9752 advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
9753 assert_eq!(stopped_but_not_yet_dispatched, state);
9754
9755 let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
9757 assert_eq!(
9758 dispatched,
9759 Interrupt::Running {
9760 parked: vec!["running".to_owned()],
9761 interrupt_task: "marked".to_owned(),
9762 }
9763 );
9764 }
9765
9766 #[test]
9767 fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
9768 let state = Interrupt::Running {
9769 parked: vec!["running".to_owned()],
9770 interrupt_task: "marked".to_owned(),
9771 };
9772 let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
9773 assert_eq!(still_running, state);
9774
9775 let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
9782 assert_eq!(
9783 ended,
9784 Interrupt::Resuming {
9785 parked: vec!["running".to_owned()]
9786 }
9787 );
9788 }
9789
9790 #[test]
9791 fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
9792 let state = Interrupt::Resuming {
9793 parked: vec!["running".to_owned()],
9794 };
9795 let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
9796 assert_eq!(still_waiting, state);
9797
9798 let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
9799 assert_eq!(dispatched, Interrupt::Idle);
9800 }
9801
9802 #[test]
9808 fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
9809 {
9810 let state = Interrupt::Parking {
9811 parked: vec!["running".to_owned()],
9812 interrupt_task: "marked".to_owned(),
9813 };
9814 let next = advance_interrupt(state, &[], &[]);
9817 assert_eq!(
9818 next,
9819 Interrupt::Resuming {
9820 parked: vec!["running".to_owned()]
9821 },
9822 "abandoning the interrupt must not abandon the resume it owes"
9823 );
9824 }
9825
9826 #[test]
9829 fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
9830 let state = Interrupt::Resuming {
9831 parked: vec!["running".to_owned()],
9832 };
9833 let next = advance_interrupt(state, &[], &[]);
9834 assert_eq!(
9835 next,
9836 Interrupt::Idle,
9837 "nothing is left to wait for; the loop must not stay wedged"
9838 );
9839 }
9840
9841 #[test]
9842 fn disabled_by_config_the_sequence_can_never_leave_idle() {
9843 let marked = interrupt_task("marked");
9844 let next = advance_interrupt_tick(
9845 false,
9846 Interrupt::Idle,
9847 &["running".to_owned()],
9848 std::slice::from_ref(&marked),
9849 );
9850 assert_eq!(
9851 next,
9852 Interrupt::Idle,
9853 "an unmarked, unconfigured daemon must behave exactly as before"
9854 );
9855 }
9856
9857 #[test]
9858 fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
9859 let state = Interrupt::Parking {
9860 parked: vec!["running".to_owned()],
9861 interrupt_task: "marked".to_owned(),
9862 };
9863 let candidates = vec![interrupt_task("marked"), task()];
9864 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
9865 assert!(
9866 allowed.is_empty(),
9867 "nothing may dispatch - not even the interrupt task itself - \
9868 until the parked run has actually stopped"
9869 );
9870 }
9871
9872 #[test]
9886 fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
9887 for state in [
9888 Interrupt::Parking {
9889 parked: vec!["running".to_owned()],
9890 interrupt_task: "marked".to_owned(),
9891 },
9892 Interrupt::Running {
9893 parked: vec!["running".to_owned()],
9894 interrupt_task: "marked".to_owned(),
9895 },
9896 Interrupt::Resuming {
9897 parked: vec!["running".to_owned()],
9898 },
9899 ] {
9900 let candidates = vec![
9901 interrupt_task("marked"),
9902 urgent_task("hot"),
9903 task_with_id("ordinary"),
9904 ];
9905 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
9906 assert!(
9907 !allowed.iter().any(|t| t.id == "hot"),
9908 "an urgent candidate must wait out the same gate as anything \
9909 else while the run it would run alongside has not actually \
9910 left flight, for state {state:?}: {allowed:?}"
9911 );
9912 }
9913 }
9914
9915 #[test]
9921 fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
9922 let state = Interrupt::Resuming {
9923 parked: vec!["hot".to_owned()],
9924 };
9925 let candidates = vec![urgent_task("hot"), task()];
9926 let allowed = interrupt_gate(&state, &[], candidates);
9927 assert_eq!(
9928 allowed.iter().filter(|t| t.id == "hot").count(),
9929 1,
9930 "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
9931 );
9932 }
9933
9934 #[test]
9935 fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
9936 let state = Interrupt::Parking {
9937 parked: vec!["running".to_owned()],
9938 interrupt_task: "marked".to_owned(),
9939 };
9940 let other = task();
9941 let candidates = vec![interrupt_task("marked"), other.clone()];
9942 let allowed = interrupt_gate(&state, &[], candidates);
9943 assert_eq!(allowed.len(), 1);
9944 assert_eq!(allowed[0].id, "marked");
9945 }
9946
9947 #[test]
9948 fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
9949 let state = Interrupt::Running {
9950 parked: vec!["running".to_owned()],
9951 interrupt_task: "marked".to_owned(),
9952 };
9953 let candidates = vec![task(), task()];
9954 let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
9955 assert!(allowed.is_empty());
9956 }
9957
9958 #[test]
9965 fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
9966 let state = Interrupt::Resuming {
9967 parked: vec!["a".to_owned(), "c".to_owned()],
9968 };
9969 let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
9970 let allowed = interrupt_gate(&state, &[], candidates);
9971 assert_eq!(
9972 allowed.len(),
9973 1,
9974 "at most one candidate may be offered while resuming: {allowed:?}"
9975 );
9976 assert_eq!(allowed[0].id, "a");
9977 }
9978
9979 #[test]
9980 fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
9981 let state = Interrupt::Resuming {
9982 parked: vec!["a".to_owned()],
9983 };
9984 let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
9985 assert!(allowed.is_empty());
9986 }
9987
9988 #[test]
9994 fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
9995 let running = task(); let marked = interrupt_task("marked");
9997
9998 let mut state = Interrupt::Idle;
9999 let in_flight = vec![running.id.clone()];
10001 state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
10002 let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
10003 assert!(gated.is_empty(), "still waiting on `running` to park");
10004
10005 state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
10007 let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
10008 assert_eq!(
10009 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
10010 vec!["marked"],
10011 "only the interrupt task may be offered to the dispatcher now"
10012 );
10013
10014 state = advance_interrupt_tick(
10016 true,
10017 state,
10018 &["marked".to_owned()],
10019 std::slice::from_ref(&running),
10020 );
10021 let gated = interrupt_gate(
10022 &state,
10023 &["marked".to_owned()],
10024 vec![marked.clone(), running.clone()],
10025 );
10026 assert!(
10027 gated.is_empty(),
10028 "the parked run must not be offered back while the interrupt \
10029 task is still running"
10030 );
10031
10032 let other = task_with_id("other");
10036 state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
10037 assert_eq!(
10038 state,
10039 Interrupt::Resuming {
10040 parked: vec![running.id.clone()]
10041 }
10042 );
10043 let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
10044 assert_eq!(
10045 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
10046 vec![running.id.as_str()],
10047 "exactly the parked run resumes - not the unrelated task, even \
10048 though it was offered first"
10049 );
10050
10051 state = advance_interrupt_tick(
10055 true,
10056 state,
10057 std::slice::from_ref(&running.id),
10058 std::slice::from_ref(&other),
10059 );
10060 assert_eq!(state, Interrupt::Idle);
10061 let gated = interrupt_gate(
10062 &state,
10063 std::slice::from_ref(&running.id),
10064 vec![other.clone()],
10065 );
10066 assert_eq!(
10067 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
10068 vec![other.id.as_str()],
10069 "ordinary dispatch is unrestricted again"
10070 );
10071 }
10072
10073 #[test]
10074 fn every_run_status_settles_the_task_it_came_from() {
10075 let table = [
10077 (RunStatus::Merged, TaskStatus::Done, 1),
10078 (RunStatus::Ready, TaskStatus::Done, 1),
10079 (RunStatus::Stalled, TaskStatus::Failed, 0),
10080 (RunStatus::Blocked, TaskStatus::Failed, 1),
10081 (RunStatus::Failed, TaskStatus::Failed, 1),
10082 (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
10083 (RunStatus::Prep, TaskStatus::Failed, 1),
10084 (RunStatus::Implementing, TaskStatus::Failed, 1),
10085 (RunStatus::Judging, TaskStatus::Failed, 1),
10086 (RunStatus::Deliberating, TaskStatus::Failed, 1),
10087 (RunStatus::Voting, TaskStatus::Failed, 1),
10088 (RunStatus::Reviewing, TaskStatus::Failed, 1),
10089 (RunStatus::Gating, TaskStatus::Failed, 1),
10090 ];
10091 for (run, want, attempts) in table {
10092 let mut t = task();
10093 t.start("20260902-000000-aaaa".to_owned());
10094 settle(
10095 &mut t,
10096 Verdict {
10097 status: run,
10098 left_pr: false,
10099 parked: false,
10100 quota_hit: matches!(run, RunStatus::Stalled),
10101 no_viable_candidates: false,
10102 },
10103 "why",
10104 2,
10105 );
10106 assert_eq!(t.status, want, "task status after {}", label(run));
10107 assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
10108 }
10109 }
10110
10111 #[test]
10112 fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
10113 let mut stalled = task();
10114 stalled.start("20260902-000000-aaaa".to_owned());
10115 settle(
10116 &mut stalled,
10117 Verdict {
10118 status: RunStatus::Stalled,
10119 left_pr: false,
10120 parked: false,
10121 quota_hit: true,
10122 no_viable_candidates: false,
10123 },
10124 "quota",
10125 1,
10126 );
10127 assert_eq!(stalled.attempts, 0);
10128 assert!(
10129 stalled.status.runnable(),
10130 "a machine problem must leave the task in line"
10131 );
10132
10133 let mut blocked = task();
10134 blocked.start("20260902-000000-aaaa".to_owned());
10135 settle(
10136 &mut blocked,
10137 Verdict {
10138 status: RunStatus::Blocked,
10139 left_pr: false,
10140 parked: false,
10141 quota_hit: false,
10142 no_viable_candidates: false,
10143 },
10144 "findings open",
10145 1,
10146 );
10147 assert_eq!(blocked.attempts, 1);
10148 assert_eq!(
10149 blocked.status,
10150 TaskStatus::Held,
10151 "the last attempt hands the task to a human"
10152 );
10153 }
10154
10155 #[test]
10156 fn a_run_that_opened_a_pull_request_is_never_re_competed() {
10157 let mut delivered = task();
10160 delivered.start("20260903-080619-01c2".to_owned());
10161 settle(
10162 &mut delivered,
10163 Verdict {
10164 status: RunStatus::Blocked,
10165 left_pr: true,
10166 parked: false,
10167 quota_hit: false,
10168 no_viable_candidates: false,
10169 },
10170 "no check status",
10171 4,
10172 );
10173 assert_eq!(
10174 delivered.status,
10175 TaskStatus::Held,
10176 "a pull request waiting on CI or a person is not a retryable failure"
10177 );
10178 assert!(
10179 !delivered.status.runnable(),
10180 "the loop must not pick this task up again"
10181 );
10182 assert_eq!(
10183 delivered.last_error.as_deref(),
10184 Some("no check status"),
10185 "the operator needs to be told what the gate was waiting for"
10186 );
10187
10188 let mut empty_handed = task();
10191 empty_handed.start("20260903-080619-01c2".to_owned());
10192 settle(
10193 &mut empty_handed,
10194 Verdict {
10195 status: RunStatus::Blocked,
10196 left_pr: false,
10197 parked: false,
10198 quota_hit: false,
10199 no_viable_candidates: false,
10200 },
10201 "findings open",
10202 4,
10203 );
10204 assert_eq!(empty_handed.status, TaskStatus::Failed);
10205 assert!(empty_handed.status.runnable());
10206 }
10207
10208 #[test]
10209 fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
10210 let mut noop = task();
10216 noop.start("20260912-131304-391f".to_owned());
10217 settle(
10218 &mut noop,
10219 Verdict {
10220 status: RunStatus::VerifiedNoop,
10221 left_pr: false,
10222 parked: false,
10223 quota_hit: false,
10224 no_viable_candidates: true,
10225 },
10226 "candidate A: already fixed by b32cfc4, on main",
10227 4,
10228 );
10229 assert_eq!(
10230 noop.status,
10231 TaskStatus::Held,
10232 "an unverified claim is a request for a human, not a failure"
10233 );
10234 assert!(
10235 !noop.status.runnable(),
10236 "the loop must not requeue this on the same unverified claim"
10237 );
10238 assert_eq!(noop.attempts, 1);
10243 }
10244
10245 #[test]
10246 fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
10247 let mut parked = task();
10252 parked.start("20260903-183634-2d98".to_owned());
10253 settle(
10254 &mut parked,
10255 Verdict {
10256 status: RunStatus::Implementing,
10257 left_pr: false,
10258 quota_hit: false,
10259 parked: true,
10260 no_viable_candidates: false,
10261 },
10262 "parked after `implementing`",
10263 2,
10264 );
10265 assert_eq!(parked.attempts, 0, "a park is refunded");
10266 assert!(
10267 parked.status.runnable(),
10268 "and the task stays in line so the next loop resumes its run"
10269 );
10270 assert_eq!(parked.status, TaskStatus::Parked);
10271 assert_eq!(
10272 parked.park_reason.as_deref(),
10273 Some("parked after `implementing`"),
10274 "the card says where it stopped"
10275 );
10276 assert_eq!(parked.last_error, None, "nothing failed");
10277
10278 let mut broken = task();
10282 broken.start("20260903-183634-2d98".to_owned());
10283 settle(
10284 &mut broken,
10285 Verdict {
10286 status: RunStatus::Implementing,
10287 left_pr: false,
10288 quota_hit: false,
10289 parked: false,
10290 no_viable_candidates: false,
10291 },
10292 "returned mid-flight",
10293 2,
10294 );
10295 assert_eq!(broken.attempts, 1);
10296 }
10297
10298 #[test]
10299 fn only_a_rate_limit_buys_the_task_its_attempt_back() {
10300 let mut flaky = task();
10305 flaky.start("20260903-123023-e633".to_owned());
10306 settle(
10307 &mut flaky,
10308 Verdict {
10309 status: RunStatus::Stalled,
10310 left_pr: false,
10311 parked: false,
10312 quota_hit: false,
10313 no_viable_candidates: false,
10314 },
10315 "verdict rests on 1 of 3 judges",
10316 2,
10317 );
10318 assert_eq!(
10319 flaky.attempts, 1,
10320 "flakiness spends an attempt, so `max_attempts` still bounds it"
10321 );
10322 assert!(flaky.status.runnable(), "and it is still worth retrying");
10323
10324 let mut limited = task();
10326 limited.start("20260903-123023-e633".to_owned());
10327 settle(
10328 &mut limited,
10329 Verdict {
10330 status: RunStatus::Stalled,
10331 left_pr: false,
10332 parked: false,
10333 quota_hit: true,
10334 no_viable_candidates: false,
10335 },
10336 "judge-2, judge-3 out of quota",
10337 2,
10338 );
10339 assert_eq!(limited.attempts, 0, "a quota window is refunded");
10340 assert!(limited.status.runnable());
10341
10342 let mut worn = task();
10345 for _ in 0..2 {
10346 worn.release();
10347 }
10348 worn.start("20260903-123023-e633".to_owned());
10349 worn.attempts = 2;
10350 settle(
10351 &mut worn,
10352 Verdict {
10353 status: RunStatus::Stalled,
10354 left_pr: false,
10355 parked: false,
10356 quota_hit: false,
10357 no_viable_candidates: false,
10358 },
10359 "no quorum again",
10360 2,
10361 );
10362 assert_eq!(worn.status, TaskStatus::Held);
10363 assert!(!worn.status.runnable());
10364 }
10365
10366 #[test]
10367 fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
10368 let mut wiped_out = task();
10375 wiped_out.start("20260907-025000-a1b2".to_owned());
10376 settle(
10377 &mut wiped_out,
10378 Verdict {
10379 status: RunStatus::Failed,
10380 left_pr: false,
10381 parked: false,
10382 quota_hit: true,
10383 no_viable_candidates: true,
10384 },
10385 "no candidate produced a change; nothing to judge",
10386 2,
10387 );
10388 assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
10389 assert!(
10390 wiped_out.status.runnable(),
10391 "a machine problem must leave the task in line"
10392 );
10393
10394 let mut partial_progress = task();
10400 partial_progress.start("20260907-025500-c3d4".to_owned());
10401 settle(
10402 &mut partial_progress,
10403 Verdict {
10404 status: RunStatus::Failed,
10405 left_pr: false,
10406 parked: false,
10407 quota_hit: true,
10408 no_viable_candidates: false,
10409 },
10410 "gate failed on the winning candidate",
10411 2,
10412 );
10413 assert_eq!(
10414 partial_progress.attempts, 1,
10415 "a candidate that actually produced a change spends the attempt \
10416 even though some other seat hit its quota"
10417 );
10418 assert!(partial_progress.status.runnable());
10419 }
10420
10421 #[test]
10422 fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
10423 let mut t = task();
10429 t.start("20260907-025000-a1b2".to_owned());
10430 let mut state = run_state(RunStatus::Failed);
10431 state.quota.push(QuotaLoss {
10432 cause: crate::agent::QuotaCause::UsageLimit,
10433 agent: String::new(),
10434 seat: "cand-a".to_owned(),
10435 node: "implement".to_owned(),
10436 at: Timestamp::now(),
10437 reset: None,
10438 });
10439 assert!(
10440 state.viable().is_empty(),
10441 "no candidate was added, so nothing is viable"
10442 );
10443 reclaim(&mut t, Some(state), 2, "en");
10444 assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
10445 assert!(t.status.runnable());
10446 }
10447
10448 #[test]
10449 fn a_held_task_is_never_offered_to_the_loop() {
10450 let dir = tempfile::tempdir().unwrap();
10451 let queue = Queue::at(dir.path().to_path_buf());
10452 for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
10453 let mut t = task();
10454 t.id = format!("2026090{n}-000000-000{n}");
10455 t.priority = priority;
10456 queue.put(&mut t).unwrap();
10457 }
10458 let mut held = task();
10459 held.id = "20260909-000000-9999".to_owned();
10460 held.priority = 99;
10461 held.hold_machine(None);
10462 queue.put(&mut held).unwrap();
10463
10464 let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
10465 assert_eq!(order.len(), 3);
10466 assert!(!order.contains(&held.id));
10467 assert_eq!(
10468 order.first().cloned(),
10469 queue.next_runnable().map(|t| t.id),
10470 "the loop's first candidate is exactly what the queue offers"
10471 );
10472 assert_eq!(
10473 order,
10474 vec![
10475 "20260902-000000-0002".to_owned(),
10476 "20260903-000000-0003".to_owned(),
10477 "20260901-000000-0001".to_owned(),
10478 ],
10479 "priority first, then oldest, so nothing starves"
10480 );
10481 }
10482
10483 #[test]
10484 fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
10485 let dir = tempfile::tempdir().unwrap();
10486 let queue = Queue::at(dir.path().to_path_buf());
10487 let mut old = task();
10488 old.id = "20260101-000000-old0".to_owned();
10489 queue.put(&mut old).unwrap();
10490 let mut fresh = task();
10491 fresh.id = "20260101-000000-new0".to_owned();
10492 queue.put(&mut fresh).unwrap();
10493
10494 std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
10498 std::thread::sleep(Duration::from_millis(60));
10499 let live = queue.claim(&fresh.id).unwrap();
10500
10501 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
10502 assert_eq!(swept, vec![old.id.clone()]);
10503 assert!(
10504 queue.claim(&old.id).is_ok(),
10505 "an unparseable lock older than the threshold is swept"
10506 );
10507 assert!(
10508 queue.claim(&fresh.id).is_err(),
10509 "a live pid protects its lock regardless of age"
10510 );
10511 drop(live);
10512 }
10513
10514 #[test]
10515 fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
10516 let dir = tempfile::tempdir().unwrap();
10519 let queue = Queue::at(dir.path().to_path_buf());
10520 let mut t = task();
10521 t.id = "20260101-000000-live".to_owned();
10522 queue.put(&mut t).unwrap();
10523
10524 let claim = queue.claim(&t.id).unwrap();
10525 std::thread::sleep(Duration::from_millis(60));
10526
10527 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
10528 assert!(
10529 swept.is_empty(),
10530 "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
10531 );
10532 assert!(
10533 queue.claim(&t.id).is_err(),
10534 "the lock still protects its task"
10535 );
10536 drop(claim);
10537 }
10538
10539 fn injected_dead_pid() -> u32 {
10542 std::process::id().checked_add(1).unwrap_or(1)
10543 }
10544
10545 #[test]
10546 fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
10547 let dir = tempfile::tempdir().unwrap();
10548 let queue = Queue::at(dir.path().to_path_buf());
10549 let mut t = task();
10550 t.id = "20260101-000000-dead".to_owned();
10551 queue.put(&mut t).unwrap();
10552 let dead_pid = injected_dead_pid();
10553
10554 std::fs::write(
10559 dir.path().join(format!("{}.lock", t.id)),
10560 dead_pid.to_string(),
10561 )
10562 .unwrap();
10563
10564 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
10565 pid != dead_pid
10566 });
10567 assert_eq!(
10568 swept,
10569 vec![t.id.clone()],
10570 "a dead owner is reclaimed immediately, not after STALE_CLAIM"
10571 );
10572 assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
10573 }
10574
10575 #[test]
10576 fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
10577 let dir = tempfile::tempdir().unwrap();
10578 let queue = Queue::at(dir.path().to_path_buf());
10579 let mut t = task();
10580 t.id = "20260101-000000-late".to_owned();
10581 queue.put(&mut t).unwrap();
10582 let dead_pid = injected_dead_pid();
10583
10584 assert!(
10587 sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
10588 "nothing has claimed the task yet"
10589 );
10590
10591 std::fs::write(
10594 dir.path().join(format!("{}.lock", t.id)),
10595 dead_pid.to_string(),
10596 )
10597 .unwrap();
10598
10599 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
10603 pid != dead_pid
10604 });
10605 assert_eq!(swept, vec![t.id.clone()]);
10606 }
10607
10608 #[test]
10609 fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
10610 crate::run::pin_test_home();
10615 let dir = tempfile::tempdir().unwrap();
10616 let queue = Queue::at(dir.path().to_path_buf());
10617 let mut t = task();
10618 t.id = "20260101-000000-crsh".to_owned();
10619 t.status = TaskStatus::Running;
10620 t.attempts = 1;
10621 t.runs.push("20260904-000000-4043".to_owned());
10625 queue.put(&mut t).unwrap();
10626 let dead_pid = injected_dead_pid();
10627
10628 std::fs::write(
10631 dir.path().join(format!("{}.lock", t.id)),
10632 dead_pid.to_string(),
10633 )
10634 .unwrap();
10635
10636 assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
10642 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
10643
10644 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
10645 pid != dead_pid
10646 });
10647 assert_eq!(swept, vec![t.id.clone()]);
10648
10649 let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
10650 assert_eq!(reclaimed, vec![t.id.clone()]);
10651 let after = queue.get(&t.id).unwrap();
10652 assert_eq!(
10653 after.status,
10654 TaskStatus::Held,
10655 "no run.json to recover from, so a human is asked"
10656 );
10657 assert_eq!(
10658 after.runs,
10659 vec!["20260904-000000-4043".to_owned()],
10660 "the crashed run's id is kept as evidence, not discarded"
10661 );
10662 }
10663
10664 #[test]
10665 fn a_lock_is_kept_when_the_process_query_is_unavailable() {
10666 let dir = tempfile::tempdir().unwrap();
10667 let queue = Queue::at(dir.path().to_path_buf());
10668 let mut t = task();
10669 t.id = "20260101-000000-unknown".to_owned();
10670 queue.put(&mut t).unwrap();
10671 let dead_pid = injected_dead_pid();
10672 std::fs::write(
10673 dir.path().join(format!("{}.lock", t.id)),
10674 dead_pid.to_string(),
10675 )
10676 .unwrap();
10677
10678 let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
10679 assert!(swept.is_empty(), "an unknown pid must keep its lock");
10680 assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
10681 }
10682
10683 fn run_state_in(status: RunStatus, language: &str) -> RunState {
10684 let mut s = run_state(status);
10685 s.config.graph.language = language.to_owned();
10686 s
10687 }
10688
10689 fn unstarted_verdict(status: RunStatus) -> Verdict {
10690 Verdict {
10691 status,
10692 left_pr: false,
10693 quota_hit: false,
10694 parked: false,
10695 no_viable_candidates: false,
10696 }
10697 }
10698
10699 #[test]
10700 fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
10701 let mut t = task();
10702 t.attempts = 1;
10703 settle_in(
10704 &mut t,
10705 unstarted_verdict(RunStatus::AlreadyInBase),
10706 "already in main",
10707 1,
10708 phrases("en"),
10709 None,
10710 );
10711 assert_eq!(t.status, TaskStatus::Done);
10712 assert_eq!(t.attempts, 0);
10713 }
10714
10715 #[test]
10716 fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
10717 let reason = |language: &str| {
10718 let mut t = task();
10719 settle_in(
10720 &mut t,
10721 unstarted_verdict(RunStatus::Judging),
10722 "boom",
10723 1,
10724 phrases(language),
10725 None,
10726 );
10727 t.last_error.or(t.hold_reason).unwrap_or_default()
10728 };
10729 assert!(
10730 reason("en").starts_with("the graph stopped at `"),
10731 "{}",
10732 reason("en")
10733 );
10734 assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
10735 assert!(reason("日本語").contains("boom"));
10736 assert_eq!(reason("fr"), reason("en"));
10737 }
10738
10739 #[test]
10740 fn describe_follows_the_run_language_and_keeps_the_run_id() {
10741 let en = describe(&run_state_in(RunStatus::Stalled, "en"));
10742 assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
10743 let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
10744 assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
10745 assert!(ja.contains("[run "), "{ja}");
10746 let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
10747 assert!(ended.starts_with("run 終了: "), "{ended}");
10748 let mut de = run_state_in(RunStatus::Failed, "de");
10749 let mut en = run_state_in(RunStatus::Failed, "en");
10750 de.id = "same".to_owned();
10751 en.id = "same".to_owned();
10752 assert_eq!(describe(&de), describe(&en));
10753 }
10754
10755 #[test]
10756 fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
10757 use crate::handover::Refused;
10758 let cases = [
10759 Refused::Foreign {
10760 branch: "b".into(),
10761 path: "/w/x".into(),
10762 why: "made by hand".into(),
10763 },
10764 Refused::Unsafe {
10765 branch: "b".into(),
10766 path: "/w/x".into(),
10767 why: "its worktree has uncommitted changes (a.rs)".into(),
10768 },
10769 Refused::ReleaseFailed {
10770 branch: "b".into(),
10771 path: "/w/x".into(),
10772 run: "ab12".into(),
10773 },
10774 ];
10775 for r in &cases {
10776 let en = (phrases("en").handover_refused)(r);
10777 assert_eq!(en, r.to_string());
10778 let ja = (phrases("ja").handover_refused)(r);
10779 assert!(
10780 !ja.contains("is checked out") && !ja.contains("try again"),
10781 "{ja}"
10782 );
10783 assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
10784 if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
10785 assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
10786 }
10787 }
10788 assert!(phrases("en").handover_hint.contains("release the task"));
10789 assert!(phrases("ja").handover_hint.contains("解放"));
10790 }
10791
10792 #[test]
10793 fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
10794 let build = |lang: &str| {
10795 let mut s = run_state_in(RunStatus::Blocked, lang);
10796 s.id = "same".to_owned();
10797 s.config.graph.review_rounds = 3;
10798 let mut r = review_round(3);
10799 r.expected = 3;
10800 r.answered = 1;
10801 s.reviews.push(r);
10802 s.event(
10803 "review",
10804 "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
10805 );
10806 s
10807 };
10808 let en = describe(&build("en"));
10809 assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
10810 let ja = describe(&build("ja"));
10811 assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
10812 assert!(!ja.contains("never answered"), "{ja}");
10813 assert!(ja.contains("[run "), "{ja}");
10814
10815 let mut failed = build("ja");
10818 failed.reviews[0].e2e.push(crate::run::CommandOutcome {
10819 command: "cargo test".to_owned(),
10820 code: Some(1),
10821 output_tail: String::new(),
10822 duration_ms: 0,
10823 resource_blocked: false,
10824 ..Default::default()
10825 });
10826 failed.event("review", "stopped; e2e failed: cargo test");
10827 let ja = describe(&failed);
10828 assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
10829 assert!(!ja.contains("席のレビュアー"), "{ja}");
10830 }
10831
10832 #[test]
10833 fn refusals_and_recovery_prose_follow_the_language() {
10834 let home = crate::run::test_home();
10835 let t = held_task_with("r1");
10836 let q = action_question(
10837 "r1",
10838 ask::ChoiceAction::Resume {
10839 run: "r1".to_owned(),
10840 },
10841 );
10842 let refuse = |p: &Phrases| match decide_action(&home, &t, &q, p, |_: &str| bail!("gone")) {
10843 ActionDecision::Refuse(s) => s,
10844 other => panic!("{other:?}"),
10845 };
10846 assert!(refuse(phrases("en")).contains("could not be read: gone"));
10847 assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
10848 assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
10849
10850 let mut held = task();
10851 reclaim(&mut held, None, 2, "ja");
10852 assert!(held.hold_reason.unwrap().contains("保留にしました"));
10853 let mut held = task();
10854 reclaim(&mut held, None, 2, "xx");
10855 assert!(held.hold_reason.unwrap().contains("held for a human"));
10856 }
10857
10858 fn run_state(status: RunStatus) -> RunState {
10859 let mut state = RunState::new(
10860 PathBuf::from("/repo"),
10861 "main".to_owned(),
10862 "abc1234def".to_owned(),
10863 "add retries".to_owned(),
10864 Config::default(),
10865 );
10866 state.status = status;
10867 state
10868 }
10869
10870 #[test]
10871 fn settlement_audits_the_loaded_run_instead_of_reloading_a_stale_snapshot() {
10872 crate::run::pin_test_home();
10873 let dir = tempfile::tempdir().unwrap();
10874 let mut state = run_state(RunStatus::Blocked);
10875 state.id = "20260101-000000-audit".into();
10876 state.save_under(dir.path()).unwrap();
10877 let mut t = task();
10878 t.start(state.id.clone());
10879 state.status = RunStatus::Ready;
10882 settle_and_diagnose(
10883 &mut t,
10884 unstarted_verdict(RunStatus::Ready),
10885 "Verified local delivery",
10886 2,
10887 &state,
10888 );
10889 let completion = t.completion_history.last().unwrap();
10890 assert_eq!(completion.actor, CompletionActor::DaemonSettle);
10891 assert_eq!(completion.prior_status, TaskStatus::Running);
10892 assert_eq!(
10893 completion.reason.as_deref(),
10894 Some("Verified local delivery")
10895 );
10896 let snapshot = completion.run.as_ref().unwrap();
10897 assert_eq!(snapshot.id, state.id);
10898 assert_eq!(snapshot.status, Some(RunStatus::Ready));
10899 assert_eq!(
10900 RunState::load_under(&state.id, dir.path()).unwrap().status,
10901 RunStatus::Blocked,
10902 "settlement records the actual outcome without rewriting run history"
10903 );
10904 }
10905
10906 fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
10907 Candidate {
10908 index: 0,
10909 label,
10910 agent: "claude".to_owned(),
10911 branch: format!("magi/x/{label}"),
10912 worktree: PathBuf::from("/repo"),
10913 summary: summary.to_owned(),
10914 stat: String::new(),
10915 files: 0,
10916 commits: usize::from(!empty),
10917 empty,
10918 failed: failed.map(str::to_owned),
10919 verified_noop: None,
10920 duration_ms: 0,
10921 folded: false,
10922 }
10923 }
10924
10925 #[test]
10926 fn diagnostic_names_the_failing_gate_checks_and_their_output() {
10927 let mut state = run_state(RunStatus::Blocked);
10928 state.gate = vec![
10929 CommandOutcome {
10930 command: "cargo make check".to_owned(),
10931 code: Some(0),
10932 output_tail: "ok".to_owned(),
10933 duration_ms: 0,
10934 resource_blocked: false,
10935 ..Default::default()
10936 },
10937 CommandOutcome {
10938 command: "cargo test".to_owned(),
10939 code: Some(101),
10940 output_tail: "thread 'x' panicked: assertion failed".to_owned(),
10941 duration_ms: 0,
10942 resource_blocked: false,
10943 ..Default::default()
10944 },
10945 ];
10946 let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
10947 assert!(d.contains("cargo test"), "{d}");
10948 assert!(
10949 !d.contains("cargo make check"),
10950 "a passing check is not a diagnostic: {d}"
10951 );
10952 assert!(d.contains("assertion failed"), "{d}");
10953 }
10954
10955 #[test]
10956 fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
10957 let mut state = run_state(RunStatus::Blocked);
10958 state.event(
10959 "land",
10960 "stopped: the fixer produced no commit while 2 check(s) were failing \
10961 (build, lint); stopping instead of looping on an unchanged tree",
10962 );
10963 let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
10964 assert!(d.contains("build"), "{d}");
10965 assert!(d.contains("lint"), "{d}");
10966 assert!(d.contains("fixer produced no commit"), "{d}");
10967 }
10968
10969 #[test]
10970 fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
10971 let state = run_state(RunStatus::VerifiedNoop);
10976 let d = describe(&state);
10977 assert!(
10978 d.contains("agent-verified no-op"),
10979 "expected the display label, not the wire spelling: {d}"
10980 );
10981 assert!(!d.contains("verified_noop"), "{d}");
10982 }
10983
10984 #[test]
10985 fn diagnostic_keeps_gate_panic_before_large_backtrace() {
10986 let mut state = run_state(RunStatus::Failed);
10987 state.gate.push(crate::run::CommandOutcome {
10988 command: "cargo test".into(),
10989 code: Some(101),
10990 output_tail: format!(
10991 "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
10992 " 41: 0x1234 - backtrace frame\n".repeat(10000)
10993 ),
10994 duration_ms: 1,
10995 resource_blocked: false,
10996 ..Default::default()
10997 });
10998 let d = diagnostic(&state).unwrap();
10999 assert!(d.contains("panicked at widget.rs:12"), "{d}");
11000 assert!(d.contains("assertion failed: widget missing"));
11001 assert!(d.contains("widget log"));
11002 }
11003
11004 #[test]
11005 fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
11006 let mut state = run_state(RunStatus::Failed);
11012 state.candidates = vec![candidate(
11013 'A',
11014 "opened pull request #42, merged it, tagged v1.2.3 and published the release",
11015 true,
11016 None,
11017 )];
11018 let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
11019 assert!(d.contains("candidate A"), "{d}");
11020 assert!(d.contains("tagged v1.2.3"), "{d}");
11021 }
11022
11023 #[test]
11024 fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
11025 let mut state = run_state(RunStatus::Failed);
11026 state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
11027 let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
11028 assert!(d.contains("candidate A"), "{d}");
11029 assert!(d.contains("agent timed out"), "{d}");
11030 }
11031
11032 #[test]
11033 fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
11034 let mut state = run_state(RunStatus::Failed);
11037 state.candidates = vec![candidate('A', "did the work", false, None)];
11038 assert!(diagnostic(&state).is_none());
11039 }
11040
11041 #[test]
11042 fn diagnostic_is_bounded_however_much_a_run_printed() {
11043 let mut state = run_state(RunStatus::Blocked);
11044 state.gate = vec![
11045 CommandOutcome {
11046 command: "cargo test".to_owned(),
11047 code: Some(101),
11048 output_tail: "x".repeat(50_000),
11049 duration_ms: 0,
11050 resource_blocked: false,
11051 ..Default::default()
11052 },
11053 CommandOutcome {
11054 command: "cargo clippy".to_owned(),
11055 code: Some(1),
11056 output_tail: "y".repeat(50_000),
11057 duration_ms: 0,
11058 resource_blocked: false,
11059 ..Default::default()
11060 },
11061 ];
11062 state.candidates = vec![
11063 candidate('A', &"z".repeat(50_000), true, None),
11064 candidate('B', &"w".repeat(50_000), true, None),
11065 ];
11066 let d = diagnostic(&state).expect("plenty here to diagnose");
11067 assert!(
11068 d.len() <= DIAGNOSTIC_MAX,
11069 "diagnostic grew to {} bytes, unbounded",
11070 d.len()
11071 );
11072 }
11073
11074 #[test]
11075 fn selected_delivery_guards_survive_recovery_failure_accounting() {
11076 for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
11077 let mut t = task();
11078 let mut state = run_state(status);
11079 t.pr_recovery = Some(crate::pr_recovery::Selection {
11080 url: "url".into(),
11081 branch: format!("magi/task-{}", t.id),
11082 head: "a".repeat(40),
11083 source_head: None,
11084 source_run: None,
11085 source_proof: None,
11086 disposition: Some(crate::pr_recovery::Disposition::Land),
11087 instruction: t.instruction.clone(),
11088 approved_at: Timestamp::now(),
11089 });
11090 state.pr_recovery = t.pr_recovery.clone();
11091 t.start(state.id.clone());
11092 settle_and_diagnose(
11093 &mut t,
11094 Verdict {
11095 status,
11096 left_pr: false,
11097 quota_hit: false,
11098 parked: false,
11099 no_viable_candidates: false,
11100 },
11101 "delivery stopped",
11102 5,
11103 &state,
11104 );
11105 assert_eq!(t.status, TaskStatus::Held);
11106 let reason = t.hold_reason.as_deref().unwrap();
11107 if status == RunStatus::Ready {
11108 assert!(reason.contains("Selected PR delivery is incomplete"));
11109 assert!(t.recovery_budget.is_none());
11110 } else {
11111 assert!(reason.contains("Selected recovery stopped"));
11112 assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
11113 }
11114 assert!(t.pr_recovery.is_some());
11115 }
11116 }
11117
11118 #[test]
11119 fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
11120 let mut state = run_state(RunStatus::Voting);
11121 state.base_sync = Some(crate::run::BaseSync {
11122 tip: "base-tip".into(),
11123 behind: 3,
11124 attempts: 4,
11125 conflict: Some("base stopped".into()),
11126 already_in: None,
11127 });
11128 state.record_base_sync_stop("candidate-head");
11129 let mut t = task();
11130 t.start(state.id.clone());
11131 let verdict = Verdict {
11132 status: RunStatus::Blocked,
11133 left_pr: false,
11134 quota_hit: false,
11135 parked: false,
11136 no_viable_candidates: false,
11137 };
11138 settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
11139 assert_eq!(
11140 t.status,
11141 TaskStatus::Held,
11142 "unspent task attempts cannot start another competition"
11143 );
11144 let at = t.held_at;
11145 let cause = t.hold_notice_cause.clone();
11146 state.begin_pass();
11147 t.release_operator("test-resume", None);
11148 t.start(state.id.clone());
11149 settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
11150 assert_eq!(t.status, TaskStatus::Held);
11151 assert_eq!(t.held_at, at);
11152 assert_eq!(t.hold_notice_cause, cause);
11153 }
11154
11155 #[test]
11156 fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
11157 let mut state = run_state(RunStatus::Blocked);
11158 state.gate = vec![CommandOutcome {
11159 command: "cargo test".to_owned(),
11160 code: Some(101),
11161 output_tail: "assertion failed".to_owned(),
11162 duration_ms: 0,
11163 resource_blocked: false,
11164 ..Default::default()
11165 }];
11166 let verdict = Verdict {
11167 status: RunStatus::Blocked,
11168 left_pr: false,
11169 quota_hit: false,
11170 parked: false,
11171 no_viable_candidates: false,
11172 };
11173
11174 let mut t = task();
11177 t.start("run-1".to_owned());
11178 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
11179 assert_eq!(t.status, TaskStatus::Failed);
11180 assert!(t.diagnostic.is_none());
11181
11182 t.start("run-2".to_owned());
11185 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
11186 assert_eq!(t.status, TaskStatus::Held);
11187 let d = t.diagnostic.expect("a held task must carry its diagnostic");
11188 assert!(d.contains("cargo test"), "{d}");
11189 }
11190
11191 fn verified_noop_run_state() -> RunState {
11192 let mut state = run_state(RunStatus::VerifiedNoop);
11193 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":[]}"#;
11194 let mut c = candidate('A', summary, true, None);
11195 c.verified_noop = Some(summary.to_owned());
11196 state.candidates = vec![c];
11197 state
11198 }
11199
11200 #[test]
11201 fn a_held_task_names_the_open_question_it_is_waiting_on() {
11202 crate::run::pin_test_home();
11207 let home = crate::run::home();
11208 let state = verified_noop_run_state();
11209 let mut q = ask::Question::new(
11210 state.id.clone(),
11211 "implement".to_owned(),
11212 "impl-A".to_owned(),
11213 "is this really a no-op?".to_owned(),
11214 String::new(),
11215 Vec::new(),
11216 );
11217 Questions::at(home.join("questions")).put(&mut q).unwrap();
11218
11219 let verdict = Verdict {
11220 status: RunStatus::VerifiedNoop,
11221 left_pr: false,
11222 quota_hit: false,
11223 parked: false,
11224 no_viable_candidates: true,
11225 };
11226 let mut t = task();
11227 t.start(state.id.clone());
11228 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
11229
11230 assert_eq!(t.status, TaskStatus::Held);
11231 let reason = t.hold_reason.expect("a held task must record why");
11232 assert!(
11233 reason.starts_with("run ended agent-verified no-op"),
11234 "the original settle reason must survive unchanged: {reason}"
11235 );
11236 assert!(
11237 reason.contains(q.short()),
11238 "the open question's id must be named so the notice is actionable: {reason}"
11239 );
11240 }
11241
11242 #[test]
11243 fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
11244 crate::run::pin_test_home();
11245 let state = verified_noop_run_state();
11246
11247 let verdict = Verdict {
11248 status: RunStatus::VerifiedNoop,
11249 left_pr: false,
11250 quota_hit: false,
11251 parked: false,
11252 no_viable_candidates: true,
11253 };
11254 let mut t = task();
11255 t.start(state.id.clone());
11256 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
11257
11258 assert_eq!(t.status, TaskStatus::Held);
11259 assert_eq!(
11260 t.hold_reason.as_deref(),
11261 Some("run ended agent-verified no-op"),
11262 "nothing to append when the question was already answered or never asked"
11263 );
11264 }
11265
11266 #[test]
11267 fn inconsistent_verified_noop_state_settles_and_reclaims_as_ordinary_failure() {
11268 crate::run::pin_test_home();
11269
11270 let mut bad = run_state(RunStatus::VerifiedNoop);
11273 let mut c = candidate(
11274 'A',
11275 "NO CHANGE NEEDED: Not established. No source changes, commit, or reproduction checks were completed. The reported Git configuration lock contention remains unresolved.",
11276 true,
11277 None,
11278 );
11279 c.verified_noop = Some("Not established.".to_owned());
11280 bad.candidates = vec![c];
11281
11282 let mut t = task();
11283 t.start(bad.id.clone());
11284 let verdict = Verdict {
11285 status: RunStatus::VerifiedNoop,
11286 left_pr: false,
11287 quota_hit: true,
11288 parked: false,
11289 no_viable_candidates: true,
11290 };
11291 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 3, &bad);
11292 assert_eq!(
11293 t.status,
11294 TaskStatus::Failed,
11295 "inconsistent verified_noop must retry as Failed when attempts remain"
11296 );
11297 assert_eq!(t.attempts, 1);
11298 assert_eq!(
11299 t.last_error.as_deref(),
11300 Some("no-change result lacks verified evidence")
11301 );
11302 assert!(t.hold_reason.is_none());
11303
11304 let mut t_exhausted = task();
11308 t_exhausted.start(bad.id.clone());
11309 reclaim(&mut t_exhausted, Some(bad.clone()), 1, "en");
11310 assert_eq!(t_exhausted.status, TaskStatus::Held);
11311 assert_eq!(t_exhausted.attempts, 1);
11312 assert_eq!(
11313 t_exhausted
11314 .hold_notice_cause
11315 .as_ref()
11316 .map(|c| c.stage.as_str()),
11317 Some("failed"),
11318 "exhausted inconsistent verified_noop must not emit a verified_noop notice cause"
11319 );
11320 let diag = t_exhausted.diagnostic.as_deref().unwrap_or("");
11321 assert!(
11322 !diag.contains("agent-verified no-op"),
11323 "diagnostic must not mislabel an invalid claim as verified no-op: {diag}"
11324 );
11325 assert!(diag.contains("Not established"), "{diag}");
11326 }
11327
11328 #[test]
11329 fn saved_noop_declaration_is_the_evidence_not_the_display_summary() {
11330 let mut state = verified_noop_run_state();
11331 let summary = state.candidates[0].summary.clone();
11332 state.candidates[0].summary = "Already satisfied.".to_owned();
11333 assert!(state.all_candidates_verified_noop());
11334
11335 state.candidates[0].summary = summary;
11336 state.candidates[0].verified_noop = Some("Historical prose only.".to_owned());
11337 assert!(!state.all_candidates_verified_noop());
11338 }
11339
11340 #[test]
11341 fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
11342 crate::run::pin_test_home();
11343 let mut first = run_state(RunStatus::Blocked);
11344 first.id = "20260101-000000-sup1".to_owned();
11345 first.save().unwrap();
11346 let mut second = run_state(RunStatus::Merged);
11347 second.id = "20260101-000000-sup2".to_owned();
11348 second.save().unwrap();
11349
11350 let mut t = task();
11351 t.runs = vec![first.id.clone(), second.id.clone()];
11352 t.status = TaskStatus::Done;
11353
11354 supersede_prior_runs(&t, &crate::run::home());
11355
11356 assert_eq!(
11357 RunState::load(&first.id).unwrap().status,
11358 RunStatus::Superseded,
11359 "the first attempt's Blocked no longer needs anyone's attention"
11360 );
11361 assert_eq!(
11362 RunState::load(&second.id).unwrap().status,
11363 RunStatus::Merged,
11364 "the run that actually succeeded is left exactly as it was"
11365 );
11366 }
11367
11368 #[test]
11369 fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
11370 crate::run::pin_test_home();
11376 let mut first = run_state(RunStatus::Blocked);
11377 first.id = "20260101-000000-sup9".to_owned();
11378 first.driver_pid = Some(std::process::id());
11381 first.driver_started_at = Some(
11382 crate::proc::process_started_at(std::process::id())
11383 .expect("this test process's own start time must be queryable"),
11384 );
11385 first.save().unwrap();
11386 let mut second = run_state(RunStatus::Merged);
11387 second.id = "20260101-000000-supa".to_owned();
11388 second.save().unwrap();
11389
11390 let mut t = task();
11391 t.runs = vec![first.id.clone(), second.id.clone()];
11392 t.status = TaskStatus::Done;
11393
11394 supersede_prior_runs(&t, &crate::run::home());
11395
11396 assert_eq!(
11397 RunState::load(&first.id).unwrap().status,
11398 RunStatus::Blocked,
11399 "a live driver_pid means something is still actually working this run, \
11400 even though no daemon claims it - rewriting under it would just be \
11401 undone the next time that process saves"
11402 );
11403 }
11404
11405 #[test]
11406 fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
11407 let dir = tempfile::tempdir().unwrap();
11413 let home = dir.path().to_path_buf();
11414 let queue = Queue::at(dir.path().join("queue"));
11415
11416 let mut first = run_state(RunStatus::Blocked);
11417 first.id = "20260101-000000-supd".to_owned();
11418 first.driver_pid = Some(std::process::id());
11419 first.driver_started_at = Some(
11420 crate::proc::process_started_at(std::process::id())
11421 .expect("this test process's own start time must be queryable"),
11422 );
11423 first.save_under(&home).unwrap();
11424 let mut second = run_state(RunStatus::Merged);
11425 second.id = "20260101-000000-supe".to_owned();
11426 second.save_under(&home).unwrap();
11427
11428 let mut t = task();
11429 t.runs = vec![first.id.clone(), second.id.clone()];
11430 t.status = TaskStatus::Done;
11431 queue.put(&mut t).unwrap();
11432
11433 resweep_superseded_attempts(&queue, &home);
11434 assert_eq!(
11435 RunState::load_under(&first.id, &home).unwrap().status,
11436 RunStatus::Blocked,
11437 "still live on the first pass, so still untouched"
11438 );
11439
11440 let mut stale = RunState::load_under(&first.id, &home).unwrap();
11446 stale.driver_started_at = Some("1".to_owned());
11447 stale.save_under(&home).unwrap();
11448
11449 resweep_superseded_attempts(&queue, &home);
11450 assert_eq!(
11451 RunState::load_under(&first.id, &home).unwrap().status,
11452 RunStatus::Superseded,
11453 "the second pass catches up what the first one correctly skipped"
11454 );
11455 }
11456
11457 #[test]
11458 fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
11459 crate::run::pin_test_home();
11460 let mut first = run_state(RunStatus::Blocked);
11461 first.id = "20260101-000000-sup3".to_owned();
11462 first.save().unwrap();
11463 let mut second = run_state(RunStatus::Blocked);
11464 second.id = "20260101-000000-sup4".to_owned();
11465 second.save().unwrap();
11466
11467 let mut t = task();
11468 t.runs = vec![first.id.clone(), second.id.clone()];
11469 t.status = TaskStatus::Failed;
11473
11474 supersede_prior_runs(&t, &crate::run::home());
11475
11476 assert_eq!(
11477 RunState::load(&first.id).unwrap().status,
11478 RunStatus::Blocked
11479 );
11480 assert_eq!(
11481 RunState::load(&second.id).unwrap().status,
11482 RunStatus::Blocked
11483 );
11484 }
11485
11486 #[test]
11487 fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
11488 crate::run::pin_test_home();
11492 let mut first = run_state(RunStatus::Blocked);
11493 first.id = "20260101-000000-sup5".to_owned();
11494 first.save().unwrap();
11495
11496 let mut t = task();
11497 t.runs = vec![first.id.clone()];
11498 t.status = TaskStatus::Done;
11499
11500 supersede_prior_runs(&t, &crate::run::home());
11501
11502 assert_eq!(
11503 RunState::load(&first.id).unwrap().status,
11504 RunStatus::Blocked,
11505 "a single-attempt task has no earlier run to supersede"
11506 );
11507 }
11508
11509 #[test]
11510 fn supersede_prior_runs_preserves_blocked_work_after_an_audited_manual_close() {
11511 for status in [
11512 RunStatus::Blocked,
11513 RunStatus::Stalled,
11514 RunStatus::Failed,
11515 RunStatus::Ready,
11516 RunStatus::Merged,
11517 ] {
11518 let dir = tempfile::tempdir().unwrap();
11519 let home = dir.path();
11520 let mut first = run_state(RunStatus::Blocked);
11521 first.id = "20260101-000000-supb".to_owned();
11522 first.save_under(home).unwrap();
11523 let mut second = run_state(status);
11524 second.id = "20260101-000000-supc".to_owned();
11525 second.save_under(home).unwrap();
11526
11527 let mut t = task();
11528 t.runs = vec![first.id.clone(), second.id.clone()];
11529 t.hold_manual(Some("Unmerged work remains".into()));
11530 let mut context = CompletionContext::new(
11531 CompletionActor::Cli,
11532 Some("Discard the unmerged attempts".into()),
11533 home,
11534 &t,
11535 );
11536 context.discard = true;
11537 t.succeed(context);
11538 assert_eq!(t.completion_history.len(), 1);
11539
11540 supersede_prior_runs(&t, home);
11541
11542 assert_eq!(
11543 RunState::load_under(&first.id, home).unwrap().status,
11544 RunStatus::Blocked,
11545 "an audited manual close is not proof the earlier work landed"
11546 );
11547 assert_eq!(
11548 RunState::load_under(&second.id, home).unwrap().status,
11549 status,
11550 "the latest attempt retains its actual outcome"
11551 );
11552 }
11553 }
11554
11555 #[test]
11556 fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
11557 crate::run::pin_test_home();
11561 let mut failed = run_state(RunStatus::Failed);
11562 failed.id = "20260101-000000-sup6".to_owned();
11563 failed.save().unwrap();
11564 let mut noop = run_state(RunStatus::VerifiedNoop);
11565 noop.id = "20260101-000000-sup7".to_owned();
11566 noop.save().unwrap();
11567 let mut winner = run_state(RunStatus::Ready);
11568 winner.id = "20260101-000000-sup8".to_owned();
11569 winner.save().unwrap();
11570
11571 let mut t = task();
11572 t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
11573 t.status = TaskStatus::Done;
11574
11575 supersede_prior_runs(&t, &crate::run::home());
11576
11577 assert_eq!(
11578 RunState::load(&failed.id).unwrap().status,
11579 RunStatus::Failed
11580 );
11581 assert_eq!(
11582 RunState::load(&noop.id).unwrap().status,
11583 RunStatus::VerifiedNoop
11584 );
11585 }
11586
11587 fn approval_question(run: &str) -> ask::Question {
11588 ask::Question::new(
11589 run.to_owned(),
11590 land::APPROVAL_NODE.to_owned(),
11591 "land".to_owned(),
11592 "merge?".to_owned(),
11593 String::new(),
11594 vec!["merge".to_owned(), "hold".to_owned()],
11595 )
11596 }
11597
11598 #[test]
11599 fn land_resume_state_leaves_a_fresh_open_question_waiting() {
11600 crate::run::pin_test_home();
11601 let mut state = run_state(RunStatus::Landing);
11602 state.id = "20260101-000000-fre1".to_owned();
11603 state.parked = true;
11604 state.save().unwrap();
11605 ask::Questions::open()
11606 .put(&mut approval_question(&state.id))
11607 .unwrap();
11608
11609 let mut t = task();
11610 t.runs.push(state.id.clone());
11611 assert_eq!(
11612 land_resume_state(&t),
11613 LandResume::StillWaiting,
11614 "nobody has answered and the timeout has not passed"
11615 );
11616 }
11617
11618 #[test]
11619 fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
11620 crate::run::pin_test_home();
11621 let mut state = run_state(RunStatus::Gating);
11622 state.id = "20260101-000000-gt01".to_owned();
11623 state.parked = true;
11624 state.config.graph.answer_timeout = 60;
11625 state.github_text = Some(crate::run::GithubTextAsk {
11626 rewrite: None,
11627 fingerprint: "f".into(),
11628 title: true,
11629 body: false,
11630 categories: vec!["title-language".into()],
11631 question: None,
11632 asks: 1,
11633 resolved: false,
11634 chosen_title: None,
11635 choice: None,
11636 publication: None,
11637 });
11638 state.save().unwrap();
11639 let store = ask::Questions::open();
11640 let mut q = ask::Question::new(
11641 state.id.clone(),
11642 crate::github_text::ASK_NODE.to_owned(),
11643 crate::github_text::ASK_SEAT.to_owned(),
11644 "s".into(),
11645 String::new(),
11646 vec!["use fallback".into()],
11647 );
11648 store.put(&mut q).unwrap();
11649 let mut t = task();
11650 t.runs.push(state.id.clone());
11651 assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
11652 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
11653 store.put(&mut q).unwrap();
11654 assert_eq!(land_resume_state(&t), LandResume::Ready);
11655 assert!(!store.get(&q.id).unwrap().status.open());
11656 state.github_text.as_mut().unwrap().resolved = true;
11658 state.save().unwrap();
11659 assert_eq!(land_resume_state(&t), LandResume::NotLanding);
11660 }
11661
11662 #[test]
11663 fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
11664 crate::run::pin_test_home();
11669 let mut state = run_state(RunStatus::Landing);
11670 state.id = "20260101-000000-exp1".to_owned();
11671 state.parked = true;
11672 state.config.graph.answer_timeout = 60;
11673 state.save().unwrap();
11674
11675 let store = ask::Questions::open();
11676 let mut q = approval_question(&state.id);
11677 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
11678 store.put(&mut q).unwrap();
11679
11680 let mut t = task();
11681 t.runs.push(state.id.clone());
11682 assert_eq!(
11683 land_resume_state(&t),
11684 LandResume::Ready,
11685 "an expired question must not be waited on forever"
11686 );
11687
11688 let after = store.get(&q.id).unwrap();
11689 assert!(
11690 !after.status.open(),
11691 "the question is abandoned, not silently ignored"
11692 );
11693 assert!(
11694 after.resolution().is_none(),
11695 "an abandoned question is not read as a decision"
11696 );
11697 }
11698
11699 #[test]
11700 fn reclaim_settles_a_running_task_against_its_last_run() {
11701 let mut t = task();
11702 t.start("20260904-000000-4043".to_owned());
11703 reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
11704 assert_eq!(
11705 t.status,
11706 TaskStatus::Done,
11707 "a run that actually finished must not stay `running` forever"
11708 );
11709 }
11710
11711 #[test]
11712 fn reclaim_preserves_dispatched_inquiries_until_a_committed_pass() {
11713 let dir = tempfile::tempdir().unwrap();
11714 let queue = Queue::at(dir.path().join("queue"));
11715 let mut task = task();
11716 let mut run = run_state(RunStatus::Blocked);
11717 run.reserve_under(dir.path()).unwrap();
11718 run.driver_exited = true;
11719 run.save_under(dir.path()).unwrap();
11720 queue.put(&mut task).unwrap();
11721 let stale = task.clone();
11722 task.resume_override = Some(crate::queue::OperatorResume {
11723 question_id: "pending-resume".into(),
11724 at: Timestamp::now(),
11725 conductor_rehold: None,
11726 forced: true,
11727 pinned_run: Some(run.id.clone()),
11728 });
11729 task.start(run.id.clone());
11730 queue.put(&mut task).unwrap();
11731 let mut recovered = queue.get(&task.id).unwrap();
11733 let disk = RunState::load_under(&run.id, dir.path()).unwrap();
11734 reclaim(&mut recovered, Some(disk), 2, "en");
11735 queue.put(&mut recovered).unwrap();
11736 assert!(recovered.resume_override.is_none());
11737 assert_eq!(
11738 recovered.dispatched_resumes.get("pending-resume"),
11739 Some(&run.id)
11740 );
11741 let mut stale = stale;
11742 queue.put(&mut stale).unwrap();
11743 assert_eq!(
11744 stale.dispatched_resumes, recovered.dispatched_resumes,
11745 "a stale task writer cannot erase dispatch ownership"
11746 );
11747 let mut resumed = RunState::load_under(&run.id, dir.path()).unwrap();
11748 assert!(resumed.decision_starts.is_empty());
11749 resumed.carry_dispatched_resumes(&queue.get(&task.id).unwrap());
11750 assert!(
11751 resumed.decision_starts.is_empty(),
11752 "handoff is not execution proof"
11753 );
11754 resumed.begin_pass();
11755 resumed.save_under(dir.path()).unwrap();
11756 let mut disk = RunState::load_under(&run.id, dir.path()).unwrap();
11757 assert_eq!(disk.decision_starts.get("pending-resume"), Some(&0));
11758 disk.carry_dispatched_resumes(&recovered);
11759 disk.begin_pass();
11760 assert_eq!(
11761 disk.decision_starts.get("pending-resume"),
11762 Some(&0),
11763 "later execution must preserve the original pass receipt"
11764 );
11765 }
11766
11767 #[test]
11768 fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
11769 let mut t = task();
11770 t.start("20260904-000000-4043".to_owned());
11771 t.last_error = Some("earlier trouble".to_owned());
11772 let mut state = run_state(RunStatus::Judging);
11773 state.parked = true;
11774 reclaim(&mut t, Some(state), 1, "en");
11775 assert_eq!(t.status, TaskStatus::Parked);
11776 assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
11777 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
11778 assert!(t.park_reason.is_some());
11779 assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
11780 assert!(!t.fresh_start);
11781 assert!(t.status.runnable());
11782 }
11783
11784 #[test]
11785 fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
11786 let mut t = task();
11787 t.start("20260904-000000-4043".to_owned());
11788 t.last_error = Some("earlier trouble".to_owned());
11789 settle(
11790 &mut t,
11791 Verdict {
11792 status: RunStatus::Judging,
11793 left_pr: false,
11794 quota_hit: false,
11795 parked: true,
11796 no_viable_candidates: false,
11797 },
11798 "parked after `judging`",
11799 1,
11800 );
11801 assert_eq!(t.status, TaskStatus::Parked);
11802 assert_eq!(t.attempts, 0);
11803 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
11804 assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
11805 assert_eq!(t.schema, crate::queue::SCHEMA);
11806 assert!(
11807 crate::notices::task_held(&t).is_none(),
11808 "a park is not news"
11809 );
11810 t.start("20260904-000000-4043".to_owned());
11811 assert_eq!(t.park_reason, None);
11812 }
11813
11814 #[test]
11815 fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
11816 let mut t = task();
11820 t.start("20260904-000000-4043".to_owned());
11821 reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
11822 assert_eq!(t.status, TaskStatus::Failed);
11823 assert!(t.status.runnable());
11824 }
11825
11826 #[test]
11827 fn a_settled_parked_pass_records_its_cause_and_the_refund() {
11828 let mut t = task();
11829 t.start("20260904-000000-4043".to_owned());
11830 assert_eq!(t.attempts, 1);
11831 let mut run = run_state(RunStatus::Implementing);
11832 run.id = "20260904-000000-4043".to_owned();
11833 run.begin_pass();
11834 let cause = crate::run::ParkCause::Upgrade {
11835 from: "0.121.0".to_owned(),
11836 to: Some("0.121.1".to_owned()),
11837 };
11838 run.end_pass_parked(cause.clone());
11839 run.parked = true;
11840 let verdict = Verdict {
11841 status: run.status,
11842 left_pr: false,
11843 quota_hit: false,
11844 parked: true,
11845 no_viable_candidates: false,
11846 };
11847 let mut orphan = t.clone();
11850 reclaim(&mut orphan, Some(run.clone()), 2, "en");
11851 assert_eq!(orphan.status, TaskStatus::Parked);
11852 assert_eq!(orphan.attempts, 0);
11853 assert_eq!(
11854 orphan.upgrade_resume_key(),
11855 Some((run.passes[0].started_at, orphan.id.as_str()))
11856 );
11857 settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
11858 assert_eq!(t.attempts, 0);
11859 assert_eq!(t.passes.len(), 1);
11860 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
11861 assert_eq!(t.passes[0].parked, Some(cause));
11862 assert_eq!(t.passes[0].pass_index, 0);
11863 assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
11864 assert!(t.upgrade_resume_key().is_some());
11865
11866 t.start("20260904-000000-4043".to_owned());
11869 run.begin_pass();
11870 run.status = RunStatus::Failed;
11871 let verdict = Verdict {
11872 status: RunStatus::Failed,
11873 left_pr: false,
11874 quota_hit: false,
11875 parked: false,
11876 no_viable_candidates: false,
11877 };
11878 settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
11879 assert_eq!(t.passes.len(), 2);
11880 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
11881 assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
11882 assert_eq!(t.passes[1].pass_index, 1);
11883 assert_eq!(t.attempts, 1);
11884 }
11885
11886 #[test]
11887 fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
11888 let mut t = task();
11889 t.start("20260904-000000-4043".to_owned());
11890 reclaim(&mut t, None, 2, "en");
11891 assert_eq!(t.status, TaskStatus::Held);
11892 assert!(
11893 t.last_error
11894 .as_deref()
11895 .is_some_and(|e| e.contains("running")),
11896 "the operator needs to know why this task was held"
11897 );
11898 }
11899
11900 #[test]
11901 fn sync_base_only_orphan_holds_without_replay_or_attempt_change() {
11902 let dir = tempfile::tempdir().unwrap();
11903 let queue = Queue::at(dir.path().to_path_buf());
11904 let mut task = task();
11905 let run = "20261124-000000-dead";
11906 task.link_run(run);
11907 task.attempts = 2;
11908 task.status = TaskStatus::Running;
11909 task.sync_only = Some(crate::base_sync_only::Request {
11910 run: run.into(),
11911 at: Timestamp::now(),
11912 });
11913 queue.put(&mut task).unwrap();
11914 assert_eq!(
11915 reclaim_orphaned_running(&queue, 3, &Default::default()),
11916 vec![task.id.clone()]
11917 );
11918 let saved = queue.get(&task.id).unwrap();
11919 assert_eq!(saved.status, TaskStatus::Held);
11920 assert_eq!(saved.attempts, 2);
11921 assert_eq!(saved.execution_runs(), [run]);
11922 assert!(
11923 saved
11924 .last_error
11925 .unwrap()
11926 .contains("verification was not allowed")
11927 );
11928 assert!(reclaim_orphaned_running(&queue, 3, &Default::default()).is_empty());
11929 }
11930
11931 #[test]
11932 fn sync_base_only_completed_orphan_holds_without_charging_or_double_refunding() {
11933 use crate::base_sync_only::{Outcome, Pass, Request};
11934
11935 let mut state = run_state(RunStatus::Blocked);
11936 let mut task = task();
11937 let request = Request {
11938 run: state.id.clone(),
11939 at: Timestamp::now(),
11940 };
11941 task.start(state.id.clone());
11942 task.sync_only = Some(request.clone());
11943 task.attempts = 2;
11945 let mut pass = Pass::new(request, &state);
11946 pass.result = Outcome::AlreadyCurrent;
11947 state.sync_only_passes.push(pass);
11948 state.begin_pass();
11949
11950 reclaim(&mut task, Some(state), 3, "en");
11951
11952 assert_eq!(task.status, TaskStatus::Held);
11953 assert_eq!(task.attempts, 2);
11954 assert!(task.sync_only.is_none());
11955 let detail = task.hold_reason.unwrap();
11956 assert!(detail.contains("HEAD already contains the base"));
11957 assert!(detail.contains("verification was not allowed"));
11958 }
11959
11960 #[test]
11961 fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
11962 let dir = tempfile::tempdir().unwrap();
11963 let queue = Queue::at(dir.path().to_path_buf());
11964
11965 let mut orphaned = task();
11967 orphaned.id = "20260904-000000-orph".to_owned();
11968 orphaned.status = TaskStatus::Running;
11969 orphaned.attempts = 1;
11970 queue.put(&mut orphaned).unwrap();
11971
11972 let mut alive = task();
11973 alive.id = "20260904-000000-live".to_owned();
11974 alive.status = TaskStatus::Running;
11975 alive.attempts = 1;
11976 queue.put(&mut alive).unwrap();
11977 let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
11978
11979 let mut queued = task();
11980 queued.id = "20260904-000000-wait".to_owned();
11981 queue.put(&mut queued).unwrap();
11982
11983 let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
11984 assert_eq!(reclaimed, vec![orphaned.id.clone()]);
11985
11986 assert_eq!(
11987 queue.get(&orphaned.id).unwrap().status,
11988 TaskStatus::Held,
11989 "nothing was driving it and there was no run to recover"
11990 );
11991 assert_eq!(
11992 queue.get(&alive.id).unwrap().status,
11993 TaskStatus::Running,
11994 "a live claim must protect the task it belongs to"
11995 );
11996 assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
11997 }
11998
11999 fn read_run_under(home: &Path, id: &str) -> RunState {
12005 let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
12006 serde_json::from_str(&body).unwrap()
12007 }
12008
12009 #[test]
12010 fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
12011 let dir = tempfile::tempdir().unwrap();
12012 let home = dir.path().to_path_buf();
12013 let now = Timestamp::now();
12014 let overrun_seat = || crate::run::ActiveSeat {
12015 node: "implement".to_owned(),
12016 started_at: now - jiff::SignedDuration::new(21_000, 0),
12017 timeout_secs: 3_600,
12018 attempt: 0,
12019 task: None,
12020 command: None,
12021 index: None,
12022 total: None,
12023 };
12024
12025 let mut dead = run_state(RunStatus::Implementing);
12026 dead.id = "20260101-000000-dead".to_owned();
12027 dead.active.insert("impl-A".to_owned(), overrun_seat());
12028 dead.driver_pid = Some(4242);
12031 dead.save_under(&home).unwrap();
12032
12033 let mut alive = run_state(RunStatus::Implementing);
12036 alive.id = "20260101-000000-aliv".to_owned();
12037 alive.active.insert("impl-A".to_owned(), overrun_seat());
12038 alive.save_under(&home).unwrap();
12039 let mut status = Status::new();
12040 status.current = vec![Current {
12041 worker: None,
12042 task: "20260101-000000-task".to_owned(),
12043 run: alive.id.clone(),
12044 }];
12045 write_status_to(&home.join("daemon.json"), &status).unwrap();
12046
12047 let questions = Questions::at(home.join("questions"));
12051 let mut q = ask::Question::new(
12052 dead.id.clone(),
12053 "implement".to_owned(),
12054 "impl-A".to_owned(),
12055 "Which storage backend?".to_owned(),
12056 String::new(),
12057 vec!["SQLite".to_owned(), "Redis".to_owned()],
12058 );
12059 questions.put(&mut q).unwrap();
12060
12061 let abandoned = reclaim_abandoned_runs_with(
12062 &home,
12063 now,
12064 |pid| if pid == 4242 { Some(false) } else { None },
12065 |_| panic!("a query answering Dead outright needs no identity corroboration"),
12066 );
12067 assert_eq!(abandoned, vec![dead.id.clone()]);
12068
12069 let reloaded = read_run_under(&home, &dead.id);
12070 assert_eq!(reloaded.status, RunStatus::Failed);
12071 assert!(reloaded.active.is_empty());
12072 assert!(
12073 !questions.get(&q.id).unwrap().status.open(),
12074 "the failed run's own open question must be settled in the same pass"
12075 );
12076
12077 let still_alive = read_run_under(&home, &alive.id);
12078 assert_eq!(
12079 still_alive.status,
12080 RunStatus::Implementing,
12081 "a live daemon's claim protects it"
12082 );
12083 assert!(!still_alive.active.is_empty());
12084 }
12085
12086 #[test]
12096 fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
12097 let dir = tempfile::tempdir().unwrap();
12098 let home = dir.path().to_path_buf();
12099 let now = Timestamp::now();
12100
12101 let mut manual = run_state(RunStatus::Reviewing);
12102 manual.id = "20260101-000000-manl".to_owned();
12103 manual.active.insert(
12104 "review-1".to_owned(),
12105 crate::run::ActiveSeat {
12106 node: "review".to_owned(),
12107 started_at: now - jiff::SignedDuration::new(21_000, 0),
12108 timeout_secs: 3_600,
12109 attempt: 0,
12110 task: None,
12111 command: None,
12112 index: None,
12113 total: None,
12114 },
12115 );
12116 manual.driver_pid = Some(4242);
12120 manual.driver_started_at = Some("1790000000".to_owned());
12121 manual.save_under(&home).unwrap();
12122
12123 let abandoned = reclaim_abandoned_runs_with(
12124 &home,
12125 now,
12126 |pid| if pid == 4242 { Some(true) } else { None },
12127 |pid| {
12128 if pid == 4242 {
12129 Some("1790000000".to_owned())
12130 } else {
12131 None
12132 }
12133 },
12134 );
12135 assert!(
12136 abandoned.is_empty(),
12137 "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
12138 );
12139
12140 let reloaded = read_run_under(&home, &manual.id);
12141 assert_eq!(reloaded.status, RunStatus::Reviewing);
12142 assert!(!reloaded.active.is_empty());
12143 }
12144
12145 #[test]
12146 fn an_already_claimed_task_is_skipped_rather_than_failed() {
12147 let dir = tempfile::tempdir().unwrap();
12148 let queue = Queue::at(dir.path().to_path_buf());
12149 let mut only = task();
12150 queue.put(&mut only).unwrap();
12151
12152 let _elsewhere = queue.claim(&only.id).unwrap();
12153 let candidates = runnable(&queue);
12154 assert_eq!(candidates.len(), 1, "the task is still runnable");
12155 assert!(
12156 queue.claim(&candidates[0].id).is_err(),
12157 "the loop cannot take a claim somebody else holds"
12158 );
12159
12160 let after = queue.get(&only.id).unwrap();
12161 assert_eq!(after.status, TaskStatus::Queued);
12162 assert_eq!(
12163 after.attempts, 0,
12164 "losing the race is not an attempt at the task"
12165 );
12166 assert_eq!(after.last_error, None);
12167 }
12168
12169 #[test]
12170 fn the_status_file_round_trips_and_its_heartbeat_advances() {
12171 let dir = tempfile::tempdir().unwrap();
12172 let path = dir.path().join("daemon.json");
12173
12174 let mut status = Status::new();
12175 status.idle = false;
12176 status.completed = 7;
12177 status.current = vec![Current {
12178 worker: None,
12179 task: "20260902-000000-t111".to_owned(),
12180 run: "20260902-000001-r111".to_owned(),
12181 }];
12182 write_status_to(&path, &status).unwrap();
12183 let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
12184 assert_eq!(first.schema, SCHEMA);
12185 assert_eq!(first.pid, std::process::id());
12186 assert!(!first.idle);
12187 assert_eq!(first.completed, 7);
12188 assert_eq!(first.current, status.current);
12189 assert!(
12190 !path.with_extension("json.tmp").exists(),
12191 "the temp file is renamed, not left behind"
12192 );
12193
12194 std::thread::sleep(Duration::from_millis(5));
12195 status.updated_at = Timestamp::now();
12196 status.polls = 3;
12197 write_status_to(&path, &status).unwrap();
12198 let second: Status =
12199 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
12200 assert!(
12201 second.updated_at > first.updated_at,
12202 "a reader can only detect staleness if the heartbeat moves"
12203 );
12204 assert_eq!(
12205 second.started_at, first.started_at,
12206 "the start time is not a heartbeat"
12207 );
12208 assert_eq!(second.polls, 3);
12209 }
12210
12211 #[test]
12212 fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
12213 let dir = tempfile::tempdir().unwrap();
12214
12215 assert!(read_status(dir.path()).is_none(), "no file, no daemon");
12216
12217 let mut status = Status::new();
12218 status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
12219 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12220 let stale = read_status(dir.path()).unwrap();
12221 assert!(
12222 !stale.running(Timestamp::now()),
12223 "a minute without a heartbeat is a dead daemon, not a busy one"
12224 );
12225 assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
12226
12227 status.updated_at = Timestamp::now();
12228 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12229 let fresh = read_status(dir.path()).unwrap();
12230 assert!(fresh.running(Timestamp::now()));
12231 }
12232
12233 #[test]
12234 fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
12235 let dir = tempfile::tempdir().unwrap();
12236 let now = Timestamp::now();
12237 let mine = "20260903-080619-01c2";
12238
12239 assert!(
12240 !is_working_on(dir.path(), mine, now),
12241 "no status file means nobody is working on anything"
12242 );
12243
12244 let mut status = Status::new();
12245 status.current = vec![Current {
12246 worker: None,
12247 task: "20260903-080340-0167".to_owned(),
12248 run: mine.to_owned(),
12249 }];
12250 status.updated_at = now;
12251 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12252 assert!(is_working_on(dir.path(), mine, now));
12253 assert!(
12254 !is_working_on(dir.path(), "20260903-105039-3cbf", now),
12255 "a daemon busy with one run is not working on another"
12256 );
12257
12258 status.updated_at = now - jiff::SignedDuration::from_secs(600);
12261 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12262 assert!(
12263 !is_working_on(dir.path(), mine, now),
12264 "a stale heartbeat is a dead daemon, so its run is a leftover"
12265 );
12266 }
12267
12268 #[test]
12269 fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
12270 let dir = tempfile::tempdir().unwrap();
12271 let now = Timestamp::now();
12272
12273 assert!(
12274 !is_working_on_short(dir.path(), "01c2", now),
12275 "no status file means nobody is working on anything"
12276 );
12277
12278 let mut status = Status::new();
12279 status.current = vec![Current {
12280 worker: None,
12281 task: "20260903-080340-0167".to_owned(),
12282 run: "20260903-080619-01c2".to_owned(),
12283 }];
12284 status.updated_at = now;
12285 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12286 assert!(
12287 is_working_on_short(dir.path(), "01c2", now),
12288 "the run's short id is the last block of its full id"
12289 );
12290 assert!(
12291 !is_working_on_short(dir.path(), "3cbf", now),
12292 "a daemon busy with one worktree bay is not working on another"
12293 );
12294 }
12295
12296 #[test]
12297 fn a_newer_status_file_still_yields_a_reading() {
12298 let dir = tempfile::tempdir().unwrap();
12299 std::fs::write(
12302 dir.path().join("daemon.json"),
12303 serde_json::json!({
12304 "schema": 2,
12305 "updated_at": Timestamp::now().to_string(),
12306 "idle": true,
12307 "surprise": { "nested": [1, 2, 3] },
12308 })
12309 .to_string(),
12310 )
12311 .unwrap();
12312
12313 let reading = read_status(dir.path()).expect("a forward-compatible read");
12314 assert!(reading.running(Timestamp::now()));
12315 assert!(reading.idle);
12316 assert!(reading.current.is_empty());
12317 }
12318
12319 #[test]
12320 fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
12321 let dir = tempfile::tempdir().unwrap();
12327 std::fs::write(
12328 dir.path().join("daemon.json"),
12329 serde_json::json!({
12330 "schema": 1,
12331 "pid": 4242,
12332 "updated_at": Timestamp::now().to_string(),
12333 "idle": false,
12334 "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
12335 "completed": 3,
12336 "polls": 9,
12337 })
12338 .to_string(),
12339 )
12340 .unwrap();
12341
12342 let reading = read_status(dir.path()).expect("an older shape must still parse");
12343 assert!(reading.running(Timestamp::now()));
12344 assert_eq!(
12345 reading.current,
12346 vec![Current {
12347 worker: None,
12348 task: "20260902-140501-aaaa".to_owned(),
12349 run: "20260902-140502-bbbb".to_owned(),
12350 }]
12351 );
12352 }
12353
12354 #[test]
12355 fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
12356 let dir = tempfile::tempdir().unwrap();
12357 std::fs::write(
12358 dir.path().join("daemon.json"),
12359 serde_json::json!({
12360 "schema": 1,
12361 "updated_at": Timestamp::now().to_string(),
12362 "idle": true,
12363 "current": null,
12364 })
12365 .to_string(),
12366 )
12367 .unwrap();
12368 let with_null = read_status(dir.path()).expect("null must still parse");
12369 assert!(with_null.current.is_empty());
12370
12371 std::fs::write(
12372 dir.path().join("daemon.json"),
12373 serde_json::json!({
12374 "schema": 1,
12375 "updated_at": Timestamp::now().to_string(),
12376 "idle": true,
12377 })
12378 .to_string(),
12379 )
12380 .unwrap();
12381 let absent = read_status(dir.path()).expect("a missing field must still parse");
12382 assert!(absent.current.is_empty());
12383 }
12384
12385 #[test]
12386 fn a_task_without_a_repository_runs_in_the_daemons_default() {
12387 let fallback = Path::new("/default");
12388 let mut blank = task();
12389 blank.repo = PathBuf::new();
12390 assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
12391 let mut dot = task();
12392 dot.repo = PathBuf::from(".");
12393 assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
12394 assert_eq!(
12395 repo_for(&task(), fallback),
12396 PathBuf::from("/repo"),
12397 "a task that names a repository keeps it"
12398 );
12399 }
12400
12401 #[test]
12402 fn new_tasks_inherit_the_daemon_build_cache_but_historical_tasks_remain_shared() {
12403 let dir = tempfile::tempdir().unwrap();
12404 let repo = dir.path();
12405 let path = repo.join("explicit.toml");
12406 std::fs::write(
12407 &path,
12408 "[verify]\nbuild_cache = 'isolated'\n[graph]\njudges = 1\n",
12409 )
12410 .unwrap();
12411 let opts = Opts {
12412 config: Some(path),
12413 ..Opts::default()
12414 };
12415 let queue = Queue::at(repo.join("queue"));
12416 let mut new = task();
12417 queue.put(&mut new).unwrap();
12418 let resolved = |task: &Task| prepare_for(repo, &opts, task).unwrap();
12419 assert_eq!(
12420 resolved(&queue.get(&new.id).unwrap()).verify.build_cache,
12421 BuildCache::Isolated
12422 );
12423
12424 let mut old = task();
12425 old.schema = 22;
12426 queue.put(&mut old).unwrap();
12427 let mut old = queue.get(&old.id).unwrap();
12428 let config = resolved(&old);
12429 assert_eq!(config.verify.build_cache, BuildCache::Shared);
12430 assert_eq!(config.graph.judges, 1, "preserve daemon config inheritance");
12431 old.hold_manual(Some("wait".into()));
12432 queue.put(&mut old).unwrap();
12433
12434 let mut saved = queue.get(&old.id).unwrap();
12435 assert_eq!(resolved(&saved).verify.build_cache, BuildCache::Shared);
12436 saved
12437 .overrides
12438 .as_mut()
12439 .unwrap()
12440 .merge_over(&crate::queue::RunOverrides {
12441 build_cache: Some(BuildCache::Isolated),
12442 ..Default::default()
12443 });
12444 queue.put(&mut saved).unwrap();
12445 assert_eq!(
12446 resolved(&queue.get(&saved.id).unwrap()).verify.build_cache,
12447 BuildCache::Isolated
12448 );
12449 }
12450
12451 #[test]
12452 fn urgent_build_cache_precedes_config_but_not_an_explicit_choice() {
12453 let dir = tempfile::tempdir().unwrap();
12454 let path = dir.path().join("explicit.toml");
12455 let write = |verify: &str| {
12456 std::fs::write(&path, format!("[verify]\nbuild_cache = 'shared'\n{verify}")).unwrap();
12457 };
12458 write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test\"]\n");
12459 let opts = Opts {
12460 config: Some(path.clone()),
12461 ..Opts::default()
12462 };
12463 let mut task = task();
12464 task.set_urgent(true).unwrap();
12465 let resolved = |task: &Task| {
12466 prepare_for(dir.path(), &opts, task)
12467 .unwrap()
12468 .verify
12469 .build_cache
12470 };
12471 assert_eq!(resolved(&task), BuildCache::Isolated);
12472 task.change_build_cache(Some(BuildCache::Shared)).unwrap();
12473 assert_eq!(resolved(&task), BuildCache::Shared);
12474 task.change_build_cache(None).unwrap();
12475 assert_eq!(resolved(&task), BuildCache::Isolated);
12476 task.set_urgent(false).unwrap();
12477 assert_eq!(resolved(&task), BuildCache::Shared);
12478
12479 task.set_urgent(true).unwrap();
12483 write("e2e = [\"npm test\"]\n");
12484 assert_eq!(resolved(&task), BuildCache::Shared);
12485 write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test | tee log\"]\n");
12486 assert_eq!(resolved(&task), BuildCache::Shared);
12487 task.change_build_cache(Some(BuildCache::Isolated)).unwrap();
12489 assert_eq!(resolved(&task), BuildCache::Isolated);
12490 }
12491
12492 #[test]
12493 fn task_implementers_edit_inherits_daemon_config_and_merge() {
12494 let dir = tempfile::tempdir().unwrap();
12495 let path = dir.path().join("explicit.toml");
12496 std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
12497 let opts = Opts {
12498 config: Some(path),
12499 merge: Some("none".into()),
12500 ..Default::default()
12501 };
12502 let mut t = task();
12503 t.set_implementers(
12504 2,
12505 &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
12506 .unwrap(),
12507 )
12508 .unwrap();
12509 let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
12510 assert_eq!(cfg.graph.implementers, 2);
12511 assert_eq!(cfg.graph.judges, 1);
12512 assert_eq!(cfg.merge.mode, MergeMode::None);
12513 t.set_implementers(1, &cfg).unwrap();
12514 let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
12515 apply_task_implementers(&mut cfg, &t);
12516 assert_eq!(cfg.graph.implementers, 1);
12517 assert_eq!(cfg.graph.judges, 1);
12518 assert_eq!(cfg.merge.mode, MergeMode::None);
12519 }
12520
12521 #[test]
12522 fn task_implementers_direct_overrides_stay_isolated_after_edits() {
12523 let dir = tempfile::tempdir().unwrap();
12524 let repo = dir.path().join("repo");
12525 std::fs::create_dir(&repo).unwrap();
12526 std::fs::write(
12527 repo.join("magi.toml"),
12528 "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
12529 )
12530 .unwrap();
12531 let daemon_config = dir.path().join("daemon.toml");
12532 std::fs::write(
12533 &daemon_config,
12534 "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
12535 )
12536 .unwrap();
12537 let opts = Opts {
12538 config: Some(daemon_config),
12539 merge: Some("pr".into()),
12540 ..Default::default()
12541 };
12542 let q = Queue::at(dir.path().join("queue"));
12543 let validation: Config =
12544 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
12545 .unwrap();
12546 for record in ["{}", r#"{"candidates":2}"#] {
12548 let overrides = serde_json::from_str(record).unwrap();
12549 let filing = crate::direct::Filing {
12550 instruction: "work".into(),
12551 title: "direct".into(),
12552 repo: repo.clone(),
12553 source: crate::queue::Source::Human,
12554 issue: None,
12555 solo: false,
12556 overrides,
12557 review_of: None,
12558 sources: Default::default(),
12559 };
12560 let filed =
12561 crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
12562 let crate::direct::Filed::Standalone {
12563 mut task,
12564 claim: _claim,
12565 } = filed
12566 else {
12567 panic!("local filing")
12568 };
12569 let before = prepare_for(&repo, &opts, &task).unwrap();
12570 assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
12571 assert_eq!(
12572 before.merge.mode,
12573 MergeMode::None,
12574 "daemon --merge must not leak"
12575 );
12576 for n in [2, 1, 2] {
12577 task.set_implementers(n, &validation).unwrap();
12578 q.put(&mut task).unwrap();
12579 task = q.get(&task.id).unwrap();
12580 assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
12581 let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
12582 apply_task_implementers(&mut cfg, &task);
12583 assert_eq!(cfg.graph.implementers, usize::from(n));
12584 assert_eq!(cfg.graph.judges, 2);
12585 assert_eq!(cfg.merge.mode, MergeMode::None);
12586 }
12587 }
12588 }
12589
12590 #[test]
12591 fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
12592 let cfg: Config =
12593 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
12594 .unwrap();
12595 let mut t = task();
12596 t.review_of = Some("review-target".into());
12597 t.hold_manual(Some("retry".into()));
12598 let mut previous = RunState::new(
12599 PathBuf::from("/repo"),
12600 "main".into(),
12601 "abc1234".into(),
12602 "review".into(),
12603 cfg.clone(),
12604 );
12605 previous.config.graph.implementers = 2;
12606 for count in [1, 3] {
12607 t.set_implementers(count, &cfg).unwrap();
12608 t.release();
12609 assert_eq!(t.review_of.as_deref(), Some("review-target"));
12610 for proposed in [
12611 Starter::Resume(previous.id.clone()),
12612 Starter::Review("recovery-target".into()),
12613 ] {
12614 assert_eq!(
12615 starter_with_implementers(&t, Some(&previous), proposed),
12616 Starter::Review("review-target".into())
12617 );
12618 }
12619 let mut configured = cfg.clone();
12620 apply_task_implementers(&mut configured, &t);
12621 assert_eq!(configured.graph.implementers, usize::from(count));
12622 assert_eq!(previous.config.graph.implementers, 2);
12623 }
12624 }
12625
12626 #[test]
12627 fn task_implementers_dispatch_and_resume_agree() {
12628 let mut t = task();
12629 let cfg: crate::config::Config =
12630 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
12631 .unwrap();
12632 let mut run = RunState::new(
12633 PathBuf::from("/repo"),
12634 "main".into(),
12635 "abc1234".into(),
12636 "work".into(),
12637 cfg.clone(),
12638 );
12639 run.config.graph.implementers = 2;
12640 for n in [2, 1, 3, 2] {
12641 t.set_implementers(n, &cfg).unwrap();
12642 let mut dispatched = cfg.clone();
12643 apply_task_implementers(&mut dispatched, &t);
12644 assert_eq!(dispatched.graph.implementers, usize::from(n));
12645 assert_eq!(implementers_match(&t, &run), n == 2);
12646 for proposed in [
12647 Starter::Resume(run.id.clone()),
12648 Starter::Review("old-branch".into()),
12649 ] {
12650 let expected = if n == 2 {
12651 proposed.clone()
12652 } else {
12653 Starter::Start
12654 };
12655 assert_eq!(
12656 starter_with_implementers(&t, Some(&run), proposed),
12657 expected
12658 );
12659 }
12660 assert_eq!(
12661 run.config.graph.implementers, 2,
12662 "history must not be rewritten"
12663 );
12664 }
12665 t.solo = false;
12666 t.overrides = None;
12667 assert!(implementers_match(&t, &run));
12668 }
12669
12670 #[test]
12671 fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
12672 let mut solo_cfg = Config::default();
12678 solo_cfg.graph.implementers = 3;
12679 let mut solo_task = task();
12680 solo_task.solo = true;
12681 apply_task_implementers(&mut solo_cfg, &solo_task);
12682 assert_eq!(solo_cfg.graph.implementers, 1);
12683
12684 let mut plain_cfg = Config::default();
12685 plain_cfg.graph.implementers = 3;
12686 let plain_task = task();
12687 assert!(!plain_task.solo);
12688 apply_task_implementers(&mut plain_cfg, &plain_task);
12689 assert_eq!(
12690 plain_cfg.graph.implementers, 3,
12691 "a task that did not ask to run alone keeps the config's candidates"
12692 );
12693 }
12694
12695 fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
12696 QuotaLoss {
12697 cause: crate::agent::QuotaCause::UsageLimit,
12698 agent: String::new(),
12699 seat: seat.into(),
12700 node: "judge".into(),
12701 at: at.parse().unwrap(),
12702 reset: reset.map(str::to_string),
12703 }
12704 }
12705
12706 #[test]
12707 fn authentication_losses_never_arm_a_cooldown_even_with_reset_hints() {
12708 let now = Timestamp::now();
12709 for reset in [None, Some("in 1h")] {
12710 let auth = crate::agent::Quota {
12711 cause: crate::agent::QuotaCause::Authentication,
12712 agent: "alpha".into(),
12713 reset: reset.map(str::to_owned),
12714 };
12715 let loss = QuotaLoss::from_report("advisor-1".into(), "advise", Some(&auth));
12716 assert_eq!(cooldown_until(&[loss], now), None);
12717 }
12718 }
12719
12720 #[test]
12721 fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
12722 let old: Vec<QuotaLoss> = (1..=4)
12723 .map(|i| {
12724 loss(
12725 &format!("judge-{i}"),
12726 "2026-09-23T05:23:00Z",
12727 Some("2:40pm (Asia/Tokyo)"),
12728 )
12729 })
12730 .collect();
12731 let fresh = losses_this_attempt(&old, &old);
12732 assert!(fresh.is_empty());
12733 assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
12734 }
12736
12737 #[test]
12738 fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
12739 let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
12740 let now = Timestamp::now();
12741 let mut after = old.clone();
12742 after.push(loss("judge-2", &now.to_string(), None));
12743 let fresh = losses_this_attempt(&old, &after);
12744 assert_eq!(fresh, vec![after[1].clone()]);
12745 let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
12746 assert_eq!(
12747 until,
12748 now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
12749 );
12750 }
12751
12752 #[test]
12753 fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
12754 let before = vec![
12757 loss("judge-1", "2026-09-23T05:23:00Z", None),
12758 loss("judge-2", "2026-09-23T05:24:00Z", None),
12759 ];
12760 let after = vec![
12761 loss("judge-2", "2026-09-23T05:24:00Z", None),
12762 loss("judge-1", "2026-09-24T01:00:00Z", None),
12763 ];
12764 assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
12765 }
12766
12767 #[test]
12768 fn merge_overrides_are_parsed_or_refused() {
12769 assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
12770 assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
12771 assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
12772 assert!(merge_mode("squash").is_err());
12773 }
12774
12775 #[test]
12776 fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
12777 let now = Timestamp::now();
12778 let fallback = Duration::from_secs(300);
12779 let cap = Duration::from_secs(1800);
12780
12781 assert_eq!(quota_wait(None, now, fallback, cap), fallback);
12783
12784 let soon = now + jiff::SignedDuration::from_secs(600);
12786 assert_eq!(
12787 quota_wait(Some(soon), now, fallback, cap),
12788 Duration::from_secs(600)
12789 );
12790
12791 let past = now - jiff::SignedDuration::from_secs(60);
12794 assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
12795
12796 let far = now + jiff::SignedDuration::from_secs(3 * 3600);
12799 assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
12800 }
12801
12802 #[test]
12803 fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
12804 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
12805
12806 let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
12807 assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
12808
12809 let already_past =
12813 parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
12814 assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
12815
12816 assert!(
12817 parse_reset_hint("session limit reached", now, now).is_none(),
12818 "free text with no recognised shape is not guessed at"
12819 );
12820 assert!(
12821 parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
12822 "an unresolvable zone name is not guessed at either"
12823 );
12824 }
12825
12826 #[test]
12827 fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
12828 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
12829
12830 let at = parse_reset_hint(
12831 "You've hit your usage limit. Visit \
12832 https://chatgpt.com/codex/settings/usage to purchase more \
12833 credits or try again at Sep 19th, 2026 5:10 PM.",
12834 now,
12835 now,
12836 )
12837 .expect("the codex reset wording is a recognised shape");
12838 assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
12839
12840 let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
12845 .expect("an explicit year needs no rollover");
12846 assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
12847
12848 assert!(
12849 parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
12850 "a two-digit year is not the documented shape and is not guessed at"
12851 );
12852 assert!(
12853 parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
12854 "a four-letter month name is not the documented three-letter abbreviation"
12855 );
12856 assert!(
12857 parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
12858 "an explicit zone on the dated shape is a format nobody has \
12859 documented, and is refused rather than guessed at as UTC"
12860 );
12861 }
12862
12863 #[test]
12864 fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
12865 let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
12866 let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
12867
12868 let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
12869 assert_eq!(at.as_second() - recorded.as_second(), 3769);
12870
12871 let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
12872 assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
12873
12874 for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
12875 assert!(
12876 parse_reset_hint(bad, now, recorded).is_none(),
12877 "{bad:?} must not be guessed at"
12878 );
12879 }
12880 }
12881
12882 fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
12886 let config = dir.join("magi.toml");
12887 std::fs::write(
12888 &config,
12889 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
12890 )
12891 .unwrap();
12892 let opts = Opts {
12893 poll: Duration::from_secs(30),
12894 config: Some(config),
12895 repo: dir.join("repo"),
12899 ..Opts::default()
12900 };
12901 let home = dir.join("home");
12910 let stamps = home.join("service-ticks");
12913 std::fs::create_dir_all(&stamps).unwrap();
12914 for service in ["waiter", "deputies", "release-watch"] {
12915 std::fs::write(
12916 stamps.join(service),
12917 Timestamp::now().as_second().to_string(),
12918 )
12919 .unwrap();
12920 }
12921 for operation in [
12922 "conductor",
12923 "maintenance",
12924 "housekeeping",
12925 "disk-pressure",
12926 "fold",
12927 "cache",
12928 "fetch",
12929 "chat-goals",
12930 "decisions",
12931 ] {
12932 std::fs::write(
12933 stamps.join(format!("daemon-{operation}")),
12934 serde_json::to_vec(&Timestamp::now()).unwrap(),
12935 )
12936 .unwrap();
12937 }
12938 let worktrees = dir.join("wt");
12939 (
12940 opts,
12941 Queue::at(dir.join("queue")),
12942 home.join("daemon.json"),
12943 home,
12944 worktrees,
12945 )
12946 }
12947
12948 #[tokio::test]
12949 async fn disk_wait_maintenance_recovers_while_another_task_is_running() {
12950 let dir = tempfile::tempdir().unwrap();
12951 let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
12952 let mut waiting = task();
12953 waiting.repo = opts.repo.clone();
12954 waiting.hold_machine(crate::disk::gate(1, 100));
12955 waiting.mark_disk_capacity();
12956 waiting.attempts = 2;
12957 queue.put(&mut waiting).unwrap();
12958 let mut busy = task();
12959 busy.status = TaskStatus::Running;
12960 queue.put(&mut busy).unwrap();
12961 let payload = serde_json::to_value(ServiceWorker {
12962 opts,
12963 queue: queue.root().to_owned(),
12964 worktrees_root: worktrees,
12965 operation: "maintenance".into(),
12966 })
12967 .unwrap();
12968 run_service_worker(&home, payload.clone()).await.unwrap();
12969 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Queued);
12970 assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
12971 assert_eq!(queue.get(&busy.id).unwrap().status, TaskStatus::Running);
12972 run_service_worker(&home, payload).await.unwrap();
12973 assert!(
12974 crate::worker::active(&home).unwrap().is_empty(),
12975 "monitoring only queues; normal dispatch owns launches"
12976 );
12977 assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
12978 }
12979
12980 #[tokio::test]
12981 async fn source_eviction_service_receipts_explain_idle_and_active_skips() {
12982 let dir = tempfile::tempdir().unwrap();
12983 let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
12984 let cfg = Config::default();
12985 start_service(
12986 &home,
12987 &opts,
12988 &queue,
12989 &worktrees,
12990 "housekeeping",
12991 Some(&cfg),
12992 true,
12993 )
12994 .await
12995 .unwrap();
12996 let receipt = home.join("source-eviction-housekeeping-dispatch.json");
12997 let read = |path: &Path| -> serde_json::Value {
12998 serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap()
12999 };
13000 assert_eq!(read(&receipt)["detail"], "cadence not due");
13001 std::fs::remove_file(home.join("service-ticks/daemon-housekeeping")).unwrap();
13002 start_service(
13003 &home,
13004 &opts,
13005 &queue,
13006 &worktrees,
13007 "housekeeping",
13008 Some(&cfg),
13009 true,
13010 )
13011 .await
13012 .unwrap();
13013 assert_eq!(
13014 read(&receipt)["detail"],
13015 "active work or runnable task queue"
13016 );
13017 assert_eq!(read(&receipt)["version"], env!("CARGO_PKG_VERSION"));
13018 assert_eq!(read(&receipt)["auto_fold"], cfg.disk.auto_fold);
13019 std::fs::remove_file(home.join("service-ticks/daemon-disk-pressure")).unwrap();
13020 start_service(
13021 &home,
13022 &opts,
13023 &queue,
13024 &worktrees,
13025 "disk-pressure",
13026 Some(&cfg),
13027 false,
13028 )
13029 .await
13030 .unwrap();
13031 assert_eq!(
13032 read(&home.join("source-eviction-disk-pressure-dispatch.json"))["detail"],
13033 "no active work; idle housekeeping owns scan"
13034 );
13035 assert!(crate::worker::active(&home).unwrap().is_empty());
13036 }
13037
13038 #[test]
13043 fn the_fold_turn_is_admitted_exactly_where_housekeeping_is_not() {
13044 let on = Config::default();
13045 for busy in [false, true] {
13046 for runnable in [false, true] {
13047 assert_ne!(
13048 housekeeping_eligible(busy, runnable),
13049 fold_turn_eligible(busy, runnable, Some(&on)),
13050 "busy={busy} runnable={runnable}"
13051 );
13052 }
13053 }
13054 assert!(!housekeeping_eligible(true, true), "the 1275 machine");
13055 assert!(!fold_turn_eligible(true, true, None));
13056 let mut off = Config::default();
13057 off.disk.auto_fold = false;
13058 assert!(!fold_turn_eligible(true, true, Some(&off)));
13059 assert!(fold_turn_eligible(true, true, Some(&Config::default())));
13060 }
13061
13062 #[tokio::test]
13063 async fn the_fold_service_says_why_it_skipped_a_dispatch() {
13064 let dir = tempfile::tempdir().unwrap();
13065 let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
13066 let read = || -> serde_json::Value {
13067 serde_json::from_slice(
13068 &std::fs::read(home.join("source-eviction-fold-dispatch.json")).unwrap(),
13069 )
13070 .unwrap()
13071 };
13072 let tick = home.join("service-ticks/daemon-fold");
13073 let cfg = Config::default();
13074 let dispatch = |busy: bool, cfg: Config| {
13075 let (home, opts, queue, worktrees) = (&home, &opts, &queue, &worktrees);
13076 async move {
13077 start_service(home, opts, queue, worktrees, "fold", Some(&cfg), busy)
13078 .await
13079 .unwrap();
13080 }
13081 };
13082 dispatch(true, cfg.clone()).await;
13083 assert_eq!(read()["detail"], "cadence not due");
13084
13085 std::fs::remove_file(&tick).unwrap();
13086 dispatch(false, cfg.clone()).await;
13087 assert_eq!(
13088 read()["detail"],
13089 "idle machine; housekeeping owns finished-run folding"
13090 );
13091 let mut off = cfg.clone();
13092 off.disk.auto_fold = false;
13093 dispatch(true, off).await;
13094 assert_eq!(read()["detail"], "auto_fold disabled");
13095 start_service(&home, &opts, &queue, &worktrees, "fold", None, true)
13097 .await
13098 .unwrap();
13099 assert_eq!(read()["detail"], "startup configuration unavailable");
13100
13101 let directory = home.join("workers/jobs/abcdef");
13103 std::fs::create_dir_all(&directory).unwrap();
13104 let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
13105 crate::pr_head::try_lock_file(&lease).unwrap();
13106 let mut job = crate::worker::Job {
13107 id: "abcdef".into(),
13108 sequence: 1,
13109 kind: "daemon-service".into(),
13110 key: "service:daemon-housekeeping".into(),
13111 payload: serde_json::Value::Null,
13112 generation: "fixture".into(),
13113 version: None,
13114 status: crate::worker::Status::Running,
13115 result: None,
13116 pid: Some(std::process::id()),
13117 created_at: Timestamp::now().as_second() as u64,
13118 finished_at: None,
13119 };
13120 let record = directory.join("job.json");
13121 std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
13122 dispatch(true, cfg).await;
13123 assert_eq!(
13124 read()["detail"],
13125 "another finished-run folding service is active"
13126 );
13127 assert_eq!(crate::worker::active(&home).unwrap().len(), 1);
13128 job.status = crate::worker::Status::Finished;
13129 std::fs::write(record, serde_json::to_vec(&job).unwrap()).unwrap();
13130 drop(lease);
13131 }
13132
13133 #[tokio::test]
13141 async fn the_scheduler_folds_a_merged_run_beside_a_busy_worker_and_a_runnable_task() {
13142 let dir = tempfile::tempdir().unwrap();
13143 let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
13144 let repo = dir.path().join("checkout");
13145 std::fs::create_dir_all(&repo).unwrap();
13146 crate::clean::tests::init_repo(&repo);
13147 std::fs::write(
13148 opts.config.as_ref().unwrap(),
13149 "[disk]\nmin_free_bytes = 0\nauto_fold = true\ncache_limit_bytes = 0\n",
13150 )
13151 .unwrap();
13152 let (id, historical) = crate::clean::tests::merged_run_with_worktree(
13153 &home,
13154 &repo,
13155 &worktrees,
13156 "20260801-000000-s001",
13157 )
13158 .await;
13159 let active = dir.path().join("active");
13160 crate::git::worktree_add_branch(&repo, &active, "magi/active", "main")
13161 .await
13162 .unwrap();
13163 let (owned_id, owned_worktree) = crate::clean::tests::due_run_with_winner_worktree(
13168 &home.join("runs"),
13169 &worktrees,
13170 &repo,
13171 "20260801-000000-s002",
13172 RunStatus::Superseded,
13173 )
13174 .await;
13175 let owned_run = home.join("runs").join(&owned_id);
13176 let owned_record = std::fs::read(owned_run.join("run.json")).unwrap();
13177 let mut busy = task();
13178 busy.repo = repo.clone();
13179 busy.status = TaskStatus::Running;
13180 busy.link_run(&owned_id);
13181 queue.put(&mut busy).unwrap();
13182 let worker_lease = crate::worker::running_fixture(
13183 &home,
13184 &format!("task:{}", busy.id),
13185 serde_json::to_value(TaskWorker {
13186 opts: Opts::default(),
13187 queue: queue.root().to_owned(),
13188 task: busy.id.clone(),
13189 lane: PermitKind::default(),
13190 standalone: true,
13191 })
13192 .unwrap(),
13193 )
13194 .unwrap();
13195 let execution = crate::driver::maintenance(&home, &owned_id).unwrap();
13196 let mut waiting = task();
13197 waiting.repo = repo.clone();
13198 queue.put(&mut waiting).unwrap();
13199 std::fs::remove_file(home.join("service-ticks/daemon-fold")).unwrap();
13200
13201 let mut cfg = Config::default();
13202 cfg.disk.auto_fold = true;
13203 INLINE_SERVICES.with(|inline| inline.set(true));
13204 let status = Arc::new(Mutex::new(Status::new()));
13205 let stop = Stop::new();
13206 let mut dispatch = Box::pin(poll(
13207 &opts,
13208 &queue,
13209 &status,
13210 &home,
13211 &worktrees,
13212 &stop,
13213 DispatchLimits {
13214 max_concurrent: 0,
13215 pause_for_interrupts: false,
13216 recovery_cfg: Some(cfg),
13217 },
13218 ));
13219 let receipt = home.join("source-eviction-fold-worker.json");
13220 let completed = async {
13221 loop {
13222 let done = std::fs::read(&receipt)
13223 .ok()
13224 .and_then(|body| serde_json::from_slice::<serde_json::Value>(&body).ok())
13225 .is_some_and(|receipt| receipt["outcome"] == "completed");
13226 if done {
13227 break;
13228 }
13229 tokio::time::sleep(Duration::from_millis(25)).await;
13230 }
13231 };
13232 tokio::select! {
13233 result = &mut dispatch => panic!("the scheduler stopped before the fold service ran: {result:?}"),
13234 result = tokio::time::timeout(Duration::from_secs(120), completed) => {
13235 result.expect("the scheduler never admitted the fold service");
13236 }
13237 }
13238 stop.stop();
13239 dispatch.await.unwrap();
13240 INLINE_SERVICES.with(|inline| inline.set(false));
13241
13242 assert!(!historical.exists(), "the merged run's worktree is folded");
13243 assert!(
13244 active.join("README.md").is_file(),
13245 "the repository's active checkout is untouched"
13246 );
13247 let run = home.join("runs").join(&id);
13248 assert!(run.join("run.json").is_file());
13249 assert!(run.join("artifacts/fold-evidence/manifest.json").is_file());
13250 let read = |name: &str| -> serde_json::Value {
13251 serde_json::from_slice(&std::fs::read(home.join(name)).unwrap()).unwrap()
13252 };
13253 assert_eq!(
13254 read("source-eviction-fold-dispatch.json")["detail"],
13255 "eligible and cadence due"
13256 );
13257 let worker = read("source-eviction-fold-worker.json");
13258 assert_eq!(worker["fold"]["records"], 2);
13259 assert_eq!(worker["fold"]["folded"], 1);
13260 assert_eq!(worker["fold"]["invoked"], 1);
13261 assert_eq!(
13262 worker["fold"]["live"], 1,
13263 "the busy worker's own run is left alone: {worker}"
13264 );
13265 assert!(owned_worktree.exists());
13268 assert_eq!(
13269 std::fs::read(owned_run.join("run.json")).unwrap(),
13270 owned_record
13271 );
13272 assert!(
13273 !RunState::load_under(&owned_id, &home).unwrap().candidates[0].folded,
13274 "the owned run's candidate is not folded"
13275 );
13276 assert_eq!(queue.get(&busy.id).unwrap().status, TaskStatus::Running);
13277 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Queued);
13278 drop(execution);
13279 drop(worker_lease);
13280 }
13281
13282 #[tokio::test]
13287 async fn the_disk_pressure_service_reports_a_platform_without_containment() {
13288 let dir = tempfile::tempdir().unwrap();
13289 let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
13290 let payload = serde_json::to_value(ServiceWorker {
13291 opts,
13292 queue: queue.root().to_owned(),
13293 worktrees_root: worktrees,
13294 operation: "disk-pressure".into(),
13295 })
13296 .unwrap();
13297 let _platform = crate::retention::WithoutContainment::new();
13298 run_service_worker(&home, payload).await.unwrap();
13299
13300 let refusal = "Automatic output reclamation requires Unix process containment";
13301 let report: serde_json::Value =
13302 serde_json::from_slice(&std::fs::read(home.join("retention.json")).unwrap()).unwrap();
13303 assert_eq!(report["failures"], serde_json::json!([refusal]));
13304 let receipt: serde_json::Value = serde_json::from_slice(
13305 &std::fs::read(home.join("source-eviction-disk-pressure-worker.json")).unwrap(),
13306 )
13307 .unwrap();
13308 assert_eq!(receipt["outcome"], "retention swept");
13309 assert_eq!(receipt["retention"]["failure_count"], 1);
13310 assert_eq!(
13311 receipt["retention"]["failures"],
13312 serde_json::json!([refusal])
13313 );
13314 }
13315
13316 #[tokio::test]
13317 async fn goal_observation_service_does_not_block_scheduler_decisions() {
13318 let dir = tempfile::tempdir().unwrap();
13319 let (opts, _, _, home, worktrees) = idle_loop(dir.path());
13320 let queue = Queue::at(home.join("queue"));
13321 let mut task = task();
13322 task.repo = opts.repo.clone();
13323 task.chat = Some("decision-chat".into());
13324 task.hold_machine(Some("waiting for a decision".into()));
13325 queue.put(&mut task).unwrap();
13326 let questions = Questions::at(home.join("questions"));
13327 let mut question = action_question(&task.id, ask::ChoiceAction::Done);
13328 question.node = crate::conduct::NODE.into();
13329 question.status = ask::QuestionStatus::Open;
13330 question.answer = None;
13331 question.answered_at = None;
13332 questions.put(&mut question).unwrap();
13333 questions
13334 .update(&question.id, |q| {
13335 q.answer(ask::Answer::Choice("resume で続行する".into()))
13336 })
13337 .unwrap();
13338
13339 let talks = crate::talk::Talks::at(home.join("talks"));
13340 let mut decision_chat = crate::talk::seeded_for_test("decision-chat", opts.repo.clone());
13341 decision_chat.pending = "Keep this unsent status question".into();
13342 talks.put(&mut decision_chat).unwrap();
13343 let mut talk = crate::talk::seeded_for_test("observing-chat", opts.repo.clone());
13344 talk.goals.push(serde_json::from_value(serde_json::json!({
13345 "id":"goal","purpose":"follow the retained job","scope":"one task",
13346 "condition":{"description":"land the result","kind":"runs_merged"},
13347 "state":"runnable","step":"reading the forge","source_turn":0,"owner_input":"land this job",
13348 "tasks":[],"runs":[],"watches":[],"evidence":"","wake":1,"handled":0,
13349 "started":1,"wakes":1,"last_checked":null,"fingerprint":""
13350 })).unwrap());
13351 talks.put(&mut talk).unwrap();
13352
13353 let directory = home.join("workers/jobs/abcdef");
13356 std::fs::create_dir_all(&directory).unwrap();
13357 let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
13358 crate::pr_head::try_lock_file(&lease).unwrap();
13359 let mut job = crate::worker::Job {
13360 id: "abcdef".into(),
13361 sequence: 1,
13362 kind: "daemon-service".into(),
13363 key: "service:daemon-chat-goals".into(),
13364 payload: serde_json::Value::Null,
13365 generation: "fixture".into(),
13366 version: None,
13367 status: crate::worker::Status::Running,
13368 result: None,
13369 pid: Some(std::process::id()),
13370 created_at: Timestamp::now().as_second() as u64,
13371 finished_at: None,
13372 };
13373 let record = directory.join("job.json");
13374 std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
13375 let status = Arc::new(Mutex::new(Status::new()));
13376 let stop = Stop::new();
13377 let mut dispatch = Box::pin(poll(
13378 &opts,
13379 &queue,
13380 &status,
13381 &home,
13382 &worktrees,
13383 &stop,
13384 DispatchLimits {
13385 max_concurrent: 1,
13386 pause_for_interrupts: false,
13387 recovery_cfg: None,
13388 },
13389 ));
13390 std::future::poll_fn(|cx| {
13391 assert!(dispatch.as_mut().poll(cx).is_pending());
13392 std::task::Poll::Ready(())
13393 })
13394 .await;
13395 assert!(lock(&status).polls > 0);
13396 let saved = queue.get(&task.id).unwrap();
13397 assert_eq!(saved.status, TaskStatus::Done);
13398 assert!(saved.action_applied(&question.id));
13399 assert!(
13400 talks
13401 .get("decision-chat")
13402 .unwrap()
13403 .pending
13404 .contains("Keep this unsent status question")
13405 );
13406 let goal = talks.get(&talk.id).unwrap().goals.remove(0);
13407 assert_eq!(goal.state, crate::chat_goal::State::Runnable);
13408 assert_eq!(
13409 goal.started,
13410 Some(1),
13411 "only the observation worker may reconcile its goal"
13412 );
13413 assert_eq!(crate::worker::active(&home).unwrap()[0].id, job.id);
13414
13415 stop.stop();
13416 dispatch.await.unwrap();
13417 job.status = crate::worker::Status::Finished;
13418 std::fs::write(record, serde_json::to_vec(&job).unwrap()).unwrap();
13419 drop(lease);
13420 }
13421
13422 #[test]
13423 fn a_stop_is_idempotent_and_once_set_stays_set() {
13424 let stop = Stop::new();
13425 assert!(!stop.stopped());
13426
13427 stop.stop();
13428 assert!(stop.stopped());
13429 stop.stop();
13430 assert!(stop.stopped(), "a second stop is not a toggle");
13431
13432 let shared = stop.clone();
13433 assert!(
13434 shared.stopped(),
13435 "a clone is the same stop; that is how the loop and its caller share one"
13436 );
13437 }
13438
13439 #[tokio::test]
13440 async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
13441 for operation in ["conductor", "maintenance", "housekeeping"] {
13442 let dir = tempfile::tempdir().unwrap();
13443 let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
13444 opts.once = true;
13445 opts.poll = Duration::from_millis(1);
13446 let mut state = run_state(RunStatus::Ready);
13449 state.reserve_under(&home).unwrap();
13450 state.save_under(&home).unwrap();
13451 let mut task = task();
13452 task.runs.push(state.id.clone());
13453 queue.put(&mut task).unwrap();
13454 let claim = queue.claim(&task.id).unwrap();
13455
13456 let directory = home.join("workers/jobs/abcdef");
13459 std::fs::create_dir_all(&directory).unwrap();
13460 let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
13461 crate::pr_head::try_lock_file(&lease).unwrap();
13462 let mut job = crate::worker::Job {
13463 id: "abcdef".into(),
13464 sequence: 1,
13465 kind: "daemon-service".into(),
13466 key: format!("service:daemon-{operation}"),
13467 payload: serde_json::Value::Null,
13468 generation: "fixture".into(),
13469 version: None,
13470 status: crate::worker::Status::Running,
13471 result: None,
13472 pid: Some(std::process::id()),
13473 created_at: Timestamp::now().as_second() as u64,
13474 finished_at: None,
13475 };
13476 let record = directory.join("job.json");
13477 std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
13478
13479 let status = Arc::new(Mutex::new(Status::new()));
13480 let stop = Stop::new();
13481 let mut drain = Box::pin(poll(
13482 &opts,
13483 &queue,
13484 &status,
13485 &home,
13486 &worktrees,
13487 &stop,
13488 DispatchLimits {
13489 max_concurrent: 1,
13490 pause_for_interrupts: false,
13491 recovery_cfg: None,
13492 },
13493 ));
13494 std::future::poll_fn(|cx| {
13495 use std::future::Future;
13496 assert!(
13497 drain.as_mut().poll(cx).is_pending(),
13498 "--once must wait for {operation} to release its queue claim"
13499 );
13500 std::task::Poll::Ready(())
13501 })
13502 .await;
13503 assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
13504
13505 let questions = Questions::at(home.join("questions"));
13508 let mut q = action_question(&state.id, ask::ChoiceAction::Done);
13509 questions.put(&mut q).unwrap();
13510 drop(claim);
13511 let expired =
13515 serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
13516 for service in [operation, "housekeeping"] {
13517 std::fs::write(
13518 home.join("service-ticks").join(format!("daemon-{service}")),
13519 &expired,
13520 )
13521 .unwrap();
13522 }
13523 job.status = crate::worker::Status::Finished;
13524 std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
13525 drop(lease);
13526 tokio::time::timeout(Duration::from_secs(2), drain)
13527 .await
13528 .expect("the settled service must allow the drain to finish")
13529 .unwrap();
13530 let after = queue.get(&task.id).unwrap();
13531 assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
13532 assert!(after.action_applied(&q.id));
13533 for service in [operation, "housekeeping"] {
13534 assert_eq!(
13535 std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
13536 .unwrap(),
13537 expired,
13538 "the final once rescan must not restart {service}"
13539 );
13540 }
13541 }
13542 }
13543
13544 #[test]
13545 fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
13546 let stop = Stop::new();
13547 stop.busy.store(1, Ordering::SeqCst);
13548 assert!(
13549 !stop.finishing(),
13550 "a busy loop nobody has asked to stop is just running"
13551 );
13552
13553 stop.stop();
13554 assert!(
13555 stop.finishing(),
13556 "a stop asked for mid-run has not landed until the run is settled"
13557 );
13558
13559 stop.busy.store(0, Ordering::SeqCst);
13560 assert!(
13561 !stop.finishing(),
13562 "once the run is settled the stop has landed and there is nothing to finish"
13563 );
13564 }
13565
13566 #[test]
13567 fn finishing_stays_true_until_the_last_of_several_runs_exits() {
13568 let stop = Stop::new();
13569 stop.busy.store(2, Ordering::SeqCst);
13570 stop.stop();
13571 assert!(stop.finishing(), "two runs still in flight");
13572
13573 stop.busy.store(1, Ordering::SeqCst);
13574 assert!(
13575 stop.finishing(),
13576 "one run finished, but a sibling is still working"
13577 );
13578
13579 stop.busy.store(0, Ordering::SeqCst);
13580 assert!(
13581 !stop.finishing(),
13582 "the last run out is what actually lands the stop"
13583 );
13584 }
13585
13586 #[tokio::test]
13587 async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
13588 let dir = tempfile::tempdir().unwrap();
13589 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
13590 let stop = Stop::new();
13591 stop.stop();
13592
13593 let began = std::time::Instant::now();
13594 tokio::time::timeout(
13595 Duration::from_secs(2),
13596 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
13597 )
13598 .await
13599 .expect("a stopped loop must return, not sit out its poll interval")
13600 .expect("the loop's own setup and teardown must not fail");
13601 assert!(
13602 began.elapsed() < opts.poll,
13603 "returned only after {:?}, which is a poll interval, not a stop",
13604 began.elapsed()
13605 );
13606 }
13607
13608 #[tokio::test]
13609 async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
13610 let dir = tempfile::tempdir().unwrap();
13611 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
13612 let stop = Stop::new();
13613
13614 let asker = {
13617 let stop = stop.clone();
13618 tokio::spawn(async move {
13619 tokio::time::sleep(Duration::from_millis(20)).await;
13620 stop.stop();
13621 })
13622 };
13623
13624 let began = std::time::Instant::now();
13625 tokio::time::timeout(
13626 Duration::from_secs(2),
13627 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
13628 )
13629 .await
13630 .expect("a stop asked for while idle must wake the wait")
13631 .expect("the loop's own setup and teardown must not fail");
13632 asker.await.unwrap();
13633 assert!(
13634 began.elapsed() < opts.poll,
13635 "returned only after {:?}, so the stop waited on the sleep",
13636 began.elapsed()
13637 );
13638 }
13639
13640 #[tokio::test]
13641 async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
13642 let dir = tempfile::tempdir().unwrap();
13643 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
13644 let stop = Stop::new();
13645 stop.stop();
13646
13647 tokio::time::timeout(
13648 Duration::from_secs(2),
13649 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
13650 )
13651 .await
13652 .expect("a stopped loop must return")
13653 .expect("the loop's own setup and teardown must not fail");
13654
13655 assert!(
13656 home.is_dir(),
13657 "the loop did publish a status file, so its removal is the teardown and not an absence"
13658 );
13659 assert!(
13660 !status_file.exists(),
13661 "a stopped loop clears its status file"
13662 );
13663 assert!(
13664 read_status(&home).is_none(),
13665 "a reader must see no daemon at all, not a heartbeat that merely stopped"
13666 );
13667 }
13668
13669 #[tokio::test]
13670 async fn housekeeping_worker_settles_questions_without_a_scheduler() {
13671 let dir = tempfile::tempdir().unwrap();
13672 let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
13673
13674 let mut settled = RunState::new(
13675 dir.path().join("repo"),
13676 "main".to_owned(),
13677 "abc1234".to_owned(),
13678 "fixture".to_owned(),
13679 Config::default(),
13680 );
13681 settled.status = RunStatus::Ready;
13682 let run_dir = home.join("runs").join(&settled.id);
13683 std::fs::create_dir_all(&run_dir).unwrap();
13684 std::fs::write(
13685 run_dir.join("run.json"),
13686 serde_json::to_string_pretty(&settled).unwrap(),
13687 )
13688 .unwrap();
13689 let questions = Questions::at(home.join("questions"));
13690 let mut question = ask::Question::new(
13691 settled.id.clone(),
13692 "review".to_owned(),
13693 "reviewer-1".to_owned(),
13694 "Continue?".to_owned(),
13695 String::new(),
13696 Vec::new(),
13697 );
13698 questions.put(&mut question).unwrap();
13699
13700 run_service_worker(
13701 &home,
13702 serde_json::to_value(ServiceWorker {
13703 opts,
13704 queue: queue.root().to_path_buf(),
13705 worktrees_root: worktrees,
13706 operation: "housekeeping".to_owned(),
13707 })
13708 .unwrap(),
13709 )
13710 .await
13711 .unwrap();
13712
13713 assert_eq!(
13714 questions.get(&question.id).unwrap().status,
13715 ask::QuestionStatus::Abandoned,
13716 "the independent housekeeping worker settles ended-run questions"
13717 );
13718 }
13719
13720 #[test]
13721 fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
13722 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
13723
13724 assert!(
13725 cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
13726 "never checked before: due at once"
13727 );
13728
13729 let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
13730 assert!(
13731 !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
13732 "well inside the interval: not due yet"
13733 );
13734
13735 let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
13736 assert!(
13737 !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
13738 "exactly at the edge: not yet due, same convention as `clean::due`"
13739 );
13740
13741 let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
13742 assert!(
13743 cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
13744 "past the interval: due again"
13745 );
13746 }
13747
13748 fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
13753 let config = dir.join("magi.toml");
13754 std::fs::write(
13760 &config,
13761 format!(
13762 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
13763 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
13764 cache_dir.display()
13765 ),
13766 )
13767 .unwrap();
13768 Opts {
13769 config: Some(config),
13770 repo: dir.join("repo"),
13771 ..Opts::default()
13772 }
13773 }
13774
13775 #[tokio::test]
13776 async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
13777 let dir = tempfile::tempdir().unwrap();
13778 let home = dir.path().join("home");
13779 let cache_dir = dir.path().join("cache");
13780 std::fs::create_dir_all(&cache_dir).unwrap();
13781 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
13782 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
13783
13784 let running = Stop::new();
13787 let mut last_checked = None;
13788 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
13789 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
13790 .await;
13791 assert_eq!(
13792 crate::disk::dir_size(&cache_dir),
13793 0,
13794 "over the cap on the first check ever: pruned at once, no idle queue required"
13795 );
13796 assert_eq!(last_checked, Some(t0));
13797
13798 std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
13800 let too_soon = t0 + jiff::SignedDuration::from_secs(1);
13801 maybe_prune_cache_between_runs(
13802 &opts.repo,
13803 &opts,
13804 &home,
13805 &running,
13806 &mut last_checked,
13807 too_soon,
13808 )
13809 .await;
13810 assert_eq!(
13811 crate::disk::dir_size(&cache_dir),
13812 10,
13813 "too soon since the last check: left alone rather than rescanned every call"
13814 );
13815 assert_eq!(
13816 last_checked,
13817 Some(t0),
13818 "an idle check does not reset the clock"
13819 );
13820
13821 let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
13823 maybe_prune_cache_between_runs(
13824 &opts.repo,
13825 &opts,
13826 &home,
13827 &running,
13828 &mut last_checked,
13829 due_again,
13830 )
13831 .await;
13832 assert_eq!(
13833 crate::disk::dir_size(&cache_dir),
13834 0,
13835 "due again: pruned back under the cap"
13836 );
13837 }
13838
13839 #[tokio::test]
13847 async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
13848 let dir = tempfile::tempdir().unwrap();
13849 let home = dir.path().join("home");
13850 let cache_dir = dir.path().join("cache");
13851 std::fs::create_dir_all(&cache_dir).unwrap();
13852 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
13853 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
13854
13855 let stop = Stop::new();
13856 stop.stop();
13857 assert!(
13858 !stop.finishing(),
13859 "no run is in flight at a between-runs boundary, so nothing else \
13860 would tell the operator this stop had not taken effect yet"
13861 );
13862
13863 let mut last_checked = None;
13864 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
13865 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
13866 .await;
13867 assert_eq!(
13868 crate::disk::dir_size(&cache_dir),
13869 10,
13870 "over its cap, and due for the first check ever, but a stop outranks \
13871 it: the cap is a standing policy the next start measures again"
13872 );
13873 assert_eq!(
13874 last_checked, None,
13875 "a check that never happened must not claim the interval"
13876 );
13877 }
13878
13879 #[tokio::test]
13882 async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
13883 let dir = tempfile::tempdir().unwrap();
13884 let cache_dir = dir.path().join("cache");
13885 std::fs::create_dir_all(&cache_dir).unwrap();
13886 std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
13887
13888 let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
13889 opts.poll = Duration::from_millis(20);
13890 opts.max_attempts = 1_000;
13891
13892 let queue = Queue::at(dir.path().join("queue"));
13893 for i in 0..128 {
13894 let mut task = Task::new(
13895 format!("queued work {i}"),
13896 format!("queued work {i}"),
13897 opts.repo.clone(),
13898 Source::Human,
13899 );
13900 queue.put(&mut task).unwrap();
13901 }
13902
13903 let home = dir.path().join("home");
13904 let worktrees = dir.path().join("wt");
13905 run_service_worker(
13906 &home,
13907 serde_json::to_value(ServiceWorker {
13908 opts,
13909 queue: queue.root().to_path_buf(),
13910 worktrees_root: worktrees,
13911 operation: "cache".to_owned(),
13912 })
13913 .unwrap(),
13914 )
13915 .await
13916 .unwrap();
13917 let after = queue.list();
13918 assert_eq!(after.len(), 128);
13919 assert!(
13920 after
13921 .iter()
13922 .all(|task| task.status.runnable() && task.attempts == 0)
13923 );
13924
13925 assert_eq!(
13926 crate::disk::dir_size(&cache_dir),
13927 0,
13928 "an oversized cache must not be left to grow unboundedly just because the \
13929 queue kept the loop busy the whole time"
13930 );
13931 }
13932
13933 #[test]
13934 fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
13935 let dir = tempfile::tempdir().unwrap();
13936 let queue = Queue::at(dir.path().join("queue"));
13937 let questions = Questions::at(dir.path().join("questions"));
13938 let mut task = task();
13939 queue.put(&mut task).unwrap();
13940
13941 let mut task_question = ask::Question::new(
13942 task.id.clone(),
13943 crate::conduct::NODE.to_owned(),
13944 "conduct".to_owned(),
13945 "Which backend?".to_owned(),
13946 String::new(),
13947 Vec::new(),
13948 );
13949 questions.put(&mut task_question).unwrap();
13950 task.block(vec![task_question.id.clone()], None);
13951 queue.put(&mut task).unwrap();
13952
13953 let mut run_question = ask::Question::new(
13954 "20260101-000000-run1".to_owned(),
13955 "review".to_owned(),
13956 "reviewer-1".to_owned(),
13957 "Run question".to_owned(),
13958 String::new(),
13959 Vec::new(),
13960 );
13961 questions.put(&mut run_question).unwrap();
13962
13963 let mut coincidental = ask::Question::new(
13968 task.id.clone(),
13969 "review".to_owned(),
13970 "reviewer-1".to_owned(),
13971 "Unrelated review question".to_owned(),
13972 String::new(),
13973 Vec::new(),
13974 );
13975 questions.put(&mut coincidental).unwrap();
13976
13977 reconcile_task_questions(&queue, &questions);
13978 assert!(questions.get(&task_question.id).unwrap().status.open());
13979 assert!(questions.get(&run_question.id).unwrap().status.open());
13980 assert!(questions.get(&coincidental.id).unwrap().status.open());
13981
13982 task.release();
13983 queue.put(&mut task).unwrap();
13984 reconcile_task_questions(&queue, &questions);
13985 assert_eq!(
13986 questions.get(&task_question.id).unwrap().status,
13987 ask::QuestionStatus::Abandoned
13988 );
13989 assert!(
13990 questions.get(&run_question.id).unwrap().status.open(),
13991 "run questions remain the run janitor's responsibility"
13992 );
13993 assert!(
13994 questions.get(&coincidental.id).unwrap().status.open(),
13995 "a non-conductor question must not be abandoned just because its \
13996 run id coincides with a task id"
13997 );
13998 }
13999
14000 #[test]
14001 fn a_freshly_started_running_task_is_never_stalled() {
14002 let dir = tempfile::tempdir().unwrap();
14003 let mut t = task();
14004 t.start("run-1".to_owned());
14005 assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
14008 }
14009
14010 #[test]
14011 fn a_long_running_task_with_no_live_daemon_is_stalled() {
14012 let dir = tempfile::tempdir().unwrap();
14013 let mut t = task();
14014 t.start("run-1".to_owned());
14015 t.updated_at = Timestamp::now()
14016 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
14017 assert!(is_stalled(&t, dir.path(), Timestamp::now()));
14018 assert_eq!(
14019 stalled_tasks(
14020 &Queue::at(dir.path().join("q")),
14021 dir.path(),
14022 Timestamp::now()
14023 )
14024 .len(),
14025 0,
14026 "the task was never written to this queue"
14027 );
14028 }
14029
14030 #[test]
14031 fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
14032 let dir = tempfile::tempdir().unwrap();
14033 let mut t = task();
14034 t.id = "20260903-080340-0167".to_owned();
14035 t.start("20260903-080619-01c2".to_owned());
14036 t.updated_at = Timestamp::now()
14037 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
14038
14039 let mut status = Status::new();
14040 status.current = vec![Current {
14041 worker: None,
14042 task: t.id.clone(),
14043 run: "20260903-080619-01c2".to_owned(),
14044 }];
14045 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
14046
14047 assert!(
14048 !is_stalled(&t, dir.path(), Timestamp::now()),
14049 "a live daemon's own heartbeat rules out stalled, however long the task has run"
14050 );
14051 }
14052
14053 fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
14057 let path = queue.path_of(id);
14058 let body = std::fs::read_to_string(&path).unwrap();
14059 let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
14060 let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
14061 v["updated_at"] = serde_json::Value::String(old.to_string());
14062 std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
14063 }
14064
14065 #[test]
14066 fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
14067 let dir = tempfile::tempdir().unwrap();
14080 let queue = Queue::at(dir.path().join("queue"));
14081 let home = dir.path().join("home");
14082
14083 let mut t = task();
14084 t.id = "20260101-000001-lock".to_owned();
14085 t.start("run-1".to_owned());
14086 queue.put(&mut t).unwrap();
14087 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
14088 std::fs::write(
14089 dir.path().join("queue").join(format!("{}.lock", t.id)),
14090 "not a pid",
14091 )
14092 .unwrap();
14093
14094 let now = Timestamp::now();
14095 assert!(
14096 reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
14097 "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
14098 and reclaim must leave the task alone"
14099 );
14100 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
14101
14102 let stalled = stalled_tasks(&queue, &home, now);
14103 assert_eq!(
14104 stalled.len(),
14105 1,
14106 "reclaim's inability to claim it yet must not hide it from the conductor"
14107 );
14108 assert_eq!(stalled[0].id, t.id);
14109 }
14110
14111 #[test]
14112 fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
14113 let dir = tempfile::tempdir().unwrap();
14114 crate::run::set_home(dir.path().join("run-home"));
14115 let queue = Queue::at(dir.path().join("queue"));
14116 let home = dir.path().join("home");
14117 let questions = Questions::at(dir.path().join("questions"));
14118
14119 let mut t = task();
14120 t.id = "20260101-000003-dead".to_owned();
14121 t.start("missing-run".to_owned());
14122 queue.put(&mut t).unwrap();
14123 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
14124
14125 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
14128 assert_eq!(
14129 stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
14130 [&t.id]
14131 );
14132 assert_eq!(
14133 reclaim_orphaned_running(&queue, 2, &Default::default()),
14134 [t.id.clone()]
14135 );
14136 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14137
14138 crate::conduct::apply(
14141 &queue,
14142 &questions,
14143 &crate::conduct::Verdict {
14144 decisions: vec![crate::conduct::Decision {
14145 id: t.id.clone(),
14146 recovery: Some(crate::conduct::Recovery::Requeue),
14147 ..crate::conduct::Decision::default()
14148 }],
14149 },
14150 )
14151 .unwrap();
14152 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
14153 }
14154
14155 #[test]
14156 fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
14157 let dir = tempfile::tempdir().unwrap();
14158 let queue = Queue::at(dir.path().join("queue"));
14159 let home = dir.path().join("home");
14160
14161 let mut fresh = task();
14162 fresh.id = "20260101-000001-aaaa".to_owned();
14163 fresh.start("run-1".to_owned());
14164 queue.put(&mut fresh).unwrap();
14165
14166 let mut old = task();
14167 old.id = "20260101-000002-bbbb".to_owned();
14168 old.start("run-2".to_owned());
14169 queue.put(&mut old).unwrap();
14170 backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
14171
14172 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
14173 assert_eq!(stalled.len(), 1);
14174 assert_eq!(stalled[0].id, old.id);
14175 }
14176
14177 #[test]
14178 fn queued_and_finished_task_views_partition_by_status() {
14179 let dir = tempfile::tempdir().unwrap();
14180 let queue = Queue::at(dir.path().join("queue"));
14181
14182 let mut queued = task();
14183 queued.id = "20260101-000001-aaaa".to_owned();
14184 queue.put(&mut queued).unwrap();
14185
14186 let mut failed = task();
14187 failed.id = "20260101-000002-bbbb".to_owned();
14188 failed.start("run-1".to_owned());
14189 failed.fail("gate red", 5);
14190 queue.put(&mut failed).unwrap();
14191
14192 let mut held = task();
14193 held.id = "20260101-000003-cccc".to_owned();
14194 held.hold_machine(None);
14195 queue.put(&mut held).unwrap();
14196
14197 let mut running = task();
14198 running.id = "20260101-000004-dddd".to_owned();
14199 running.start("run-2".to_owned());
14200 queue.put(&mut running).unwrap();
14201
14202 let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
14203 assert_eq!(queued_ids, [queued.id.clone()]);
14204
14205 let mut finished_ids: Vec<String> =
14206 finished_tasks(&queue).into_iter().map(|t| t.id).collect();
14207 finished_ids.sort_unstable();
14208 let mut want = vec![failed.id.clone(), held.id.clone()];
14209 want.sort_unstable();
14210 assert_eq!(finished_ids, want);
14211 }
14212
14213 #[test]
14214 fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
14215 for short in [false, true] {
14216 let dir = tempfile::tempdir().unwrap();
14217 let queue = Queue::at(dir.path().join("queue"));
14218 let questions = ask::Questions::at(dir.path().join("questions"));
14219 let mut running = task();
14220 running.id = "20261013-192213-feb2".into();
14221 running.start("existing-run".into());
14222 queue.put(&mut running).unwrap();
14223 let mut middle = task();
14224 middle.id = "20261013-193611-ca5b".into();
14225 middle.block(
14226 vec![if short {
14227 "feb2".into()
14228 } else {
14229 running.id.clone()
14230 }],
14231 None,
14232 );
14233 queue.put(&mut middle).unwrap();
14234 let mut waiting = task();
14235 waiting.id = "20261013-202849-ee37".into();
14236 waiting.block(
14237 vec![if short {
14238 "ca5b".into()
14239 } else {
14240 middle.id.clone()
14241 }],
14242 Some("wait for implementation".into()),
14243 );
14244 queue.put(&mut waiting).unwrap();
14245 assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
14246 let inv = crate::blockers::Inventory::load(&queue, &questions);
14247 assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
14248 assert!(inv.stuck().is_empty());
14249 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
14250 assert!(report.quarantined.is_empty());
14251 assert!(report.asked.is_empty());
14252 resolve_blockers(&queue, &questions);
14253 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
14254 assert!(questions.list().is_empty());
14255 running.succeed(CompletionContext::new(
14258 CompletionActor::DaemonSettle,
14259 None,
14260 dir.path(),
14261 &running,
14262 ));
14263 queue.put(&mut running).unwrap();
14264 resolve_blockers(&queue, &questions);
14265 assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
14266 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
14267 middle = queue.get(&middle.id).unwrap();
14268 middle.succeed(CompletionContext::new(
14269 CompletionActor::DaemonSettle,
14270 None,
14271 dir.path(),
14272 &middle,
14273 ));
14274 queue.put(&mut middle).unwrap();
14275 resolve_blockers(&queue, &questions);
14276 let after = queue.get(&waiting.id).unwrap();
14277 assert_eq!(after.status, TaskStatus::Queued);
14278 assert!(after.blocked_by.is_empty());
14279 assert_eq!(after.instruction, waiting.instruction);
14280 }
14281 }
14282
14283 #[test]
14284 fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
14285 for future_schema in [false, true] {
14286 let name = "20261013-193611-ca5b";
14287 let mut future = task();
14288 future.id = name.into();
14289 future.schema = crate::queue::SCHEMA + 1;
14290 let contents = if future_schema {
14291 serde_json::to_string(&future).unwrap()
14292 } else {
14293 "corrupt".into()
14294 };
14295 let dir = tempfile::tempdir().unwrap();
14296 let queue = Queue::at(dir.path().join("queue"));
14297 let questions = ask::Questions::at(dir.path().join("questions"));
14298 let mut waiting = task();
14299 waiting.id = "20261013-202849-ee37".into();
14300 waiting.block(vec!["ca5b".into()], None);
14301 queue.put(&mut waiting).unwrap();
14302 std::fs::write(queue.path_of(name), contents).unwrap();
14303 assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
14304 assert!(
14305 crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
14306 );
14307 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
14308 assert!(report.asked.is_empty());
14309 resolve_blockers(&queue, &questions);
14310 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
14311 assert!(questions.list().is_empty());
14312 }
14313 let dir = tempfile::tempdir().unwrap();
14314 let queue = Queue::at(dir.path().join("queue"));
14315 let questions = ask::Questions::at(dir.path().join("questions"));
14316 let mut waiting = task();
14317 waiting.id = "20261013-202849-ee37".into();
14318 waiting.block(vec!["ca5b".into()], None);
14319 queue.put(&mut waiting).unwrap();
14320 let mut done = task();
14321 done.id = "20261013-193611-ca5b".into();
14322 done.succeed(CompletionContext::new(
14323 CompletionActor::Cli,
14324 None,
14325 dir.path(),
14326 &done,
14327 ));
14328 queue.put(&mut done).unwrap();
14329 std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
14332 assert!(queue.get("ca5b").is_err());
14333 assert_eq!(
14334 crate::queue::dependency(&queue, &questions, "ca5b"),
14335 crate::queue::Dependency::Ambiguous
14336 );
14337 resolve_blockers(&queue, &questions);
14338 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
14339 assert!(report.asked.is_empty());
14340 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
14341 assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
14342 }
14343
14344 #[test]
14345 fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
14346 for held in [false, true] {
14347 for question in [false, true] {
14348 for reference in ["ca5b", "20261013-193611-ca5b"] {
14349 let dir = tempfile::tempdir().unwrap();
14350 let queue = Queue::at(dir.path().join("queue"));
14351 let questions = ask::Questions::at(dir.path().join("questions"));
14352 let mut prerequisite = task();
14353 prerequisite.id = "20261013-193611-ca5b".into();
14354 prerequisite.start("existing-run".into());
14355 queue.put(&mut prerequisite).unwrap();
14356 let mut waiting = task();
14357 waiting.id = "20261013-202849-ee37".into();
14358 if held {
14359 waiting.hold_machine(Some("waiting for separate consent".into()));
14360 }
14361 queue.put(&mut waiting).unwrap();
14362 let reason = "Deleting saved data requires separate owner consent";
14363 crate::conduct::apply(
14364 &queue,
14365 &questions,
14366 &crate::conduct::Verdict {
14367 decisions: vec![crate::conduct::Decision {
14368 id: waiting.id.clone(),
14369 blocked_by: vec![reference.into()],
14370 question: question.then(|| "May the saved data be deleted?".into()),
14371 recovery: (!question).then_some(crate::conduct::Recovery::Hold),
14372 reason: Some(reason.into()),
14373 ..crate::conduct::Decision::default()
14374 }],
14375 },
14376 )
14377 .unwrap();
14378 let before = queue.get(&waiting.id).unwrap();
14379 if question {
14380 assert_eq!(before.status, TaskStatus::Blocked);
14381 let q = questions.get(&before.blocked_by[0]).unwrap();
14382 assert_eq!(q.summary, "May the saved data be deleted?");
14383 assert!(q.status.open());
14384 } else {
14385 assert_eq!(before.status, TaskStatus::Held);
14386 let recorded_reason = before.hold_reason.as_deref().unwrap();
14387 assert!(recorded_reason.starts_with(reason));
14388 if held {
14389 assert!(recorded_reason.contains("waiting for separate consent"));
14390 }
14391 }
14392 prerequisite.succeed(CompletionContext::new(
14393 CompletionActor::DaemonSettle,
14394 None,
14395 dir.path(),
14396 &prerequisite,
14397 ));
14398 queue.put(&mut prerequisite).unwrap();
14399 resolve_blockers(&queue, &questions);
14400 let after = queue.get(&waiting.id).unwrap();
14401 assert_eq!(after.status, before.status);
14402 assert_eq!(after.blocked_by, before.blocked_by);
14403 assert_eq!(after.hold_reason, before.hold_reason);
14404 assert_eq!(after.instruction, waiting.instruction);
14405 if question {
14406 assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
14407 }
14408 assert!(
14409 queue.next_runnable().is_none(),
14410 "dependency completion is not consent"
14411 );
14412 }
14413 }
14414 }
14415 }
14416
14417 #[test]
14418 fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
14419 let dir = tempfile::tempdir().unwrap();
14420 let queue = Queue::at(dir.path().join("queue"));
14421 let questions = ask::Questions::at(dir.path().join("questions"));
14422
14423 let mut dep = task();
14424 dep.id = "20260101-000001-dep0".to_owned();
14425 dep.succeed(CompletionContext::new(
14426 CompletionActor::DaemonSettle,
14427 None,
14428 dir.path(),
14429 &dep,
14430 ));
14431 queue.put(&mut dep).unwrap();
14432
14433 let mut still_going = task();
14434 still_going.id = "20260101-000002-dep1".to_owned();
14435 queue.put(&mut still_going).unwrap();
14436
14437 let mut blocked = task();
14438 blocked.id = "20260101-000003-main".to_owned();
14439 blocked.block(
14440 vec![dep.id.clone(), still_going.id.clone()],
14441 Some("waits on both".to_owned()),
14442 );
14443 queue.put(&mut blocked).unwrap();
14444
14445 resolve_blockers(&queue, &questions);
14446
14447 let after = queue.get(&blocked.id).unwrap();
14448 assert_eq!(
14449 after.status,
14450 TaskStatus::Blocked,
14451 "one dependency is still outstanding"
14452 );
14453 assert_eq!(after.blocked_by, [still_going.id.clone()]);
14454 }
14455
14456 #[test]
14457 fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
14458 let dir = tempfile::tempdir().unwrap();
14459 let queue = Queue::at(dir.path().join("queue"));
14460 let questions = ask::Questions::at(dir.path().join("questions"));
14461
14462 let mut q = crate::ask::Question::new(
14463 "20260101-000001-main".to_owned(),
14464 crate::conduct::NODE.to_owned(),
14465 "conduct".to_owned(),
14466 "Which backend?".to_owned(),
14467 String::new(),
14468 Vec::new(),
14469 );
14470 questions.put(&mut q).unwrap();
14471 q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
14472 .unwrap();
14473 questions.put(&mut q).unwrap();
14474
14475 let mut blocked = task();
14476 blocked.id = "20260101-000001-main".to_owned();
14477 blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
14478 queue.put(&mut blocked).unwrap();
14479
14480 resolve_blockers(&queue, &questions);
14481
14482 let after = queue.get(&blocked.id).unwrap();
14483 assert_eq!(
14484 after.status,
14485 TaskStatus::Queued,
14486 "the only blocker resolved"
14487 );
14488 assert_eq!(after.answers.len(), 1);
14489 assert_eq!(after.answers[0].question, "Which backend?");
14490 assert_eq!(after.answers[0].answer, "SQLite");
14491
14492 let instruction = instruction_for(&after);
14494 assert!(instruction.contains("Which backend?"));
14495 assert!(instruction.contains("SQLite"));
14496 }
14497
14498 #[test]
14499 fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
14500 let dir = tempfile::tempdir().unwrap();
14501 let queue = Queue::at(dir.path().join("queue"));
14502 let questions = ask::Questions::at(dir.path().join("questions"));
14503
14504 let mut q = crate::ask::Question::new(
14505 "20260101-000001-main".to_owned(),
14506 crate::conduct::NODE.to_owned(),
14507 "conduct".to_owned(),
14508 "Is the setup done?".to_owned(),
14509 String::new(),
14510 Vec::new(),
14511 );
14512 q.abandon("no answer within 60s of asking");
14513 questions.put(&mut q).unwrap();
14514
14515 let mut blocked = task();
14516 blocked.id = "20260101-000001-main".to_owned();
14517 blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
14518 queue.put(&mut blocked).unwrap();
14519
14520 resolve_blockers(&queue, &questions);
14521
14522 let after = queue.get(&blocked.id).unwrap();
14523 assert_eq!(
14524 after.status,
14525 TaskStatus::Held,
14526 "never left blocked on nothing"
14527 );
14528 assert!(!after.operator_held(), "a machine hold, for triage");
14529 assert!(
14530 after
14531 .hold_reason
14532 .as_deref()
14533 .unwrap_or_default()
14534 .contains("went unanswered")
14535 );
14536 }
14537
14538 #[test]
14539 fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
14540 let dir = tempfile::tempdir().unwrap();
14546 let queue = Queue::at(dir.path().join("queue"));
14547 let questions = ask::Questions::at(dir.path().join("questions"));
14548
14549 let mut q = crate::ask::Question::new(
14550 "20260101-000001-main".to_owned(),
14551 crate::conduct::NODE.to_owned(),
14552 "conduct".to_owned(),
14553 "How should this be handled?".to_owned(),
14554 String::new(),
14555 Vec::new(),
14556 );
14557 questions.put(&mut q).unwrap();
14558 q.answer(crate::ask::Answer::Text(
14559 "leave it held, a human will look at it later".to_owned(),
14560 ))
14561 .unwrap();
14562 questions.put(&mut q).unwrap();
14563
14564 let mut held = task();
14565 held.id = "20260101-000001-main".to_owned();
14566 held.hold_machine(Some("out of attempts".to_owned()));
14567 held.block(vec![q.id.clone()], Some("what now?".to_owned()));
14568 queue.put(&mut held).unwrap();
14569
14570 resolve_blockers(&queue, &questions);
14571
14572 let after = queue.get(&held.id).unwrap();
14573 assert_eq!(after.status, TaskStatus::Held);
14574 assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
14575 assert_eq!(
14576 after.answers[0].answer,
14577 "leave it held, a human will look at it later"
14578 );
14579 }
14580
14581 #[test]
14582 fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
14583 let dir = tempfile::tempdir().unwrap();
14584 let queue = Queue::at(dir.path().join("queue"));
14585 let questions = ask::Questions::at(dir.path().join("questions"));
14586 let mut dep = task();
14587 dep.id = "20260101-000001-gone".to_owned();
14588 queue.put(&mut dep).unwrap();
14589 let mut blocked = task();
14590 blocked.id = "20260101-000003-main".to_owned();
14591 blocked.block(vec![dep.id.clone()], None);
14592 queue.put(&mut blocked).unwrap();
14593
14594 let claim = queue.claim(&blocked.id).unwrap();
14596 queue.remove(&dep.id, false, &questions).unwrap();
14597 drop(claim);
14598 resolve_blockers(&queue, &questions);
14599
14600 let after = queue.get(&blocked.id).unwrap();
14601 assert_eq!(after.status, TaskStatus::Queued);
14602 assert!(after.blocked_by.is_empty());
14603 }
14604
14605 #[test]
14606 fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
14607 let dir = tempfile::tempdir().unwrap();
14613 let queue = Queue::at(dir.path().join("queue"));
14614 let questions = ask::Questions::at(dir.path().join("questions"));
14615
14616 let mut still_going = task();
14617 still_going.id = "20260101-000002-dep1".to_owned();
14618 queue.put(&mut still_going).unwrap();
14619
14620 let mut blocked = task();
14621 blocked.id = "20260101-000003-main".to_owned();
14622 blocked.block(
14623 vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
14624 Some("waits on both".to_owned()),
14625 );
14626 queue.put(&mut blocked).unwrap();
14627
14628 resolve_blockers(&queue, &questions);
14629
14630 let after = queue.get(&blocked.id).unwrap();
14631 assert_eq!(
14632 after.status,
14633 TaskStatus::Held,
14634 "a missing dependency must not leave the task blocked forever"
14635 );
14636 assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
14637 assert!(after.blocked_by.is_empty());
14638 let reason = after.hold_reason.as_deref().unwrap_or_default();
14639 assert!(
14640 reason.contains("20260101-000001-gone"),
14641 "the missing id must be named so an operator can tell what happened: {reason}"
14642 );
14643 assert!(
14644 reason.contains(&still_going.id),
14645 "the still-valid dependency must not silently vanish from the record: {reason}"
14646 );
14647 }
14648
14649 #[test]
14650 fn instruction_for_is_unchanged_without_any_answers() {
14651 let t = task();
14652 assert_eq!(instruction_for(&t), t.instruction);
14653 }
14654
14655 #[test]
14656 fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
14657 let dir = tempfile::tempdir().unwrap();
14658 let q = Queue::at(dir.path().join("queue"));
14659 let src = dir.path().join("shot.png");
14660 std::fs::write(&src, "x").unwrap();
14661 let mut t = task();
14662 q.attach(&mut t, &[src]).unwrap();
14663 let paths = task_attachments(&q, &t).unwrap();
14664 assert_eq!(paths.len(), 1);
14665 assert!(paths[0].is_absolute() && paths[0].is_file());
14666 std::fs::remove_file(&paths[0]).unwrap();
14667 let err = task_attachments(&q, &t).unwrap_err().to_string();
14668 assert!(err.contains("shot.png"), "{err}");
14669 }
14670
14671 #[tokio::test]
14672 async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
14673 let dir = tempfile::tempdir().unwrap();
14674 let queue_path = dir.path().join("queue");
14675 let queue = Queue::at(queue_path.clone());
14676 let mut t = task();
14677 t.source = Source::Agent {
14678 run: "originating-chat".into(),
14679 node: crate::queue::CHAT_NODE.into(),
14680 };
14681 let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
14682 stage: "config-fetch",
14683 target: "origin/main".into(),
14684 });
14685 record_config_failure(&mut t, &fetch);
14686 t.hold_machine(Some(format!("{fetch:#}")));
14687 let fetch_key = t.chat_notice_due().unwrap();
14688 t.chat_notices.push(fetch_key.clone());
14689 queue.put(&mut t).unwrap();
14690
14691 let queue = Queue::at(queue_path);
14692 let mut t = queue.get(&t.id).unwrap();
14693 let a = dir.path().join("a.toml");
14694 let b = dir.path().join("b.toml");
14695 for (path, text, new_cause) in [
14696 (&a, "[graph", true),
14697 (&a, "[verify", false),
14698 (&a, "[graph]\nimplementers = 'invalid-type'", true),
14699 (&b, "[graph]\nimplementers = 'invalid-type'", true),
14700 ] {
14701 t.release_operator("test", None);
14702 std::fs::write(path, text).unwrap();
14703 let error = Config::discover_fetched(dir.path(), Some(path))
14704 .await
14705 .unwrap_err();
14706 record_config_failure(&mut t, &error);
14707 t.hold_machine(Some(format!("{error:#}")));
14708 let due = t.chat_notice_due();
14709 assert_eq!(due.is_some(), new_cause, "{error:#}");
14710 if let Some(key) = due {
14711 assert_ne!(key, fetch_key);
14712 t.chat_notices.push(key);
14713 }
14714 }
14715 t.succeed(CompletionContext::new(
14716 CompletionActor::DaemonSettle,
14717 None,
14718 dir.path(),
14719 &t,
14720 ));
14721 assert_eq!(
14722 t.chat_notice_due(),
14723 Some(format!(
14724 "done:{}",
14725 t.completion_history.last().unwrap().occurrence
14726 ))
14727 );
14728 }
14729
14730 #[test]
14731 fn different_missing_attachments_have_distinct_persisted_notice_causes() {
14732 let dir = tempfile::tempdir().unwrap();
14733 let queue_path = dir.path().join("queue");
14734 let queue = Queue::at(queue_path.clone());
14735 let mut t = task();
14736 t.source = crate::queue::Source::Agent {
14737 run: "originating-chat".into(),
14738 node: crate::queue::CHAT_NODE.into(),
14739 };
14740 let a = dir.path().join("a.png");
14741 let b = dir.path().join("b.png");
14742 std::fs::write(&a, "a").unwrap();
14743 std::fs::write(&b, "b").unwrap();
14744 queue.attach(&mut t, &[a, b]).unwrap();
14745 let paths = task_attachments(&queue, &t).unwrap();
14746 for path in &paths {
14747 std::fs::remove_file(path).unwrap();
14748 }
14749 let missing = task_attachments(&queue, &t).unwrap_err();
14750 t.attempts += 1;
14751 let reason = missing.to_string();
14752 t.fail_startup_target("startup-attachments", missing.name, reason, 1);
14753 let first = t.chat_notice_due().expect("first attachment notice");
14754 t.chat_notices.push(first.clone());
14755 queue.put(&mut t).unwrap();
14756
14757 let queue = Queue::at(queue_path.clone());
14758 let mut t = queue.get(&t.id).unwrap();
14759 assert!(t.chat_notice_due().is_none(), "restart does not replay");
14760 t.release_operator("test", None);
14761 t.attempts += 1;
14762 let missing = task_attachments(&queue, &t).unwrap_err();
14763 t.fail_startup_target(
14764 "startup-attachments",
14765 missing.name,
14766 "same missing attachment with regenerated wording",
14767 1,
14768 );
14769 assert!(t.chat_notice_due().is_none(), "same object stays quiet");
14770
14771 std::fs::write(&paths[0], "restored").unwrap();
14772 t.release_operator("test", None);
14773 t.attempts += 1;
14774 let missing = task_attachments(&queue, &t).unwrap_err();
14775 let reason = missing.to_string();
14776 t.fail_startup_target("startup-attachments", missing.name, reason, 1);
14777 let second = t
14778 .chat_notice_due()
14779 .expect("different attachment must notify");
14780 assert_ne!(first, second);
14781 assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
14782 }
14783
14784 #[test]
14785 fn resumed_instruction_is_unchanged_without_any_answers() {
14786 let t = task();
14787 assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
14788 }
14789
14790 #[test]
14791 fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
14792 let mut t = task();
14793 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
14794 let old = t.instruction.clone();
14798
14799 let refreshed = resumed_instruction(&old, &t);
14800 assert!(refreshed.starts_with(&old), "the original text is kept");
14801 assert!(refreshed.contains("Which backend?"));
14802 assert!(refreshed.contains("SQLite"));
14803 }
14804
14805 #[test]
14806 fn resumed_instruction_keeps_an_original_answers_heading() {
14807 let mut t = task();
14808 t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
14809 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
14810
14811 let refreshed = resumed_instruction(&t.instruction, &t);
14812
14813 assert!(
14814 refreshed.starts_with(&t.instruction),
14815 "an answers heading in the original instruction is not the appended block"
14816 );
14817 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
14818 assert!(refreshed.contains("Which backend?"));
14819 assert!(refreshed.contains("SQLite"));
14820
14821 let repeated = resumed_instruction(&refreshed, &t);
14822 assert_eq!(
14823 repeated, refreshed,
14824 "only the final appended block is refreshed"
14825 );
14826 }
14827
14828 #[test]
14829 fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
14830 let mut t = task();
14831 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
14832
14833 let once = resumed_instruction(&t.instruction, &t);
14837 let twice = resumed_instruction(&once, &t);
14838 assert_eq!(once, twice);
14839 assert_eq!(once.matches("Which backend?").count(), 1);
14840
14841 t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
14843 let refreshed = resumed_instruction(&once, &t);
14844 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
14845 assert!(refreshed.contains("Which backend?"));
14846 assert!(refreshed.contains("Which cache?"));
14847 }
14848
14849 #[test]
14850 fn prepare_instruction_covers_all_three_starters() {
14851 let mut t = task();
14852 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
14853
14854 assert_eq!(
14857 prepare_instruction(&Starter::Start, None, &t),
14858 Some(instruction_for(&t))
14859 );
14860
14861 let old = t.instruction.clone();
14864 assert_eq!(
14865 prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
14866 Some(resumed_instruction(&old, &t))
14867 );
14868
14869 assert_eq!(
14873 prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
14874 None
14875 );
14876 }
14877
14878 #[test]
14879 fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
14880 assert_eq!(
14881 choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
14882 Starter::Review("magi/eba2/A".to_owned())
14883 );
14884 }
14885
14886 #[test]
14887 fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
14888 assert_eq!(
14889 choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
14890 Starter::Start,
14891 "a vanished review branch must not fall back to resuming the old run either"
14892 );
14893 }
14894
14895 #[test]
14896 fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
14897 let mut t = task();
14898 t.start("old-run".to_owned());
14899 t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
14900 t.release();
14901 let branch = t.review_branch.take();
14902 assert_eq!(
14903 choose_starter(branch.as_deref(), true, Some("old-run")),
14904 Starter::Review("magi/eba2/A".to_owned()),
14905 "a review wins over resuming the old run"
14906 );
14907 }
14908
14909 #[test]
14910 fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
14911 assert_eq!(
14912 choose_starter(None, false, Some("some-run")),
14913 Starter::Resume("some-run".to_owned())
14914 );
14915 assert_eq!(choose_starter(None, false, None), Starter::Start);
14916 }
14917
14918 #[test]
14919 fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
14920 let mut released = task();
14921 released.start("stalled-run".to_owned());
14922 released.requeue();
14923 let unfinished = (!released.fresh_start)
14924 .then(|| Some("stalled-run".to_owned()))
14925 .flatten();
14926 assert_eq!(
14927 choose_starter(None, false, unfinished.as_deref()),
14928 Starter::Start,
14929 "release keeps run history but must not resume it"
14930 );
14931 assert_eq!(released.runs, ["stalled-run"]);
14932 }
14933
14934 #[test]
14935 fn landing_hold_receipt_survives_release_retry_and_checkpoint_removal() {
14936 let dir = tempfile::tempdir().unwrap();
14937 let queue = Queue::at(dir.path().join("queue"));
14938 let mut state = run_state(RunStatus::Blocked);
14939 state.merge_decision = Some(crate::merge_decision::Decision {
14940 question: "hold-inquiry".into(),
14941 target: crate::merge_decision::Target {
14942 pr: "https://example.test/pull/1".into(),
14943 head: "reviewed-head".into(),
14944 language: "en".into(),
14945 },
14946 choice: land::HOLD.into(),
14947 closed: false,
14948 replacement_run: None,
14949 replacement_pr: None,
14950 });
14951 let mut t = task();
14952 t.start(state.id.clone());
14953 settle_and_diagnose(
14954 &mut t,
14955 Verdict {
14956 status: RunStatus::Blocked,
14957 left_pr: true,
14958 quota_hit: false,
14959 parked: false,
14960 no_viable_candidates: false,
14961 },
14962 "held",
14963 2,
14964 &state,
14965 );
14966 queue.put(&mut t).unwrap();
14967 t.release_operator("chat", None);
14968 t.edit("revised".into(), "revised instruction".into())
14969 .unwrap();
14970 queue.put(&mut t).unwrap();
14971 drop(state);
14972 assert_eq!(
14973 queue
14974 .get(&t.id)
14975 .unwrap()
14976 .decision_effects
14977 .get("hold-inquiry"),
14978 Some(&format!("decision: {}", land::HOLD))
14979 );
14980 }
14981
14982 fn stopped_public_run(status: RunStatus) -> RunState {
14983 let mut state = run_state(status);
14984 state.driver_exited = true;
14985 state.config.graph.land = true;
14986 state.config.graph.review_rounds = 1;
14987 state.reviews = vec![review_round(1)];
14988 state.merge = Some(crate::run::MergeOutcome {
14989 mode: MergeMode::Pr,
14990 ok: false,
14991 detail: "landing stopped".into(),
14992 empty: false,
14993 });
14994 state.pr = Some(crate::run::PrRecord {
14995 url: "https://example.test/pull/1".into(),
14996 number: 1,
14997 state: "open".into(),
14998 checks: "red".into(),
14999 round: 1,
15000 rounds: 1,
15001 red_at_merge: Vec::new(),
15002 });
15003 state
15004 }
15005
15006 #[test]
15007 fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
15008 for status in [RunStatus::Blocked, RunStatus::Gating] {
15009 let home = tempfile::tempdir().unwrap();
15010 let mut state = stopped_public_run(status);
15011 state.save_under(home.path()).unwrap();
15012 assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
15013 assert!(!exhausted_review_budget(&state));
15014 let mut task = held_task_with(&state.id);
15015 task.release();
15016 let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
15017 assert_eq!(
15018 choose_starter(None, false, unfinished.as_deref()),
15019 Starter::Resume(state.id.clone())
15020 );
15021 let question = action_question(&state.id, resume_action(&state.id));
15022 assert_eq!(
15023 decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
15024 state.clone()
15025 )),
15026 ActionDecision::Resume(state.id.clone())
15027 );
15028 assert_eq!(
15030 crate::resume::validate(home.path(), &state.id).unwrap().id,
15031 state.id
15032 );
15033 let queue = Queue::at(home.path().join("queue"));
15034 let mut controlled = Task::new(
15035 "resume land".into(),
15036 state.instruction.clone(),
15037 state.repo.clone(),
15038 Source::Agent {
15039 run: "talk".into(),
15040 node: crate::queue::CHAT_NODE.into(),
15041 },
15042 );
15043 controlled.runs.push(state.id.clone());
15044 controlled.hold_machine(Some("land stopped".into()));
15045 queue.put(&mut controlled).unwrap();
15046 let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
15047 assert_eq!(resumed.status, TaskStatus::Queued);
15048 assert_eq!(
15049 resumed.resume_override.unwrap().pinned_run,
15050 Some(state.id.clone())
15051 );
15052 assert_eq!(resumed.attempts, 0);
15053 }
15054 }
15055
15056 #[test]
15057 fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
15058 for review_rounds in [0, 1] {
15059 let home = tempfile::tempdir().unwrap();
15060 let mut state = run_state(RunStatus::Blocked);
15061 state.config.graph.review_rounds = review_rounds;
15062 if review_rounds > 0 {
15063 let mut review = review_round(1);
15064 review.clean = true;
15065 state.reviews = vec![review];
15066 }
15067 state.gate_ran = true;
15068 state.gate = vec![crate::run::CommandOutcome {
15069 command: "verify".into(),
15070 code: Some(1),
15071 output_tail: "gate failed after repair budget exhausted".into(),
15072 duration_ms: 0,
15073 resource_blocked: false,
15074 ..Default::default()
15075 }];
15076 state.save_under(home.path()).unwrap();
15077 assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
15078 assert!(exhausted_review_budget(&state));
15079 let mut task = held_task_with(&state.id);
15080 task.release();
15081 assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
15082 let question = action_question(&state.id, resume_action(&state.id));
15083 assert_ne!(
15084 decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
15085 state.clone()
15086 )),
15087 ActionDecision::Resume(state.id.clone())
15088 );
15089 let error = crate::resume::validate(home.path(), &state.id)
15090 .unwrap_err()
15091 .to_string();
15092 assert!(!error.contains("review budget exhausted"), "{error}");
15093 assert!(
15094 error.contains(if review_rounds == 0 {
15095 "review is disabled"
15096 } else {
15097 "gate already ran"
15098 }),
15099 "{error}"
15100 );
15101
15102 state.gate_ran = false;
15104 state.gate.clear();
15105 assert!(!exhausted_review_budget(&state));
15106 assert_eq!(
15107 unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
15108 Some(state.id)
15109 );
15110 }
15111 }
15112
15113 #[test]
15114 fn sequencer_resource_resume_keeps_the_reserved_run_after_review_exhaustion() {
15115 let home = tempfile::tempdir().unwrap();
15116 let mut state = run_state(RunStatus::Blocked);
15117 state.config.graph.review_rounds = 1;
15118 let mut unresolved = review_round(1);
15119 unresolved.blocking = 1;
15120 unresolved.e2e.push(crate::run::CommandOutcome {
15121 command: "verify".into(),
15122 code: Some(1),
15123 output_tail: "previous verification failed".into(),
15124 duration_ms: 0,
15125 resource_blocked: false,
15126 artifact: None,
15127 failure_evidence: None,
15128 rerun_comparison: None,
15129 });
15130 state.reviews.push(unresolved);
15131 state.base_sync = Some(crate::run::BaseSync {
15132 tip: "base".into(),
15133 behind: 1,
15134 attempts: 0,
15135 conflict: None,
15136 already_in: None,
15137 });
15138 state.reserve_base_operation("winner", "base");
15139 state.resource_block = Some(crate::run::ResourceBlock {
15140 cause: crate::run::ResourceBlockCause::Other,
15141 node: "rebase".into(),
15142 kind: crate::rebase::SEQUENCER_INFRASTRUCTURE.into(),
15143 detail: "recording exec failed".into(),
15144 at: jiff::Timestamp::now(),
15145 });
15146 state.save_under(home.path()).unwrap();
15147 assert_eq!(
15148 crate::resume::validate(home.path(), &state.id).unwrap().id,
15149 state.id
15150 );
15151 assert_eq!(
15152 crate::repair_budget::legacy::classify(&state, "winner", "base").class,
15153 crate::repair_budget::legacy::Class::SequencerInfrastructure
15154 );
15155 state.finish_base_operation(None);
15156 state.save_under(home.path()).unwrap();
15157 assert!(crate::resume::validate(home.path(), &state.id).is_err());
15158 }
15159
15160 #[test]
15161 fn resource_blocked_verification_resumes_the_same_run() {
15162 for (kind, stage) in [
15163 ("cache", "clean"),
15164 ("coordination", "clean"),
15165 ("cache", "review-e2e"),
15166 ("coordination", "no-reviews"),
15167 ("coordination", "handoff"),
15168 ] {
15169 let home = tempfile::tempdir().unwrap();
15170 let mut state = run_state(RunStatus::Blocked);
15171 state.config.graph.review_rounds = 1;
15172 let mut review = review_round(1);
15173 review.clean = true;
15174 state.reviews = vec![review];
15175 if stage == "review-e2e" {
15176 let review = &mut state.reviews[0];
15177 review.clean = false;
15178 review.blocking = 1;
15179 review.e2e = vec![crate::run::CommandOutcome {
15180 command: "verify".into(),
15181 code: None,
15182 output_tail: "resource wait expired".into(),
15183 duration_ms: 0,
15184 resource_blocked: true,
15185 ..Default::default()
15186 }];
15187 } else if stage == "no-reviews" {
15188 state.config.graph.review_rounds = 0;
15189 state.reviews.clear();
15190 } else if stage == "handoff" {
15191 let review = &mut state.reviews[0];
15194 review.clean = false;
15195 review.blocking = 1;
15196 review.e2e = vec![crate::run::CommandOutcome {
15197 command: "verify".into(),
15198 code: Some(0),
15199 output_tail: String::new(),
15200 duration_ms: 0,
15201 resource_blocked: false,
15202 ..Default::default()
15203 }];
15204 }
15205 state.gate_ran = false;
15206 state.resource_block = Some(crate::run::ResourceBlock {
15207 cause: crate::run::ResourceBlockCause::Other,
15208 node: if stage == "review-e2e" {
15209 "review"
15210 } else {
15211 "gate"
15212 }
15213 .into(),
15214 kind: kind.into(),
15215 detail: "resource wait expired".into(),
15216 at: jiff::Timestamp::now(),
15217 });
15218 state.save_under(home.path()).unwrap();
15219 assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
15220 assert!(!exhausted_review_budget(&state));
15221 let mut task = held_task_with(&state.id);
15222 task.release();
15223 let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
15224 assert_eq!(
15225 choose_starter(None, false, unfinished.as_deref()),
15226 Starter::Resume(state.id.clone())
15227 );
15228 let question = action_question(&state.id, resume_action(&state.id));
15229 assert_eq!(
15230 decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
15231 state.clone()
15232 )),
15233 ActionDecision::Resume(state.id.clone())
15234 );
15235 assert_eq!(
15236 crate::resume::validate(home.path(), &state.id).unwrap().id,
15237 state.id
15238 );
15239 let queue = Queue::at(home.path().join("queue"));
15240 let mut controlled = Task::new(
15241 "resume verification".into(),
15242 state.instruction.clone(),
15243 state.repo.clone(),
15244 Source::Agent {
15245 run: "talk".into(),
15246 node: crate::queue::CHAT_NODE.into(),
15247 },
15248 );
15249 controlled.runs.push(state.id.clone());
15250 controlled.hold_machine(Some("verification resource unavailable".into()));
15251 queue.put(&mut controlled).unwrap();
15252 let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
15253 assert_eq!(resumed.status, TaskStatus::Queued);
15254 assert_eq!(
15255 resumed.resume_override.unwrap().pinned_run,
15256 Some(state.id.clone())
15257 );
15258 assert_eq!(resumed.attempts, 0);
15259
15260 state.config.graph.review_rounds = 1;
15262 let mut unresolved = review_round(1);
15263 unresolved.blocking = 1;
15264 state.reviews = vec![unresolved];
15265 state.resource_block = None;
15266 state.save_under(home.path()).unwrap();
15267 assert!(exhausted_review_budget(&state));
15268 assert!(crate::resume::validate(home.path(), &state.id).is_err());
15269 }
15270 }
15271
15272 #[tokio::test]
15273 async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
15274 if !crate::standalone_test(
15275 "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
15276 ) {
15277 return;
15278 }
15279 let home = tempfile::tempdir().unwrap();
15280 let mut owner = stopped_public_run(RunStatus::Blocked);
15281 owner.save_under(home.path()).unwrap();
15282 let history = vec![owner.id.clone()];
15283 let repo = owner.repo.clone();
15284 let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
15285 let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
15286 let initial =
15287 std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
15288 assert!(
15289 initial.is_pending(),
15290 "a busy record must not hold or resume the task"
15291 );
15292 owner.retired_to = Some("20260101-000001-bbbb".into());
15293 owner.save_under(home.path()).unwrap();
15294 drop(lock);
15295 let result = tokio::time::timeout(Duration::from_secs(10), lookup)
15296 .await
15297 .expect("ownership lock released")
15298 .expect("read settled owner");
15299 assert!(
15300 result.is_none(),
15301 "the retired owner must not be resumed from a stale read"
15302 );
15303 }
15304
15305 #[tokio::test]
15306 async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
15307 if !crate::standalone_test(
15308 "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
15309 ) {
15310 return;
15311 }
15312 let home = tempfile::tempdir().unwrap();
15313 let mut owner = stopped_public_run(RunStatus::Blocked);
15314 let repo = tempfile::tempdir().unwrap();
15315 crate::git::git(repo.path(), &["init"]).await.unwrap();
15316 owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
15317 owner.id = "20260101-000000-aaaa".into();
15318 owner.save_under(home.path()).unwrap();
15319 let mut successor = run_state(RunStatus::Blocked);
15320 successor.id = "20260101-000001-bbbb".into();
15321 successor.save_under(home.path()).unwrap();
15322 let runs = vec![owner.id.clone(), successor.id.clone()];
15323 assert_eq!(
15324 public_resume_owner(home.path(), &runs, &owner.repo)
15325 .await
15326 .unwrap()
15327 .unwrap()
15328 .id,
15329 owner.id
15330 );
15331 let subdir = owner.repo.join("nested");
15332 std::fs::create_dir(&subdir).unwrap();
15333 assert_eq!(
15334 public_resume_owner(home.path(), &runs, &subdir)
15335 .await
15336 .unwrap()
15337 .unwrap()
15338 .id,
15339 owner.id
15340 );
15341 #[cfg(unix)]
15342 {
15343 let alias = home.path().join("repo-alias");
15344 std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
15345 assert_eq!(
15346 public_resume_owner(home.path(), &runs, &alias.join("nested"))
15347 .await
15348 .unwrap()
15349 .unwrap()
15350 .id,
15351 owner.id
15352 );
15353 }
15354 let different = tempfile::tempdir().unwrap();
15355 crate::git::git(different.path(), &["init"]).await.unwrap();
15356 assert!(
15357 public_resume_owner(home.path(), &runs, different.path())
15358 .await
15359 .is_err()
15360 );
15361 owner.status = RunStatus::Superseded;
15364 owner.pr.as_mut().unwrap().state = "closed".into();
15365 owner.save_under(home.path()).unwrap();
15366 assert!(
15367 public_resume_owner(home.path(), &runs, &owner.repo)
15368 .await
15369 .unwrap()
15370 .is_none()
15371 );
15372 std::fs::remove_file(
15373 home.path()
15374 .join("runs")
15375 .join(&successor.id)
15376 .join("run.json"),
15377 )
15378 .unwrap();
15379 assert!(
15380 public_resume_owner(home.path(), &runs, &owner.repo)
15381 .await
15382 .is_err()
15383 );
15384 }
15385
15386 #[test]
15387 fn an_ordinary_release_keeps_a_resumable_run_available() {
15388 let mut released = task();
15389 released.start("stalled-run".to_owned());
15390 released.release();
15391 let unfinished = (!released.fresh_start)
15392 .then(|| Some("stalled-run".to_owned()))
15393 .flatten();
15394 assert_eq!(
15395 choose_starter(None, false, unfinished.as_deref()),
15396 Starter::Resume("stalled-run".to_owned()),
15397 "manual release must preserve the normal resume path"
15398 );
15399 }
15400
15401 #[test]
15402 fn resume_refusals_explain_admission_without_changing_task_or_run() {
15403 use crate::handover::{ResumeRefusal, resume_refusal_under};
15404 let home = tempfile::tempdir().unwrap();
15405 let mut exhausted = run_state(RunStatus::Blocked);
15406 exhausted.driver_exited = true;
15407 exhausted.config.graph.review_rounds = 3;
15408 exhausted.reviews = (1..=3).map(review_round).collect();
15409 for refusal in [
15410 ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
15411 ResumeRefusal::Status(RunStatus::Ready),
15412 ResumeRefusal::Released("20261022-000000-aaaa".into()),
15413 ResumeRefusal::Retired("retirement-successor".into()),
15414 ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
15415 ] {
15416 let mut state = exhausted.clone();
15417 let expected = match refusal {
15418 ResumeRefusal::Status(_) => {
15419 state.status = RunStatus::Ready;
15420 "status `ready`"
15421 }
15422 ResumeRefusal::Released(ref target) => {
15423 state.released_to = Some(target.clone());
15424 "execution was released"
15425 }
15426 ResumeRefusal::Retired(ref target) => {
15427 state.retired_to = Some(target.clone());
15428 "execution was retired"
15429 }
15430 ResumeRefusal::OwnershipTransferred(ref target) => {
15431 state.pr_taken_over_by = Some(target.clone());
15432 "PR ownership was transferred"
15433 }
15434 _ => "review budget exhausted (3/3 rounds used)",
15435 };
15436 assert_eq!(
15437 resume_refusal_under(&state, Some(home.path())),
15438 Some(refusal.clone())
15439 );
15440 assert_eq!(
15441 refusal.successor(),
15442 state
15443 .released_to
15444 .as_deref()
15445 .or(state.retired_to.as_deref())
15446 .or(state.pr_taken_over_by.as_deref())
15447 );
15448 state.save_under(home.path()).unwrap();
15449 let queue = Queue::at(home.path().join("queue"));
15450 let mut task = Task::new(
15451 "retained implementation".into(),
15452 state.instruction.clone(),
15453 state.repo.clone(),
15454 Source::Agent {
15455 run: "talk".into(),
15456 node: crate::queue::CHAT_NODE.into(),
15457 },
15458 );
15459 task.runs.push(state.id.clone());
15460 task.hold_machine(Some("stopped".into()));
15461 queue.put(&mut task).unwrap();
15462 let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
15463 let before_run = serde_json::to_value(&state).unwrap();
15464 let error = crate::chat_control::resume(&queue, home.path(), &state.id)
15465 .unwrap_err()
15466 .to_string();
15467 assert!(error.contains(expected), "{error}");
15468 assert!(!error.contains("only a stalled or blocked"), "{error}");
15469 if matches!(refusal, ResumeRefusal::Status(_)) {
15470 assert!(
15471 error.contains("is final; there is nothing left to resume"),
15472 "{error}"
15473 );
15474 }
15475 if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
15476 assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
15477 assert!(error.contains("review-only successor with a new review budget"));
15478 assert!(error.contains("does not resume this run"));
15479 }
15480 for target in [
15481 &state.released_to,
15482 &state.retired_to,
15483 &state.pr_taken_over_by,
15484 ]
15485 .into_iter()
15486 .flatten()
15487 {
15488 let short = if state.retired_to.as_ref() == Some(target) {
15489 target.as_str()
15490 } else {
15491 crate::run::short_of(target)
15492 };
15493 assert!(
15494 error.contains(&format!("run {short}; inspect `magi show {short}`")),
15495 "{error}"
15496 );
15497 if short != target {
15498 assert!(!error.contains(target), "full successor id leaked: {error}");
15499 }
15500 }
15501 assert_eq!(
15502 serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
15503 before_task
15504 );
15505 assert_eq!(
15506 serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
15507 .unwrap(),
15508 before_run
15509 );
15510 let question = action_question(&state.id, resume_action(&state.id));
15511 for phrases in [&PHRASES_EN, &PHRASES_JA] {
15512 let decision = decide_action(home.path(), &task, &question, phrases, |id| {
15513 RunState::load_under(id, home.path())
15514 });
15515 let ActionDecision::Refuse(detail) = decision else {
15516 panic!(
15517 "refusal expected: decision={decision:?}, refusal={refusal:?}, run={}, home={}",
15518 state.id,
15519 home.path().display()
15520 );
15521 };
15522 assert!(detail.contains(expected), "{detail}");
15523 }
15524 }
15525 exhausted.status = RunStatus::Ready;
15527 exhausted.released_to = Some("released".into());
15528 exhausted.retired_to = Some("retired".into());
15529 exhausted.pr_taken_over_by = Some("owner".into());
15530 let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
15531 assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
15532 let detail = reason.diagnostic(&exhausted);
15533 for target in ["released", "retired", "owner"] {
15534 assert!(detail.contains(&format!("magi show {target}")));
15535 }
15536 }
15537
15538 #[test]
15539 fn resume_action_ignores_question_checkpoints_in_another_home() {
15540 crate::run::pin_test_home();
15541 let home = tempfile::tempdir().unwrap();
15542 let mut state = run_state(RunStatus::Blocked);
15543 state.id = format!(
15546 "resume-context-{}",
15547 home.path().file_name().unwrap().to_str().unwrap()
15548 );
15549 state.driver_exited = true;
15550 state.config.graph.review_rounds = 1;
15551 state.reviews = vec![review_round(1)];
15552 state.save_under(home.path()).unwrap();
15553 let task = held_task_with(&state.id);
15554 let answer = action_question(&state.id, resume_action(&state.id));
15555 let mut checkpoint = approval_question(&state.id);
15556 let foreign = Questions::open();
15557 foreign.put(&mut checkpoint).unwrap();
15558 let refusal = crate::handover::resume_refusal_under(&state, Some(home.path()));
15559 let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
15560 RunState::load_under(id, home.path())
15561 });
15562 let matching: Vec<_> = foreign
15563 .list()
15564 .into_iter()
15565 .filter(|q| q.run == state.id && q.status.open())
15566 .collect();
15567 std::fs::remove_file(foreign.path_of(&checkpoint.id)).unwrap();
15568 assert!(
15569 matches!(decision, ActionDecision::Refuse(_)),
15570 "decision={decision:?}, refusal={refusal:?}, run={}, home={}, foreign_home={}, matching={matching:?}",
15571 state.id,
15572 home.path().display(),
15573 crate::run::test_home().display()
15574 );
15575 assert_eq!(
15576 refusal,
15577 Some(crate::handover::ResumeRefusal::ReviewBudget { used: 1, limit: 1 })
15578 );
15579 let local = Questions::at(home.path().join("questions"));
15580 for status in [
15581 ask::QuestionStatus::Open,
15582 ask::QuestionStatus::Answered,
15583 ask::QuestionStatus::Abandoned,
15584 ] {
15585 let mut question = checkpoint.clone();
15586 match status {
15587 ask::QuestionStatus::Open => {}
15588 ask::QuestionStatus::Answered => {
15589 question
15590 .answer(ask::Answer::Choice(question.choices[0].clone()))
15591 .unwrap();
15592 }
15593 ask::QuestionStatus::Abandoned => question.abandon("fixture closed"),
15594 }
15595 local.put(&mut question).unwrap();
15596 let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
15597 RunState::load_under(id, home.path())
15598 });
15599 if status.open() {
15600 assert_eq!(decision, ActionDecision::Resume(state.id.clone()));
15601 } else {
15602 assert!(
15603 matches!(decision, ActionDecision::Refuse(ref detail) if detail.contains("review budget exhausted")),
15604 "status={status:?}, decision={decision:?}"
15605 );
15606 }
15607 }
15608 }
15609
15610 #[test]
15611 fn resume_action_checks_the_driver_lease_in_the_supplied_home() {
15612 let home = tempfile::tempdir().unwrap();
15613 let mut state = run_state(RunStatus::Stalled);
15614 state.id = format!(
15615 "resume-driver-{}",
15616 home.path().file_name().unwrap().to_str().unwrap()
15617 );
15618 state.driver_claimed = Some(false);
15619 state.save_under(home.path()).unwrap();
15620 let task = held_task_with(&state.id);
15621 let question = action_question(&state.id, resume_action(&state.id));
15622 let decide = || {
15623 decide_action(home.path(), &task, &question, &PHRASES_EN, |id| {
15624 RunState::load_under(id, home.path())
15625 })
15626 };
15627 let lease = crate::driver::maintenance(home.path(), &state.id).unwrap();
15628 assert_eq!(state.liveness_under(home.path(), false), Liveness::Live);
15629 let expected_lock = home.path().join("runs").join(&state.id).join("driver.lock");
15630 match decide() {
15631 ActionDecision::Refuse(detail) => {
15632 assert!(
15633 detail.starts_with("run already has a live driver: "),
15634 "{detail}"
15635 );
15636 assert!(
15637 detail.contains(&expected_lock.display().to_string()),
15638 "{detail}"
15639 );
15640 }
15641 other => panic!("expected live driver refusal, got {other:?}"),
15642 }
15643 drop(lease);
15644 assert_eq!(decide(), ActionDecision::Resume(state.id.clone()));
15645 }
15646
15647 #[test]
15648 fn resume_checkpoint_admission_uses_the_supplied_question_store() {
15649 let home = tempfile::tempdir().unwrap();
15650 let mut state = run_state(RunStatus::Blocked);
15651 state.driver_exited = true;
15652 state.config.graph.review_rounds = 1;
15653 state.reviews = vec![review_round(1)];
15654 assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
15655 for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
15656 let mut saved = state.clone();
15657 match checkpoint {
15658 "publication" => saved.pr_publication_pending = true,
15659 "approval" => {
15660 saved.land_approval = Some(crate::run::LandApproval {
15661 question: "approval".into(),
15662 head: "head".into(),
15663 })
15664 }
15665 "armed" => saved.land_armed_head = Some("head".into()),
15666 "landing" => saved.status = RunStatus::Landing,
15667 _ => {
15668 let mut question = ask::Question::new(
15669 saved.id.clone(),
15670 "review".into(),
15671 "review-1".into(),
15672 "continue?".into(),
15673 String::new(),
15674 vec!["continue".into()],
15675 );
15676 ask::Questions::at(home.path().join("questions"))
15677 .put(&mut question)
15678 .unwrap();
15679 }
15680 }
15681 saved.save_under(home.path()).unwrap();
15682 assert!(
15683 crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
15684 "{checkpoint}"
15685 );
15686 assert!(
15687 crate::resume::validate(home.path(), &saved.id).is_ok(),
15688 "{checkpoint}"
15689 );
15690 }
15691 }
15692
15693 #[test]
15694 fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
15695 let mut state = run_state(RunStatus::Blocked);
15696 state.config.graph.review_rounds = 3;
15697 state.reviews = vec![review_round(1), review_round(2), review_round(3)];
15698 assert!(exhausted_review_budget(&state));
15699
15700 state.reviews.pop();
15702 assert!(!exhausted_review_budget(&state));
15703
15704 let mut stalled = run_state(RunStatus::Stalled);
15707 stalled.config.graph.review_rounds = 1;
15708 stalled.reviews = vec![review_round(1)];
15709 assert!(!exhausted_review_budget(&stalled));
15710 }
15711
15712 fn review_round(round: usize) -> crate::run::ReviewRound {
15713 crate::run::ReviewRound {
15714 round,
15715 head: "deadbeef".to_owned(),
15716 verified_head: None,
15717 verified_at: None,
15718 reviews: Vec::new(),
15719 e2e: Vec::new(),
15720 verify_retried: false,
15721 e2e_deferred: false,
15722 e2e_defer_reason: None,
15723 fix: None,
15724 blocking: 0,
15725 answered: 1,
15726 expected: 1,
15727 clean: false,
15728 progressed: true,
15729 vote_split: false,
15730 reconsideration: Vec::new(),
15731 verdict: None,
15732 }
15733 }
15734
15735 #[test]
15736 fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
15737 let mut run = RunState::new(
15738 PathBuf::from("/repo"),
15739 "main".to_owned(),
15740 "abc1234def".to_owned(),
15741 "add retries".to_owned(),
15742 Config::default(),
15743 );
15744 run.status = RunStatus::Judging;
15745 run.parked = true;
15746 let mut task = Task::new(
15747 "add retries".to_owned(),
15748 "add retries".to_owned(),
15749 PathBuf::from("/repo"),
15750 crate::queue::Source::Human,
15751 );
15752 task.status = TaskStatus::Failed;
15753 task.runs = vec![run.id.clone()];
15754 let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
15755 assert!(with(&task, &run), "parked after judging is the case");
15756 let mut parked_task = task.clone();
15757 parked_task.status = TaskStatus::Parked;
15758 assert!(with(&parked_task, &run), "the Parked status is the case");
15759
15760 let mut not_parked = run.clone();
15761 not_parked.parked = false;
15762 not_parked.status = RunStatus::Stalled;
15763 assert!(!with(&task, ¬_parked), "a stall is the conductor's");
15764
15765 let mut fresh = task.clone();
15766 fresh.fresh_start = true;
15767 assert!(!with(&fresh, &run), "a requeue asked for a new competition");
15768
15769 let mut review = task.clone();
15770 review.review_branch = Some("magi/x/A".to_owned());
15771 assert!(!with(&review, &run), "review is ranked before resume");
15772
15773 let mut held = task.clone();
15774 held.status = TaskStatus::Held;
15775 assert!(!with(&held, &run), "a hold stays visible to the conductor");
15776
15777 let mut released = run.clone();
15778 released.released_to = Some("20260901-000000-new1".to_owned());
15779 assert!(!with(&task, &released), "nothing left to resume into");
15780
15781 assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
15782 "unreadable"
15783 )));
15784 }
15785
15786 #[test]
15787 fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
15788 let mut released = RunState::new(
15789 PathBuf::from("/repo"),
15790 "main".to_owned(),
15791 "abc1234def".to_owned(),
15792 "add retries".to_owned(),
15793 Config::default(),
15794 );
15795 released.status = RunStatus::Blocked;
15796 assert_eq!(
15797 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
15798 Some(released.id.clone())
15799 );
15800 released.released_to = Some("20260901-000000-new1".to_owned());
15801 assert_eq!(
15802 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
15803 None,
15804 "there is nothing left to resume it into"
15805 );
15806 }
15807
15808 #[test]
15809 fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
15810 let mut exhausted = RunState::new(
15819 PathBuf::from("/repo"),
15820 "main".to_owned(),
15821 "abc1234def".to_owned(),
15822 "add retries".to_owned(),
15823 Config::default(),
15824 );
15825 exhausted.status = RunStatus::Blocked;
15826 exhausted.config.graph.review_rounds = 1;
15827 exhausted.reviews = vec![review_round(1)];
15828
15829 assert_eq!(
15830 unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
15831 None,
15832 "an exhausted `Blocked` run must not be offered as resumable"
15833 );
15834
15835 let mut has_budget_left = RunState::new(
15838 PathBuf::from("/repo"),
15839 "main".to_owned(),
15840 "abc1234def".to_owned(),
15841 "add retries".to_owned(),
15842 Config::default(),
15843 );
15844 has_budget_left.status = RunStatus::Blocked;
15845 has_budget_left.config.graph.review_rounds = 3;
15846 has_budget_left.reviews = vec![review_round(1)];
15847
15848 assert_eq!(
15849 unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
15850 Ok(has_budget_left.clone())
15851 }),
15852 Some(has_budget_left.id.clone())
15853 );
15854 }
15855
15856 #[test]
15857 fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
15858 let mut run = RunState::new(
15859 PathBuf::from("/repo"),
15860 "main".to_owned(),
15861 "abc1234def".to_owned(),
15862 "add retries".to_owned(),
15863 Config::default(),
15864 );
15865 run.status = RunStatus::Blocked;
15866 run.config.graph.review_rounds = 1;
15867 run.reviews = vec![review_round(1)];
15868 run.pr_publication_pending = true;
15869 assert_eq!(
15870 unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
15871 Some(run.id.clone()),
15872 "a spent review budget must not turn a failed publication into a re-competition"
15873 );
15874 }
15875
15876 #[test]
15877 fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
15878 let mut task = Task::new(
15879 "recover work".into(),
15880 "recover work".into(),
15881 PathBuf::from("/repo"),
15882 crate::queue::Source::Human,
15883 );
15884 let mut history = std::collections::BTreeMap::new();
15885 for index in 0..8 {
15886 let mut run = run_state(RunStatus::Blocked);
15887 run.id = format!("20260101-000000-{index:04}");
15888 run.base_commit = format!("upstream-{index}");
15889 if index > 0 {
15891 run.candidates.clear();
15892 }
15893 task.runs.extend([run.id.clone(), run.id.clone()]);
15894 history.insert(run.id.clone(), run);
15895 task.requeue();
15896 }
15897 let check = |task: &Task, starter: &Starter, limit| {
15898 retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
15899 };
15900 assert!(
15901 check(&task, &Starter::Start, 8)
15902 .unwrap()
15903 .contains("8 unretired")
15904 );
15905 assert!(check(&task, &Starter::Start, 9).is_none());
15906 assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
15907 task.release_operator("owner", None);
15908 assert_eq!(task.attempts, 0);
15909 let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
15910 assert!(check(&restored, &Starter::Start, 8).is_some());
15911 assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
15912 assert!(check(&restored, &Starter::Start, 0).is_none());
15913 }
15914
15915 #[test]
15916 fn retained_attempt_bound_includes_failed_startups_without_execution_history() {
15917 let tmp = tempfile::tempdir().unwrap();
15918 let mut task = Task::new(
15919 "recover selected PR".into(),
15920 "preserve implementation".into(),
15921 tmp.path().join("repo"),
15922 crate::queue::Source::Human,
15923 );
15924 let mut failed = run_state(RunStatus::Failed);
15925 failed.id = "20260101-000000-fail".into();
15926 failed.candidates.clear();
15927 failed.prep_complete = Some(false);
15928 failed.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
15929 failed.startup = Some(crate::run::Startup {
15930 kind: "pr-recovery".into(),
15931 branch: Some("selected-public-head".into()),
15932 stage: "worktree-setup".into(),
15933 complete: false,
15934 failure: Some("setup modified a tracked file and failed".into()),
15935 });
15936 let worktree = failed.worktree_root().join("under-review");
15939 std::fs::create_dir_all(&worktree).unwrap();
15940 let retained_edit = worktree.join("implementation");
15941 std::fs::write(&retained_edit, "retained setup edit").unwrap();
15942 task.record_startup_failure(crate::run::StartupFailure {
15943 run: failed.id.clone(),
15944 stage: "worktree-setup".into(),
15945 });
15946 let task: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
15947 assert!(task.runs.is_empty() && task.passes.is_empty());
15948 assert_eq!(task.attempts, 0);
15949 let starter = Starter::Review("selected-public-head".into());
15950 assert!(
15951 retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone()))
15952 .unwrap()
15953 .contains("1 unretired")
15954 );
15955 assert!(retained_attempt_hold(&task, &starter, 2, |_| Ok(failed.clone())).is_none());
15956 assert!(
15957 retained_attempt_hold(&task, &starter, 2, |_| anyhow::bail!("unreadable"))
15958 .unwrap()
15959 .contains("Cannot verify")
15960 );
15961 let mut mixed = task.clone();
15963 mixed.runs.push(failed.id.clone());
15964 mixed
15965 .startup_failures
15966 .push(task.startup_failures[0].clone());
15967 assert!(retained_attempt_hold(&mixed, &starter, 2, |_| Ok(failed.clone())).is_none());
15968 failed.retired_to = Some("verified-recovery-owner".into());
15969 assert!(retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone())).is_none());
15970 assert!(
15971 retained_attempt_hold(&task, &Starter::Resume(failed.id.clone()), 1, |_| {
15972 panic!("resuming the existing owner must not allocate a new attempt")
15973 })
15974 .is_none()
15975 );
15976 assert_eq!(
15977 std::fs::read_to_string(retained_edit).unwrap(),
15978 "retained setup edit"
15979 );
15980 assert!(task.runs.is_empty() && task.passes.is_empty());
15981 assert_eq!(task.attempts, 0);
15982 }
15983
15984 #[test]
15985 fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
15986 let mut task = Task::new(
15987 "recover work".into(),
15988 "recover work".into(),
15989 PathBuf::from("/repo"),
15990 crate::queue::Source::Human,
15991 );
15992 let mut run = run_state(RunStatus::Superseded);
15993 run.candidates.clear();
15994 task.runs.push(run.id.clone());
15995 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
15996 run.retired_to = Some("authority".into());
15997 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
15998 run.retired_to = None;
15999 run.released_to = Some("authority".into());
16000 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
16001 assert!(
16002 retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
16003 .unwrap()
16004 .contains("Cannot verify")
16005 );
16006 assert!(
16008 retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
16009 panic!("resume must not load historical attempts")
16010 })
16011 .is_none()
16012 );
16013 }
16014
16015 #[test]
16016 fn retired_resume_requires_a_valid_same_repository_authority() {
16017 let mut source = run_state(RunStatus::Blocked);
16018 let mut empty = run_state(RunStatus::Blocked);
16019 empty.retired_to = Some(source.id.clone());
16020 let runs = vec![source.id.clone(), empty.id.clone()];
16021 let resolve = |source: &RunState, empty: &RunState| {
16022 unfinished_run_with(&runs, "fixture", |id| {
16023 if id == source.id {
16024 Ok(source.clone())
16025 } else if id == empty.id {
16026 Ok(empty.clone())
16027 } else {
16028 bail!("unreadable authority")
16029 }
16030 })
16031 };
16032 assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
16033 assert_eq!(
16034 choose_starter(None, false, resolve(&source, &empty).as_deref()),
16035 Starter::Resume(source.id.clone())
16036 );
16037 source.retired_to = Some(empty.id.clone());
16038 assert!(
16039 resolve(&source, &empty).is_none(),
16040 "cycles do not revive obsolete runs"
16041 );
16042 source.retired_to = None;
16043 source.repo = PathBuf::from("/another-repository");
16044 assert!(resolve(&source, &empty).is_none());
16045 source.repo = empty.repo.clone();
16046 source.released_to = Some("later".into());
16047 assert!(resolve(&source, &empty).is_none());
16048 empty.retired_to = Some("unlisted-run".into());
16049 assert!(resolve(&source, &empty).is_none());
16050 }
16051
16052 #[test]
16053 fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
16054 let mut older_stalled = RunState::new(
16062 PathBuf::from("/repo"),
16063 "main".to_owned(),
16064 "abc1234def".to_owned(),
16065 "add retries".to_owned(),
16066 Config::default(),
16067 );
16068 older_stalled.status = RunStatus::Stalled;
16069
16070 let mut newest_exhausted = RunState::new(
16071 PathBuf::from("/repo"),
16072 "main".to_owned(),
16073 "abc1234def".to_owned(),
16074 "add retries".to_owned(),
16075 Config::default(),
16076 );
16077 newest_exhausted.status = RunStatus::Blocked;
16078 newest_exhausted.config.graph.review_rounds = 1;
16079 newest_exhausted.reviews = vec![review_round(1)];
16080
16081 assert_eq!(
16082 unfinished_run_with(
16083 &[older_stalled.id.clone(), newest_exhausted.id.clone()],
16084 "t",
16085 |_| Ok(newest_exhausted.clone())
16086 ),
16087 None,
16088 "the newest run is exhausted, so nothing here is worth resuming - \
16089 least of all the older, already-superseded run"
16090 );
16091 }
16092
16093 #[test]
16094 fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
16095 assert_eq!(
16096 unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
16097 Err(anyhow::anyhow!("fixture is absent"))
16098 }),
16099 None
16100 );
16101 }
16102
16103 fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
16104 let mut q = ask::Question::new(
16105 run.to_owned(),
16106 "implement".to_owned(),
16107 "impl-A".to_owned(),
16108 "continue?".to_owned(),
16109 String::new(),
16110 vec!["resume で続行する".to_owned(), "other".to_owned()],
16111 );
16112 q.actions.insert("resume で続行する".to_owned(), action);
16113 q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
16114 .unwrap();
16115 q
16116 }
16117
16118 fn held_task_with(run: &str) -> Task {
16119 let mut t = task();
16120 t.runs = vec![run.to_owned()];
16121 t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
16122 t
16123 }
16124
16125 fn resume_action(run: &str) -> ask::ChoiceAction {
16126 ask::ChoiceAction::Resume { run: run.into() }
16127 }
16128
16129 #[test]
16130 fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
16131 let home = crate::run::test_home();
16132 for parked in [false, true] {
16133 let mut t = task();
16134 t.start("A".into());
16135 t.start("B".into());
16136 assert_eq!(t.runs, vec!["A", "B"]);
16137 t.start("A".into());
16138 let mut resumed = run_state(RunStatus::Blocked);
16139 resumed.id = "A".into();
16140 resumed.parked = parked;
16141 resumed.driver_exited = true;
16142 t.hold_machine(Some("resumed run stopped".into()));
16143 let q = action_question("A", resume_action("A"));
16144 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
16145 assert_eq!(
16146 decide_action(&home, &t, &q, &PHRASES_EN, |id| {
16147 assert_eq!(id, "A");
16148 Ok(resumed.clone())
16149 }),
16150 ActionDecision::Resume("A".into())
16151 );
16152 assert_eq!(
16153 action_standing(&t, &action_question("B", resume_action("B"))),
16154 ActionStanding::Stale
16155 );
16156 t.release_operator("cli", None);
16157 let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
16158 assert_eq!(id, "A");
16159 Ok(resumed.clone())
16160 });
16161 assert_eq!(
16162 choose_starter(None, false, unfinished.as_deref()),
16163 Starter::Resume("A".into())
16164 );
16165 assert_eq!(t.runs, vec!["B", "A"]);
16166 }
16167 }
16168
16169 #[test]
16170 fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
16171 let home = crate::run::test_home();
16172 let mut state = crate::land::tests::repair_state(true, true);
16173 state.status = RunStatus::Landing;
16174 state.parked = true;
16175 state.driver_exited = true;
16176 let mut q = ask::Question::new(
16177 state.id.clone(),
16178 land::APPROVAL_NODE.into(),
16179 "land".into(),
16180 "Merge?".into(),
16181 String::new(),
16182 vec![land::APPROVE.into(), land::HOLD.into()],
16183 );
16184 q.id = state.id.clone();
16185 state.land_approval = Some(crate::run::LandApproval {
16186 question: q.id.clone(),
16187 head: "current-head".into(),
16188 });
16189 assert!(land::upgrade_repair_choice(&mut q, &state));
16190 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
16191 let mut task = held_task_with(&state.id);
16192 task.status = TaskStatus::Parked;
16193 assert_eq!(
16194 decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
16195 ActionDecision::Resume(state.id.clone())
16196 );
16197 q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
16198 q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
16199 task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
16200 assert_eq!(
16201 decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
16202 ActionDecision::Resume(state.id.clone()),
16203 "a repair answer newer than the manual hold resumes the existing owner"
16204 );
16205 task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
16206 for answered_at in [q.answered_at, None] {
16207 let mut older = q.clone();
16208 older.answered_at = answered_at;
16209 let refused = decide_action(&home, &task, &older, &PHRASES_EN, |_| {
16210 panic!("a later manual hold must prevent dispatch")
16211 });
16212 let ActionDecision::Refuse(reason) = refused else {
16213 panic!("expected an actionable refusal, got {refused:?}");
16214 };
16215 assert!(reason.contains("later operator decision"));
16216 assert!(reason.contains(&format!("magi task release {}", task.id)));
16217 }
16218 task.operator_decided_at = None;
16219 let mut superseded = state.clone();
16220 superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
16221 assert_eq!(
16222 decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(superseded)),
16223 ActionDecision::Stale
16224 );
16225 for case in 1..4 {
16226 let mut changed = state.clone();
16227 match case {
16228 1 => changed.status = RunStatus::Blocked,
16229 2 => changed.released_to = Some("new-owner".into()),
16230 _ => changed.land_approval.as_mut().unwrap().head.clear(),
16231 }
16232 assert!(matches!(
16233 decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(changed)),
16234 ActionDecision::Refuse(_)
16235 ));
16236 }
16237 assert!(matches!(
16238 decide_action(&home, &task, &q, &PHRASES_EN, |_| anyhow::bail!(
16239 "missing owner"
16240 )),
16241 ActionDecision::Refuse(_)
16242 ));
16243 task.runs.push("replacement".into());
16244 task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
16245 assert_eq!(
16246 decide_action(&home, &task, &q, &PHRASES_EN, |_| panic!(
16247 "old owner must not load"
16248 )),
16249 ActionDecision::Stale
16250 );
16251 }
16252
16253 #[test]
16254 fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
16255 let mut state = crate::land::tests::repair_state(true, true);
16256 state.status = RunStatus::Landing;
16257 state.parked = true;
16258 state.driver_exited = true;
16259 let mut q = ask::Question::new(
16260 state.id.clone(),
16261 land::APPROVAL_NODE.into(),
16262 "land".into(),
16263 "Merge?".into(),
16264 String::new(),
16265 vec![land::APPROVE.into(), land::HOLD.into()],
16266 );
16267 q.id = state.id.clone();
16268 state.land_approval = Some(crate::run::LandApproval {
16269 question: q.id.clone(),
16270 head: "current-head".into(),
16271 });
16272 state.save().unwrap();
16273 land::upgrade_repair_choice(&mut q, &state);
16274 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
16275 Questions::open().put(&mut q).unwrap();
16276 let tmp = tempfile::tempdir().unwrap();
16277 let queue = Queue::at(tmp.path().join("queue"));
16278 let mut task = held_task_with(&state.id);
16279 task.status = TaskStatus::Parked;
16280 queue.put(&mut task).unwrap();
16281 let empty = Arc::new(tokio::sync::Semaphore::new(0));
16282 let free = Arc::new(tokio::sync::Semaphore::new(1));
16283 assert!(matches!(
16284 claim_dispatch(&queue, &task, false, &empty, &free),
16285 Err(SkipReason::OrdinaryCapacity)
16286 ));
16287 assert!(matches!(
16288 claim_dispatch(&queue, &task, true, &free, &free),
16289 Err(SkipReason::CoolingDown)
16290 ));
16291 let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
16292 assert!(claim.permit.is_some());
16293 assert!(matches!(
16294 claim_dispatch(&queue, &task, false, &free, &free),
16295 Err(SkipReason::ClaimUnavailable)
16296 ));
16297 drop(claim);
16298 Questions::open()
16299 .update(&q.id, |q| {
16300 q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
16301 Ok(())
16302 })
16303 .unwrap();
16304 let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
16305 assert!(claim.permit.is_none());
16306 assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
16307 }
16308
16309 #[test]
16310 fn decide_action_resumes_only_the_latest_resumable_run() {
16311 let home = crate::run::test_home();
16312 let t = held_task_with("r1");
16313 let q = action_question("r1", resume_action("r1"));
16314 let load = |s: RunState| move |_: &str| Ok(s);
16315 assert_eq!(
16316 decide_action(
16317 &home,
16318 &t,
16319 &q,
16320 &PHRASES_EN,
16321 load(run_state(RunStatus::Blocked))
16322 ),
16323 ActionDecision::Resume("r1".into())
16324 );
16325 let q_other = action_question("r1", resume_action("r0"));
16327 assert!(matches!(
16328 decide_action(
16329 &home,
16330 &t,
16331 &q_other,
16332 &PHRASES_EN,
16333 load(run_state(RunStatus::Blocked))
16334 ),
16335 ActionDecision::Refuse(_)
16336 ));
16337 assert!(matches!(
16339 decide_action(
16340 &home,
16341 &t,
16342 &q,
16343 &PHRASES_EN,
16344 load(run_state(RunStatus::Ready))
16345 ),
16346 ActionDecision::Refuse(_)
16347 ));
16348 let mut released = run_state(RunStatus::Blocked);
16350 released.released_to = Some("elsewhere".into());
16351 assert!(matches!(
16352 decide_action(&home, &t, &q, &PHRASES_EN, load(released)),
16353 ActionDecision::Refuse(_)
16354 ));
16355 assert!(matches!(
16357 decide_action(&home, &t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
16358 ActionDecision::Refuse(_)
16359 ));
16360 }
16361
16362 #[test]
16363 fn decide_action_ignores_a_question_about_an_earlier_run() {
16364 let home = crate::run::test_home();
16365 let mut t = held_task_with("r1");
16366 t.runs.push("r2".to_owned());
16367 let never = |_: &str| -> Result<RunState> { bail!("not read") };
16368 assert_eq!(
16369 decide_action(
16370 &home,
16371 &t,
16372 &action_question("r1", ask::ChoiceAction::Done),
16373 &PHRASES_EN,
16374 never
16375 ),
16376 ActionDecision::Stale
16377 );
16378 }
16379
16380 #[test]
16381 fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
16382 let home = crate::run::test_home();
16383 let mut t = held_task_with("r1");
16384 let never = |_: &str| -> Result<RunState> { bail!("not read") };
16385 assert_eq!(
16386 decide_action(
16387 &home,
16388 &t,
16389 &action_question("r1", ask::ChoiceAction::Requeue),
16390 &PHRASES_EN,
16391 never
16392 ),
16393 ActionDecision::Requeue
16394 );
16395 let done_q = action_question("r1", ask::ChoiceAction::Done);
16396 assert_eq!(
16397 decide_action(&home, &t, &done_q, &PHRASES_EN, never),
16398 ActionDecision::Done
16399 );
16400 t.mark_action_applied(&done_q.id);
16401 assert_eq!(
16402 decide_action(&home, &t, &done_q, &PHRASES_EN, never),
16403 ActionDecision::Skip
16404 );
16405
16406 let mut plain = action_question("r1", ask::ChoiceAction::Done);
16408 plain.actions.clear();
16409 assert_eq!(
16410 decide_action(&home, &held_task_with("r1"), &plain, &PHRASES_EN, never),
16411 ActionDecision::Skip
16412 );
16413 let mut running = held_task_with("r1");
16415 running.status = TaskStatus::Running;
16416 assert_eq!(
16417 decide_action(
16418 &home,
16419 &running,
16420 &action_question("r1", ask::ChoiceAction::Done),
16421 &PHRASES_EN,
16422 never
16423 ),
16424 ActionDecision::Skip
16425 );
16426 }
16427
16428 #[test]
16429 fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
16430 crate::run::pin_test_home();
16431 for legacy in [false, true] {
16432 let dir = tempfile::tempdir().unwrap();
16433 let queue = Queue::at(dir.path().join("queue"));
16434 let questions = Questions::at(dir.path().join("questions"));
16435 let run = "20260101-000000-hold";
16436 let mut task = held_task_with(run);
16437 task.status = TaskStatus::Parked;
16438 let mut q = ask::Question::new(
16439 run.into(),
16440 land::APPROVAL_NODE.into(),
16441 "land".into(),
16442 "Repair?".into(),
16443 String::new(),
16444 vec![land::REPAIR.into()],
16445 );
16446 q.actions.insert(land::REPAIR.into(), resume_action(run));
16447 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
16448 q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
16450 q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
16451 questions.put(&mut q).unwrap();
16452 task.hold_manual(Some("Keep this PR paused".into()));
16453 if legacy {
16454 task.hold_source = None;
16455 }
16456 queue.put(&mut task).unwrap();
16457
16458 apply_task_choice_actions(&queue, &questions, dir.path());
16459 let after = queue.get(&task.id).unwrap();
16460 assert!(after.operator_held());
16461 assert_eq!(after.hold_source, task.hold_source);
16462 assert_eq!(after.operator_decided_at, task.operator_decided_at);
16463 assert_eq!(after.runs, task.runs);
16464 assert_eq!(after.instruction, task.instruction);
16465 assert!(after.resume_override.is_none());
16466 assert!(after.action_applied(&q.id));
16467 let reason = after.hold_reason.as_deref().unwrap();
16468 assert!(reason.starts_with("Keep this PR paused"));
16469 assert!(reason.contains("later operator decision"));
16470 assert!(reason.contains(&format!("magi task release {}", task.id)));
16471
16472 for recovery in [
16473 crate::conduct::Recovery::Review,
16474 crate::conduct::Recovery::Requeue,
16475 ] {
16476 crate::conduct::apply(
16477 &queue,
16478 &questions,
16479 &crate::conduct::Verdict {
16480 decisions: vec![crate::conduct::Decision {
16481 id: task.id.clone(),
16482 recovery: Some(recovery),
16483 ..Default::default()
16484 }],
16485 },
16486 )
16487 .unwrap();
16488 }
16489 apply_task_choice_actions(&queue, &questions, dir.path());
16492 let still_held = queue.get(&task.id).unwrap();
16493 assert!(still_held.operator_held());
16494 assert_eq!(still_held.hold_reason, after.hold_reason);
16495 assert_eq!(still_held.runs, task.runs);
16496 assert!(still_held.review_branch.is_none());
16497 assert!(!still_held.fresh_start);
16498 assert!(queue.next_runnable().is_none());
16499 }
16500 }
16501
16502 #[test]
16503 fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
16504 for held in [false, true] {
16505 for retry in [false, true] {
16506 let dir = tempfile::tempdir().unwrap();
16507 let queue = Queue::at(dir.path().join("queue"));
16508 let questions = Questions::at(dir.path().join("questions"));
16509 let home = dir.path().join("home");
16510 let mut t = task();
16511 if held {
16512 t.hold_machine(Some("driver state unknown".into()));
16513 }
16514 queue.put(&mut t).unwrap();
16515 let verdict = serde_json::from_value(serde_json::json!({
16516 "decisions": [{
16517 "id": t.id,
16518 "question": "Driver state unknown; retry the checks or hold?",
16519 "choices": ["daemon: recheck and retry", "daemon: hold the task"],
16520 "actions": {
16521 "daemon: recheck and retry": {"do": "requeue"},
16522 "daemon: hold the task": {"do": "hold"}
16523 }
16524 }]
16525 }))
16526 .unwrap();
16527 crate::conduct::apply(&queue, &questions, &verdict).unwrap();
16528 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
16529 let mut q = questions.list().pop().unwrap();
16530 let choice = if retry {
16531 "daemon: recheck and retry"
16532 } else {
16533 "daemon: hold the task"
16534 };
16535 assert_eq!(q.actions.len(), 2);
16536 q.answer(ask::Answer::Choice(choice.into())).unwrap();
16537 questions.put(&mut q).unwrap();
16538
16539 questions.beat(&q.id, ask::WaiterKind::Deputy);
16541 for _ in 0..2 {
16542 resolve_blockers(&queue, &questions);
16543 apply_task_choice_actions(&queue, &questions, &home);
16544 let waiting = queue.get(&t.id).unwrap();
16545 assert_eq!(waiting.status, TaskStatus::Blocked);
16546 assert_eq!(waiting.blocked_by, [q.id.clone()]);
16547 assert!(waiting.answers.is_empty());
16548 assert!(!waiting.action_applied(&q.id));
16549 assert!(runnable(&queue).is_empty());
16550 let free = Arc::new(tokio::sync::Semaphore::new(1));
16551 assert!(claim_dispatch(&queue, &t, false, &free, &free).is_err());
16552 }
16553 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
16554
16555 resolve_blockers(&queue, &questions);
16557 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
16558 apply_task_choice_actions(&queue, &questions, &home);
16559 let after = queue.get(&t.id).unwrap();
16560 assert_eq!(
16561 after.status,
16562 if retry {
16563 TaskStatus::Queued
16564 } else {
16565 TaskStatus::Held
16566 }
16567 );
16568 assert!(after.action_applied(&q.id));
16569 assert_eq!(after.operator_held(), !retry);
16570 assert_eq!(after.answers.len(), 1);
16571
16572 let mut changed = after;
16574 if retry {
16575 changed.hold_manual(Some("later hold".into()));
16576 } else {
16577 changed.release_operator("test", None);
16578 }
16579 let expected = changed.status;
16580 queue.put(&mut changed).unwrap();
16581 apply_task_choice_actions(&queue, &questions, &home);
16582 assert_eq!(queue.get(&t.id).unwrap().status, expected);
16583 }
16584 }
16585 }
16586
16587 #[test]
16588 fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
16589 let dir = tempfile::tempdir().unwrap();
16590 let queue = Queue::at(dir.path().join("queue"));
16591 let questions = Questions::at(dir.path().join("questions"));
16592 let home = dir.path().join("home");
16593 let mut state = run_state(RunStatus::Blocked);
16594 state.id = "20260101-000000-act1".to_owned();
16595 state.save_under(&home).unwrap();
16596
16597 let mut t = held_task_with(&state.id);
16598 queue.put(&mut t).unwrap();
16599 let mut q = action_question(&state.id, resume_action(&state.id));
16600 questions.put(&mut q).unwrap();
16601
16602 apply_task_choice_actions(&queue, &questions, &home);
16603 let after = queue.get(&t.id).unwrap();
16604 assert_eq!(after.status, TaskStatus::Queued);
16605 assert!(!after.fresh_start);
16606 assert!(after.action_applied(&q.id));
16607 let pin = after.resume_override.clone().unwrap();
16608 assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
16609 assert!(pin.forced);
16610
16611 let mut again = queue.get(&t.id).unwrap();
16613 again.hold_machine(Some("later".into()));
16614 queue.put(&mut again).unwrap();
16615 apply_task_choice_actions(&queue, &questions, &home);
16616 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
16617 }
16618
16619 #[test]
16620 fn done_choice_cannot_discard_unfinished_work_or_record_success_receipts() {
16621 let dir = tempfile::tempdir().unwrap();
16622 let home = dir.path();
16623 let queue = Queue::at(home.join("queue"));
16624 let questions = Questions::at(home.join("questions"));
16625 let mut state = run_state(RunStatus::Blocked);
16626 state.save_under(home).unwrap();
16627 let mut task = held_task_with(&state.id);
16628 queue.put(&mut task).unwrap();
16629 let mut question = action_question(&state.id, ask::ChoiceAction::Done);
16630 questions.put(&mut question).unwrap();
16631
16632 apply_task_choice_actions(&queue, &questions, home);
16633
16634 let after = queue.get(&task.id).unwrap();
16635 assert_eq!(after.status, TaskStatus::Held);
16636 assert!(after.hold_reason.as_deref().unwrap().contains("--discard"));
16637 assert_eq!(after.runs, task.runs);
16638 assert!(after.completion_history.is_empty());
16639 assert!(!after.decision_effects.contains_key(&question.id));
16640 assert_eq!(
16641 RunState::load_under(&state.id, home).unwrap().status,
16642 RunStatus::Blocked
16643 );
16644 }
16645
16646 #[test]
16647 fn a_delivered_answer_is_still_acted_on_exactly_once() {
16648 let dir = tempfile::tempdir().unwrap();
16649 let queue = Queue::at(dir.path().join("queue"));
16650 let questions = Questions::at(dir.path().join("questions"));
16651 let home = dir.path().join("home");
16652 let mut state = run_state(RunStatus::Blocked);
16653 state.id = "20260101-000000-act2".to_owned();
16654 state.save_under(&home).unwrap();
16655
16656 let mut t = held_task_with(&state.id);
16657 queue.put(&mut t).unwrap();
16658 let mut q = action_question(&state.id, resume_action(&state.id));
16659 q.answer_delivered = true;
16660 questions.put(&mut q).unwrap();
16661
16662 apply_task_choice_actions(&queue, &questions, &home);
16665 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
16666 assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
16667
16668 let mut again = queue.get(&t.id).unwrap();
16670 again.hold_machine(Some("later".into()));
16671 queue.put(&mut again).unwrap();
16672 apply_task_choice_actions(&queue, &questions, &home);
16673 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
16674 }
16675
16676 #[test]
16677 fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
16678 let dir = tempfile::tempdir().unwrap();
16679 let queue = Queue::at(dir.path().join("queue"));
16680 let questions = Questions::at(dir.path().join("questions"));
16681 let home = dir.path().join("home");
16682 let mut state = run_state(RunStatus::Blocked);
16683 state.id = "20260101-000000-act3".to_owned();
16684 state.save_under(&home).unwrap();
16685 let mut t = held_task_with(&state.id);
16686 queue.put(&mut t).unwrap();
16687 let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
16688 questions.put(&mut q).unwrap();
16689
16690 questions.beat(&q.id, crate::ask::WaiterKind::Asker);
16691 apply_task_choice_actions(&queue, &questions, &home);
16692 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
16693
16694 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
16695 apply_task_choice_actions(&queue, &questions, &home);
16696 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
16697 }
16698
16699 #[test]
16700 fn action_standing_tells_the_reasons_apart() {
16701 let mut t = held_task_with("r1");
16702 let q = action_question("r1", ask::ChoiceAction::Requeue);
16703 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
16704 let mut plain = q.clone();
16705 plain.actions.clear();
16706 assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
16707
16708 t.mark_action_applied(&q.id);
16710 assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
16711
16712 let mut t = held_task_with("r1");
16714 t.start("r2".to_owned());
16715 assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
16716 let q2 = action_question("r2", ask::ChoiceAction::Requeue);
16718 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
16719 t.status = TaskStatus::Blocked;
16720 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
16721
16722 let mut c = action_question("r0", ask::ChoiceAction::Requeue);
16724 c.node = crate::conduct::NODE.to_owned();
16725 assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
16726 assert!(!ActionStanding::Busy.daemon_owns());
16727 }
16728
16729 #[test]
16730 fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
16731 let dir = tempfile::tempdir().unwrap();
16732 let queue = Queue::at(dir.path().join("queue"));
16733 let questions = Questions::at(dir.path().join("questions"));
16734 let home = dir.path().join("home");
16735 let mut state = run_state(RunStatus::Ready);
16737 state.id = "20260101-000000-act4".to_owned();
16738 state.save_under(&home).unwrap();
16739 let mut t = held_task_with(&state.id);
16740 t.status = TaskStatus::Running;
16741 queue.put(&mut t).unwrap();
16742 let mut q = action_question(&state.id, ask::ChoiceAction::Done);
16743 q.cwd = Some(dir.path().display().to_string());
16744 questions.put(&mut q).unwrap();
16745
16746 let running = queue.get(&t.id).unwrap();
16749 assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
16750 assert!(matches!(
16751 crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
16752 crate::waiter::Action::Deliver(_)
16753 ));
16754 apply_task_choice_actions(&queue, &questions, &home);
16756 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
16757 let mut back = queue.get(&t.id).unwrap();
16758 back.hold_machine(Some("later".into()));
16759 queue.put(&mut back).unwrap();
16760 apply_task_choice_actions(&queue, &questions, &home);
16761 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
16762 let mut again = queue.get(&t.id).unwrap();
16763 again.hold_machine(Some("again".into()));
16764 queue.put(&mut again).unwrap();
16765 apply_task_choice_actions(&queue, &questions, &home);
16766 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
16767 }
16768
16769 #[test]
16770 fn stale_heartbeat_pointing_to_terminal_worker_does_not_block_resume_while_unproven_claims_stay_protected()
16771 {
16772 let dir = tempfile::tempdir().unwrap();
16773 let home = dir.path();
16774 let queue = Queue::at(home.join("queue"));
16775 let mut state = run_state(RunStatus::Blocked);
16776 state.id = "20261125-084544-669a".to_owned();
16777 state.driver_exited = true;
16778 state.driver_pid = None;
16779 state.driver_started_at = None;
16780 state.save_under(home).unwrap();
16781
16782 let mut t = held_task_with(&state.id);
16783 queue.put(&mut t).unwrap();
16784
16785 let worker_id = "fc769e65-0000-4000-8000-000000000001";
16788 let retained_dir = home.join("workers").join("results").join(worker_id);
16789 std::fs::create_dir_all(&retained_dir).unwrap();
16790 let finished_job = crate::worker::Job {
16791 id: worker_id.to_owned(),
16792 sequence: 1,
16793 kind: "task".to_owned(),
16794 key: format!("task:{}", t.id),
16795 payload: serde_json::json!({
16796 "queue": home.join("queue"),
16797 "task": t.id,
16798 "opts": Opts::default(),
16799 "standalone": false,
16800 }),
16801 generation: "a".repeat(64),
16802 version: Some("0.260.0".to_owned()),
16803 status: crate::worker::Status::Finished,
16804 result: Some("completed".to_owned()),
16805 pid: Some(37456),
16806 created_at: 1,
16807 finished_at: Some(2),
16808 };
16809 std::fs::write(
16810 retained_dir.join("job.json"),
16811 serde_json::to_vec(&finished_job).unwrap(),
16812 )
16813 .unwrap();
16814
16815 let now = Timestamp::now();
16816 let mut status = Status::new();
16817 status.updated_at = now;
16818 status.current = vec![Current {
16819 worker: Some(worker_id.to_owned()),
16820 task: t.id.clone(),
16821 run: state.id.clone(),
16822 }];
16823 write_status_to(&home.join("daemon.json"), &status).unwrap();
16824
16825 assert!(
16826 claim_for_run(home, &state.id, now).is_none(),
16827 "a fresh heartbeat pointing to a confirmed terminal worker must not claim the run"
16828 );
16829 assert!(crate::resume::validate(home, &state.id).is_ok());
16830
16831 status.current = vec![Current {
16833 worker: None,
16834 task: t.id.clone(),
16835 run: state.id.clone(),
16836 }];
16837 write_status_to(&home.join("daemon.json"), &status).unwrap();
16838 let legacy_err = crate::resume::validate(home, &state.id)
16839 .unwrap_err()
16840 .to_string();
16841 assert!(
16842 legacy_err.starts_with("run already has a live driver: daemon heartbeat claim"),
16843 "{legacy_err}"
16844 );
16845 assert!(legacy_err.contains("worker=none"), "{legacy_err}");
16846
16847 let missing_id = "fc769e65-0000-4000-8000-000000000002";
16849 status.current = vec![Current {
16850 worker: Some(missing_id.to_owned()),
16851 task: t.id.clone(),
16852 run: state.id.clone(),
16853 }];
16854 write_status_to(&home.join("daemon.json"), &status).unwrap();
16855 let missing_err = crate::resume::validate(home, &state.id)
16856 .unwrap_err()
16857 .to_string();
16858 assert!(
16859 missing_err.starts_with("run already has a live driver: daemon heartbeat claim"),
16860 "{missing_err}"
16861 );
16862 assert!(missing_err.contains(missing_id), "{missing_err}");
16863 assert!(missing_err.contains("status=unknown"), "{missing_err}");
16864
16865 let running_id = "fc769e65-0000-4000-8000-000000000003";
16868 let running_dir = home.join("workers").join("jobs").join(running_id);
16869 std::fs::create_dir_all(&running_dir).unwrap();
16870 let running_job = crate::worker::Job {
16871 id: running_id.to_owned(),
16872 status: crate::worker::Status::Running,
16873 pid: Some(42424),
16874 finished_at: None,
16875 result: None,
16876 ..finished_job
16877 };
16878 std::fs::write(
16879 running_dir.join("job.json"),
16880 serde_json::to_vec(&running_job).unwrap(),
16881 )
16882 .unwrap();
16883 std::fs::write(running_dir.join("live.lock"), b"").unwrap();
16884 status.current = vec![Current {
16885 worker: Some(running_id.to_owned()),
16886 task: t.id.clone(),
16887 run: state.id.clone(),
16888 }];
16889 write_status_to(&home.join("daemon.json"), &status).unwrap();
16890 let running_err = crate::resume::validate(home, &state.id)
16891 .unwrap_err()
16892 .to_string();
16893 assert!(
16894 running_err.starts_with("run already has a live driver: daemon heartbeat claim"),
16895 "{running_err}"
16896 );
16897 assert!(running_err.contains(running_id), "{running_err}");
16898 assert!(running_err.contains("pid=42424"), "{running_err}");
16899 assert!(running_err.contains("status=running"), "{running_err}");
16900 }
16901
16902 #[test]
16903 fn resume_validate_refusals_include_concrete_evidence_for_every_live_path() {
16904 let dir = tempfile::tempdir().unwrap();
16905 let home = dir.path();
16906 let queue = Queue::at(home.join("queue"));
16907 let mut state = run_state(RunStatus::Blocked);
16908 state.id = "20261125-090000-evid".to_owned();
16909 state.driver_exited = true;
16910 state.save_under(home).unwrap();
16911 let mut t = held_task_with(&state.id);
16912 queue.put(&mut t).unwrap();
16913
16914 let payload = serde_json::json!({
16916 "queue": home.join("queue"),
16917 "task": t.id,
16918 "opts": Opts::default(),
16919 "standalone": false,
16920 });
16921 let (job, lease) =
16922 crate::worker::running_fixture(home, &format!("task:{}", t.id), payload).unwrap();
16923 let worker_err = crate::resume::validate(home, &state.id)
16924 .unwrap_err()
16925 .to_string();
16926 assert!(
16927 worker_err.starts_with("run already has a live driver: worker claim"),
16928 "{worker_err}"
16929 );
16930 assert!(worker_err.contains(&job.id), "{worker_err}");
16931 assert!(
16932 worker_err.contains(&format!("pid={}", std::process::id())),
16933 "{worker_err}"
16934 );
16935 assert!(worker_err.contains("status=running"), "{worker_err}");
16936 assert!(worker_err.contains("live.lock held"), "{worker_err}");
16937 drop(lease);
16938 std::fs::remove_dir_all(home.join("workers").join("jobs").join(&job.id)).unwrap();
16939
16940 let starting_id = "fc769e65-0000-4000-8000-000000000010";
16942 let starting_dir = home.join("workers").join("jobs").join(starting_id);
16943 std::fs::create_dir_all(&starting_dir).unwrap();
16944 let starting_job = crate::worker::Job {
16945 id: starting_id.to_owned(),
16946 sequence: 2,
16947 kind: "task".to_owned(),
16948 key: format!("task:{}", t.id),
16949 payload: serde_json::json!({
16950 "queue": home.join("queue"),
16951 "task": t.id,
16952 "opts": Opts::default(),
16953 "standalone": false,
16954 }),
16955 generation: "a".repeat(64),
16956 version: None,
16957 status: crate::worker::Status::Starting,
16958 result: None,
16959 pid: None,
16960 created_at: 1,
16961 finished_at: None,
16962 };
16963 std::fs::write(
16964 starting_dir.join("job.json"),
16965 serde_json::to_vec(&starting_job).unwrap(),
16966 )
16967 .unwrap();
16968 let starting_err = crate::resume::validate(home, &state.id)
16969 .unwrap_err()
16970 .to_string();
16971 assert!(
16972 starting_err.starts_with("run already has a live driver: worker claim"),
16973 "{starting_err}"
16974 );
16975 assert!(starting_err.contains(starting_id), "{starting_err}");
16976 assert!(starting_err.contains("status=starting"), "{starting_err}");
16977 assert!(
16978 starting_err.contains("unfenced starting reservation"),
16979 "{starting_err}"
16980 );
16981 std::fs::remove_dir_all(&starting_dir).unwrap();
16982
16983 let corrupt_id = "bad00000-0000-4000-8000-000000000099";
16985 let corrupt_dir = home.join("workers").join("jobs").join(corrupt_id);
16986 std::fs::create_dir_all(&corrupt_dir).unwrap();
16987 std::fs::write(corrupt_dir.join("job.json"), b"{not valid json").unwrap();
16988 let store_err = crate::resume::validate(home, &state.id)
16989 .unwrap_err()
16990 .to_string();
16991 assert!(
16992 store_err.starts_with(
16993 "run already has a live driver: worker store observation failed (conservative protection):"
16994 ),
16995 "{store_err}"
16996 );
16997 assert!(store_err.contains(corrupt_id), "{store_err}");
16998 std::fs::remove_dir_all(&corrupt_dir).unwrap();
16999
17000 state.driver_exited = false;
17002 state.driver_claimed = Some(false);
17003 state.driver_pid = None;
17004 state.driver_started_at = None;
17005 state.save_under(home).unwrap();
17006 let exec_lease = crate::driver::maintenance(home, &state.id).unwrap();
17007 let lease_err = crate::resume::validate(home, &state.id)
17008 .unwrap_err()
17009 .to_string();
17010 let lock_path = home.join("runs").join(&state.id).join("driver.lock");
17011 assert!(
17012 lease_err.starts_with("run already has a live driver: execution lease held"),
17013 "{lease_err}"
17014 );
17015 assert!(
17016 lease_err.contains(&lock_path.display().to_string()),
17017 "{lease_err}"
17018 );
17019 drop(exec_lease);
17020
17021 let pid = std::process::id();
17023 let identity = crate::proc::process_started_at(pid).expect("current process identity");
17024 state.driver_claimed = None;
17025 state.driver_pid = Some(pid);
17026 state.driver_started_at = Some(identity.clone());
17027 state.save_under(home).unwrap();
17028 let pid_err = crate::resume::validate(home, &state.id)
17029 .unwrap_err()
17030 .to_string();
17031 assert!(
17032 pid_err.starts_with("run already has a live driver: live driver process"),
17033 "{pid_err}"
17034 );
17035 assert!(pid_err.contains(&format!("pid={pid}")), "{pid_err}");
17036 assert!(
17037 pid_err.contains(&format!("identity={identity}")),
17038 "{pid_err}"
17039 );
17040
17041 let question = action_question(&state.id, resume_action(&state.id));
17043 let decision = decide_action(home, &t, &question, &PHRASES_EN, |id| {
17044 RunState::load_under(id, home)
17045 });
17046 assert_eq!(decision, ActionDecision::Refuse(pid_err));
17047 }
17048}