magi/daemon.rs
1//! The unattended loop: take the next task, run the graph, record what
2//! happened, take the next one.
3//!
4//! This is what turns magi from a command a human types into something an
5//! agent can hand work to. [`crate::queue`] is the mailbox; this module is the
6//! thing that empties it. Nothing here decides *how* a task is implemented —
7//! that is [`crate::graph`] — it only decides which task runs next, and what a
8//! finished run means for the task that produced it.
9//!
10//! # One run at a time, on purpose
11//!
12//! There is no `--jobs` flag and there will not be one. A single run is
13//! already internally parallel: candidates implement concurrently and judges
14//! rank concurrently, so the machine is not idle while one task is in flight.
15//! The real constraint is not CPU but the agent CLIs' quota, and two graphs at
16//! once doubles the burn rate on exactly the resource whose exhaustion produces
17//! [`RunStatus::Stalled`]. Serialising the loop is what keeps a full backlog
18//! from converting the whole day's quota into a pile of untrustworthy verdicts.
19//!
20//! # A crash is legible, and the loop notices on its own
21//!
22//! The task is written as [`crate::queue::TaskStatus::Running`], with its run
23//! id, *before* the graph starts, and is only rewritten once the run reaches a
24//! terminal status. A daemon killed mid-run therefore leaves the task
25//! `Running` and pointing at the run that was in flight. The alternative —
26//! reverting the task to `Queued` on the way out — would hide the abandoned
27//! run and re-spend its quota on the next poll.
28//!
29//! A task left `Running` forever is not the point, though:
30//! [`crate::queue::TaskStatus::runnable`] never offers it again, so a daemon
31//! that died mid-run would otherwise strand its task for good.
32//! [`reclaim_orphaned_running`] runs on every poll and settles exactly the
33//! tasks no live process is actually driving — proven by [`Queue::claim`]
34//! succeeding rather than by a staleness guess — against whatever their last
35//! run actually became, through the same [`settle`] a live finish uses. A run
36//! that genuinely cannot be read still holds its task for a human; the run's
37//! own report explains how far it got.
38//!
39//! # Retries are bounded
40//!
41//! Every attempt at a task consumes one of [`Opts::max_attempts`], after which
42//! the task is [`crate::queue::TaskStatus::Held`] for a human. The one
43//! exception is a run that ended `Stalled`: the panel collapsed because the
44//! agent CLIs hit their quota, which is a fact about the machine and not about
45//! the task, so it must not spend an attempt. Without that exception a quota
46//! outage would quietly hold the entire backlog, and the operator would come
47//! back to a reset quota and nothing left that the loop is willing to run.
48
49use std::path::{Path, PathBuf};
50use std::sync::Arc;
51use std::sync::atomic::{AtomicBool, Ordering};
52use std::sync::{Mutex, MutexGuard};
53use std::time::Duration;
54
55use anyhow::{Context, Result, bail};
56use jiff::Timestamp;
57use serde::{Deserialize, Serialize};
58use tokio::sync::Notify;
59
60use crate::ask::{self, Questions};
61use crate::clean;
62use crate::conduct::Conductor;
63use crate::config::{Config, MergeMode};
64use crate::graph::Runner;
65use crate::land;
66use crate::notices::{self, Link, Notice};
67use crate::queue::{Queue, Task, TaskStatus};
68use crate::run::{Liveness, QuotaLoss, RunState, RunStatus};
69use crate::triage;
70
71/// On-disk format for [`Status`]. Bumped when a field's meaning changes.
72pub const SCHEMA: u32 = 1;
73
74/// How often the status file is refreshed. A reader treats a status file older
75/// than [`STALE_SECS`] as "no daemon", so the heartbeat has to be brisk enough
76/// that a busy daemon is never mistaken for a dead one.
77pub const HEARTBEAT: Duration = Duration::from_secs(5);
78
79/// How old a heartbeat may be before a reader calls the daemon dead. Six
80/// missed beats: long enough to survive a slow filesystem, short enough that
81/// a crashed daemon is not still reported as running a task.
82///
83/// The single threshold every reader shares — the web UI's `/api/health` and
84/// `magi doctor` both call [`Reading::running`] rather than each comparing
85/// against their own copy of this number, so a crashed daemon cannot look
86/// alive on one screen and dead on another.
87pub const STALE_SECS: i64 = 30;
88
89/// Default queue poll interval.
90pub const POLL: Duration = Duration::from_secs(5);
91
92/// How old a claim has to be before startup sweeps it. Longer than any run
93/// this graph plausibly takes, so a sweep cannot pull a task out from under a
94/// daemon that is merely slow.
95pub const STALE_CLAIM: Duration = Duration::from_secs(6 * 60 * 60);
96
97/// How long a task may sit [`TaskStatus::Running`] with no live daemon's
98/// heartbeat naming it before [`crate::conduct`] is shown it as stalled.
99///
100/// [`reclaim_orphaned_running`] settles most crashes immediately, on every
101/// poll, by attempting the task's own claim: a dead pid is proof enough for
102/// [`sweep_stale_claims`] to drop the lock the same tick, and the very next
103/// claim attempt succeeds. But a lock whose pid cannot be parsed at all — an
104/// empty or corrupt `.lock` file — falls back to [`STALE_CLAIM`]'s six-hour
105/// age instead, since there is nothing else to check (see
106/// [`sweep_stale_claims`]'s own doc). For as long as that lock survives, the
107/// claim keeps failing and `reclaim_orphaned_running` correctly leaves the
108/// task `running` — see
109/// `stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet` for
110/// exactly this ordering. `stalled_tasks` is what surfaces that task to the
111/// conductor well before the mechanical six-hour sweep would, and thirty
112/// minutes is comfortably below `STALE_CLAIM` while still being generous
113/// enough that a task merely late to publish its first [`HEARTBEAT`] is
114/// never mistaken for abandoned.
115pub const STALLED_RUNNING: Duration = Duration::from_secs(30 * 60);
116
117/// What the loop is working on, for the status file.
118#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
119#[serde(default)]
120pub struct Current {
121 /// Task id being run.
122 pub task: String,
123 /// Run id the task produced.
124 pub run: String,
125}
126
127/// The daemon's liveness, published to `<home>/daemon.json`.
128///
129/// This is the only interface between the loop and the web UI, which is why it
130/// carries `updated_at` as well as `started_at`: a reader cannot tell a
131/// running daemon from a `SIGKILL`ed one by the file's existence alone, but it
132/// can compare the heartbeat against the clock.
133#[derive(Debug, Clone, Serialize, Deserialize)]
134pub struct Status {
135 /// On-disk format version.
136 pub schema: u32,
137 /// Process id, so a human can find or kill the daemon.
138 pub pid: u32,
139 /// When this process started.
140 pub started_at: Timestamp,
141 /// Last heartbeat.
142 pub updated_at: Timestamp,
143 /// True when the queue has nothing runnable.
144 pub idle: bool,
145 /// Every task and run currently in flight. More than one entry means the
146 /// loop is driving more than one run at once — see
147 /// [`crate::config::Daemon::max_concurrent_runs`]. Empty, not absent, when
148 /// nothing is running, so a reader never has to treat "no field" and "an
149 /// empty list" as two different kinds of idle.
150 pub current: Vec<Current>,
151 /// Tasks that reached a terminal status in this process.
152 pub completed: usize,
153 /// Queue polls since start, so a wedged loop shows up as a frozen count.
154 pub polls: u64,
155}
156
157impl Status {
158 /// A fresh, idle status for this process.
159 #[must_use]
160 pub fn new() -> Self {
161 let now = Timestamp::now();
162 Self {
163 schema: SCHEMA,
164 pid: std::process::id(),
165 started_at: now,
166 updated_at: now,
167 idle: true,
168 current: Vec::new(),
169 completed: 0,
170 polls: 0,
171 }
172 }
173}
174
175impl Default for Status {
176 fn default() -> Self {
177 Self::new()
178 }
179}
180
181/// How the loop should behave.
182#[derive(Debug, Clone)]
183pub struct Opts {
184 /// Repository used by tasks that name none.
185 pub repo: PathBuf,
186 /// Explicit `magi.toml`, instead of the discovered layer stack.
187 pub config: Option<PathBuf>,
188 /// Queue poll interval.
189 pub poll: Duration,
190 /// Attempts a task gets before it is held for a human.
191 pub max_attempts: usize,
192 /// Drain what is runnable now, then return, instead of waiting for more.
193 pub once: bool,
194 /// Merge mode override (`none`, `local`, `pr`); `None` keeps the config's.
195 pub merge: Option<String>,
196 /// Where the janitor's [`crate::clean::fold_orphaned_worktrees`] and
197 /// [`crate::git::worktree_prune`] look for and reclaim worktrees.
198 /// `None` resolves to [`crate::run::default_worktree_root`] - the
199 /// operator's real `~/wt/<repo>` - the same way a run with no
200 /// [`crate::config::Graph::worktree_root`] resolves its own. A caller
201 /// that does not own that directory (a test, an embedding that manages
202 /// worktrees itself) must set this, or every idle tick reclaims worktrees
203 /// out from under whoever actually does.
204 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
221/// How many runs a plain `usize` from config may drive concurrently, floored
222/// at one. A `0` in a config file would otherwise stall the loop entirely -
223/// no runnable task could ever start - which is never what an operator who
224/// wrote `0` meant.
225fn max_concurrent(n: usize) -> usize {
226 n.max(1)
227}
228
229/// Where the status file lives.
230#[must_use]
231pub fn status_path() -> PathBuf {
232 crate::run::home().join("daemon.json")
233}
234
235/// Publish the status file for this process.
236pub fn write_status(status: &Status) -> Result<()> {
237 write_status_to(&status_path(), status)
238}
239
240/// Publish a status to an explicit path.
241///
242/// Written to a sibling `.tmp` and renamed, because the web UI reads this file
243/// on every health poll and must never see a half-written one.
244pub fn write_status_to(path: &Path, status: &Status) -> Result<()> {
245 if let Some(parent) = path.parent() {
246 std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
247 }
248 let body = serde_json::to_string_pretty(status).context("serialize daemon status")?;
249 let tmp = path.with_extension("json.tmp");
250 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
251 std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
252 Ok(())
253}
254
255/// Delete the status file. Called on the way out so a clean exit reads as
256/// "no daemon" rather than as a daemon whose heartbeat merely stopped.
257pub fn clear_status() {
258 clear_status_at(&status_path());
259}
260
261/// Delete a status file at an explicit path, so the loop's teardown and
262/// [`clear_status`] cannot drift apart: the loop is handed the path it
263/// published to, and a test can watch a temp file disappear.
264fn clear_status_at(path: &Path) {
265 let _ = std::fs::remove_file(path);
266}
267
268/// A cooperative stop, shared with whoever asked the loop to run.
269///
270/// Cloning is how the request travels: [`serve_until`] keeps one handle, the
271/// Ctrl-C listener and the web UI keep others, and every clone points at the
272/// same flag. There is no channel because there is nothing to send — the only
273/// message is "stop", it is idempotent, and a flag cannot be missed by a
274/// receiver that was not listening yet.
275///
276/// The handle also answers the question the operator's screen asks next: a
277/// stop does not take effect until the run in flight has finished, so
278/// [`Stop::finishing`] reports "asked to stop, still working" rather than
279/// leaving a caller to infer it from a heartbeat and hope.
280#[derive(Debug, Clone, Default)]
281pub struct Stop {
282 /// Set once, never cleared: a stop is not something an operator takes back
283 /// half way through, and a clearable flag would let a start racing a stop
284 /// resurrect a loop that is already unwinding.
285 stopped: Arc<AtomicBool>,
286 /// How many runs are in flight, so `finishing` can distinguish a stop
287 /// that has landed from one that is waiting on `execute`. A count, not a
288 /// flag, because more than one run can be in flight at once - see
289 /// [`crate::config::Daemon::max_concurrent_runs`] - and the last one to
290 /// finish is the one that should turn "finishing" off.
291 busy: Arc<std::sync::atomic::AtomicUsize>,
292 /// Wakes the idle wait. Without this a stop would not be seen until the
293 /// poll interval elapsed, and an operator tapping stop on a phone would
294 /// watch a button do nothing for five seconds.
295 wake: Arc<Notify>,
296 /// Handed to the run in flight, so a stop can also mean "park at the next
297 /// node boundary" instead of "finish the whole competition first".
298 pause: crate::graph::Pause,
299}
300
301impl Stop {
302 /// A stop nobody has asked for yet.
303 #[must_use]
304 pub fn new() -> Self {
305 Self::default()
306 }
307
308 /// Ask the loop to stop. Idempotent, and safe to call before the loop
309 /// starts: the flag is checked before the first poll.
310 pub fn stop(&self) {
311 self.stopped.store(true, Ordering::SeqCst);
312 // `notify_one` rather than `notify_waiters` because the loop may not be
313 // parked yet: this stores a permit, so a wait that registers a moment
314 // later returns at once instead of sleeping out the whole interval.
315 self.wake.notify_one();
316 }
317
318 /// Has a stop been asked for?
319 #[must_use]
320 pub fn stopped(&self) -> bool {
321 self.stopped.load(Ordering::SeqCst)
322 }
323
324 /// Has a stop been asked for that has not taken effect yet, because a run
325 /// is still in flight?
326 ///
327 /// This is the state a screen has to be able to show. A stop never abandons
328 /// a run — see [`serve_until`] — so between the tap and the loop's return
329 /// there is a window of tens of minutes in which "running" and "stopped"
330 /// are both misleading answers.
331 #[must_use]
332 pub fn finishing(&self) -> bool {
333 self.stopped() && self.busy_now()
334 }
335
336 /// Ask the loop to stop *and* the run in flight to park at its next node
337 /// boundary.
338 ///
339 /// The plain [`Stop::stop`] never abandons a run, which is right when the
340 /// operator only wants the queue to drain: a competition is tens of
341 /// minutes and its worktrees are paid for. But an operator who wants to
342 /// replace the binary cannot wait out a run that has an hour left, and
343 /// killing the process loses whatever the seats in flight had not written.
344 /// Parking costs at most the node in progress and leaves the run
345 /// resumable.
346 pub fn park(&self) {
347 self.pause.park();
348 self.stop();
349 }
350
351 /// Has a park been asked for?
352 #[must_use]
353 pub fn parking(&self) -> bool {
354 self.pause.parked()
355 }
356
357 /// The pause handle to give a runner.
358 #[must_use]
359 pub fn pause(&self) -> crate::graph::Pause {
360 self.pause.clone()
361 }
362
363 /// Is any run in flight right now?
364 ///
365 /// `finishing` answers "a stop is waiting on a run", which is false until
366 /// someone asks to stop. An upgrade needs the plain question, because it
367 /// is about to be the one asking.
368 #[must_use]
369 pub fn busy_now(&self) -> bool {
370 self.busy.load(Ordering::SeqCst) > 0
371 }
372
373 /// Mark one more run as in flight, for [`Stop::finishing`].
374 fn enter(&self) {
375 self.busy.fetch_add(1, Ordering::SeqCst);
376 }
377
378 /// Mark one run as finished. The last one out is what makes
379 /// [`Stop::busy_now`] false again.
380 fn exit(&self) {
381 self.busy.fetch_sub(1, Ordering::SeqCst);
382 }
383
384 /// Wait out one poll interval, returning early once a stop is asked for.
385 async fn idle(&self, poll: Duration) {
386 tokio::select! {
387 () = tokio::time::sleep(poll) => {}
388 () = self.wake.notified() => {}
389 }
390 }
391}
392
393/// The daemon's published state, read permissively.
394///
395/// This mirrors [`Status`], but is a separate declaration on purpose: every
396/// field defaults, so a status file from an older or newer magi still yields
397/// a usable reading — one this build has never heard of — instead of a parse
398/// error that hides the daemon entirely.
399#[derive(Debug, Clone, Default, Deserialize)]
400#[serde(default)]
401pub struct Reading {
402 /// Format version the daemon claims.
403 pub schema: u32,
404 /// Daemon process id, for an operator who wants to stop it.
405 pub pid: Option<u32>,
406 /// When that process started.
407 pub started_at: Option<Timestamp>,
408 /// Last heartbeat. Absent means the file is unusable, hence not running.
409 pub updated_at: Option<Timestamp>,
410 /// True when the queue had nothing runnable at the last poll.
411 pub idle: bool,
412 /// What the daemon is working on. Empty means idle; more than one entry
413 /// means more than one run is in flight at once.
414 ///
415 /// `deserialize_with` rather than the plain derive: a daemon started
416 /// before this field became a list is still out there writing the old
417 /// shape — a single `{"task":...,"run":...}` object, or its absence —
418 /// on every heartbeat until it is restarted, and a live process reading
419 /// that file during the rollout must still see it as running rather than
420 /// as absent. A bare type change here would fail the whole struct's
421 /// deserialization on a type mismatch, defeating the permissiveness this
422 /// type exists for.
423 #[serde(deserialize_with = "de_current")]
424 pub current: Vec<Current>,
425 /// Tasks this daemon process has finished.
426 pub completed: u64,
427 /// Queue polls this daemon process has made.
428 pub polls: u64,
429}
430
431/// Accept the old single-`Current`-or-absent shape as well as the current
432/// list, so a reader never has to know which build wrote the file.
433fn de_current<'de, D>(deserializer: D) -> std::result::Result<Vec<Current>, D::Error>
434where
435 D: serde::Deserializer<'de>,
436{
437 #[derive(Deserialize)]
438 #[serde(untagged)]
439 enum Shape {
440 Many(Vec<Current>),
441 One(Current),
442 }
443 Ok(
444 Option::<Shape>::deserialize(deserializer)?.map_or_else(Vec::new, |shape| match shape {
445 Shape::Many(v) => v,
446 Shape::One(c) => vec![c],
447 }),
448 )
449}
450
451impl Reading {
452 /// Seconds since the last heartbeat, or `None` when there has never been
453 /// one.
454 #[must_use]
455 pub fn age_secs(&self, now: Timestamp) -> Option<i64> {
456 self.updated_at
457 .map(|at| (now.as_second() - at.as_second()).max(0))
458 }
459
460 /// Whether the loop counts as running: a heartbeat no older than
461 /// [`STALE_SECS`]. The alternative is a reader that claims a task is in
462 /// progress hours after the daemon that owned it was killed.
463 #[must_use]
464 pub fn running(&self, now: Timestamp) -> bool {
465 self.age_secs(now).is_some_and(|secs| secs <= STALE_SECS)
466 }
467}
468
469/// Read `<home>/daemon.json` permissively, or `None` when there is nothing
470/// usable there.
471///
472/// Missing, half-written and unparseable all collapse to `None`, because the
473/// only question a reader asks is whether a daemon is alive, and a file it
474/// cannot read is not evidence that one is.
475#[must_use]
476pub fn read_status(home: &Path) -> Option<Reading> {
477 let body = std::fs::read_to_string(home.join("daemon.json")).ok()?;
478 serde_json::from_str(&body).ok()
479}
480
481/// Every run a live daemon is working on right now.
482///
483/// One definition of liveness, because deleting a task and deleting a run are
484/// both gated on it from both the CLI and the web UI - four callers that must
485/// never disagree about whether the same thing is in flight. A stale heartbeat
486/// reads as "no daemon": that is [`Reading::running`]'s judgement, and a task
487/// left at `running` or a run left at `implementing` by a killed daemon is a
488/// leftover record rather than work in progress. More than one entry once
489/// [`crate::config::Daemon::max_concurrent_runs`] is more than one - a caller
490/// after "the one thing in flight" wants [`is_working_on`] or
491/// [`is_working_on_task`], not this directly.
492#[must_use]
493pub fn current_work(home: &Path, now: Timestamp) -> Vec<Current> {
494 read_status(home)
495 .filter(|reading| reading.running(now))
496 .map(|reading| reading.current)
497 .unwrap_or_default()
498}
499
500/// Whether a live daemon is working on this run at this moment.
501#[must_use]
502pub fn is_working_on(home: &Path, run: &str, now: Timestamp) -> bool {
503 current_work(home, now).iter().any(|c| c.run == run)
504}
505
506/// Whether a live daemon is working on a run whose short id is this one.
507///
508/// For a worktree that has no run record to compare against at all -
509/// [`crate::clean::fold_orphaned_worktrees`]'s whole reason to exist - a full
510/// id is not available to hand to [`is_working_on`]. The short id is: a run's
511/// worktree bay is named after it (see [`crate::run::RunState::worktree_root`]),
512/// and it is exactly the gap between the daemon claiming a task and
513/// `RunState::new` saving the first `run.json` that this exists to protect -
514/// a run genuinely in flight but invisible to a scan of `runs/`.
515#[must_use]
516pub fn is_working_on_short(home: &Path, short: &str, now: Timestamp) -> bool {
517 current_work(home, now)
518 .iter()
519 .any(|c| crate::run::short_of(&c.run) == short)
520}
521
522/// Whether a live daemon is working on this task at this moment.
523#[must_use]
524pub fn is_working_on_task(home: &Path, task: &str, now: Timestamp) -> bool {
525 current_work(home, now).iter().any(|c| c.task == task)
526}
527
528/// Remove claim files whose owner is provably dead, or that have simply
529/// outlived `older_than`, and return the task ids swept.
530///
531/// A daemon killed with `SIGKILL` never runs [`crate::queue::Claim`]'s
532/// destructor, and the orphaned `.lock` file would make its task permanently
533/// unclaimable — the backlog would stop for good at exactly the task that was
534/// in flight when the machine went down.
535///
536/// The pid recorded in the lock is the authority whenever it can be read at
537/// all; age is only a fallback for when it cannot be.
538///
539/// - **A parseable pid wins outright.** [`crate::proc::pid_alive`] decides,
540/// full stop — dead sweeps the lock immediately, regardless of age; alive
541/// protects it, regardless of age. This is what lets a lock be reclaimed in
542/// seconds instead of waiting out [`STALE_CLAIM`]: a lock made 33 minutes
543/// before this daemon even started, next to a `queued` task, no longer has
544/// to sit for six hours before anything notices its owner is gone.
545/// - **A pid that cannot be parsed at all** — an empty or corrupt lock file —
546/// falls back to `older_than`, since there is nothing else to check.
547///
548/// Age must never override a *positive* liveness confirmation. `sweep`
549/// [`poll`]s concurrently with every attempt this daemon itself has spawned —
550/// see [`InFlightGuard`] — not only between them the way a single sequential
551/// loop once did, so a run that legitimately runs longer than `older_than`
552/// (a multi-round review, a long land wait carried across several resumed
553/// attempts) still has this very process's own live pid sitting in its own
554/// lock file on every later sweep. Deciding by age alone in that case would
555/// delete this daemon's own still-valid claim on its own in-flight task,
556/// which [`reclaim_orphaned_running`] would then read as abandoned and hand
557/// to a second attempt — two `Runner`s writing the same `run.json` and the
558/// same worktree at once. `pid_alive` answering "alive" for anything it
559/// cannot determine (a live process, a pid this build cannot check, one
560/// under another account) is exactly what keeps that path from ever
561/// firing on a guess.
562///
563/// [`STALE_CLAIM`] itself stays large: a helper program missing or its
564/// output unreadable must not be license to guess, and the risk of an
565/// unparseable lock outliving a genuinely dead owner is bounded by an order
566/// of magnitude above any plausible run rather than by a positive check.
567///
568/// Runs on every poll, not only at startup — a daemon up for days must keep
569/// noticing a lock some other, now-dead, daemon left behind just as readily
570/// as one it trips over on the way up.
571pub fn sweep_stale_claims(queue: &Queue, older_than: Duration) -> Vec<String> {
572 sweep_stale_claims_with(queue, older_than, crate::proc::pid_alive)
573}
574
575/// [`sweep_stale_claims`] with its process-query boundary supplied by the
576/// caller. This keeps the lock policy testable where process listing is
577/// unavailable, while production still uses the platform query above.
578fn sweep_stale_claims_with<F>(queue: &Queue, older_than: Duration, pid_alive: F) -> Vec<String>
579where
580 F: Fn(u32) -> bool,
581{
582 let this_process = std::process::id();
583 let mut swept: Vec<String> = std::fs::read_dir(queue.root())
584 .into_iter()
585 .flatten()
586 .flatten()
587 .map(|e| e.path())
588 .filter(|p| p.extension().is_some_and(|x| x == "lock"))
589 .filter(|p| {
590 match std::fs::read_to_string(p)
591 .ok()
592 .and_then(|body| body.trim().parse::<u32>().ok())
593 {
594 // This process wrote it and is asking the question right
595 // now, so it is definitionally still alive - settled without
596 // spawning a helper process at all.
597 Some(pid) if pid == this_process => false,
598 Some(pid) => !pid_alive(pid),
599 None => p
600 .metadata()
601 .and_then(|m| m.modified())
602 .and_then(|t| t.elapsed().map_err(std::io::Error::other))
603 .is_ok_and(|age| age >= older_than),
604 }
605 })
606 .filter(|p| std::fs::remove_file(p).is_ok())
607 .filter_map(|p| {
608 p.file_stem()
609 .and_then(|s| s.to_str())
610 .map(std::borrow::ToOwned::to_owned)
611 })
612 .collect();
613 swept.sort_unstable();
614 swept
615}
616
617/// Is `task` stalled: [`TaskStatus::Running`], past [`STALLED_RUNNING`], with
618/// no live daemon's heartbeat naming it? Deterministic — no model call, and
619/// the exact test [`stalled_tasks`] uses to decide what `crate::conduct` is
620/// shown.
621fn is_stalled(task: &Task, home: &Path, now: Timestamp) -> bool {
622 task.status == TaskStatus::Running
623 && (now.as_second() - task.updated_at.as_second()) >= STALLED_RUNNING.as_secs() as i64
624 && !is_working_on_task(home, &task.id, now)
625}
626
627/// Every task [`is_stalled`] right now — "止まったタスク" in
628/// `crate::conduct`'s vocabulary.
629fn stalled_tasks(queue: &Queue, home: &Path, now: Timestamp) -> Vec<Task> {
630 queue
631 .list()
632 .into_iter()
633 .filter(|t| is_stalled(t, home, now))
634 .collect()
635}
636
637/// Runnable tasks a dependency can still be set on — "runnable なタスク" in
638/// `crate::conduct`'s vocabulary. Deliberately `Queued` only, not
639/// `Failed`-and-so-also-runnable: a task that already attempted and lost
640/// belongs in [`finished_tasks`], where the question is a recovery, not a
641/// dependency.
642fn queued_tasks(queue: &Queue) -> Vec<Task> {
643 queue
644 .list()
645 .into_iter()
646 .filter(|t| t.status == TaskStatus::Queued)
647 .collect()
648}
649
650/// `Failed`/`Held` tasks nobody has decided a recovery for yet — "終わった
651/// タスク" in `crate::conduct`'s vocabulary.
652fn finished_tasks(queue: &Queue) -> Vec<Task> {
653 queue
654 .list()
655 .into_iter()
656 .filter(|t| matches!(t.status, TaskStatus::Failed | TaskStatus::Held))
657 .collect()
658}
659
660/// Deterministically resolve `Task::blocked_by`: a dependency task that
661/// reached `Done`, or a question that was answered, is removed — no model
662/// involved, on every poll. An answered question's content is copied onto
663/// the task ([`Task::record_answer`]) before its id is dropped, so it
664/// reaches the next `crate::conduct` prompt and the next run's instruction
665/// (see [`instruction_for`]) rather than only clearing the block.
666///
667/// A `blocked_by` id that names neither an existing task nor an existing
668/// question - `magi task rm` (or an operator by hand) deleted it while this
669/// task was still waiting - is caught before any of that: it can never
670/// become `Done` or `Answered`, so the ordinary loop below would otherwise
671/// leave the task `blocked` forever with nothing to notice. Such a task is
672/// quarantined to a machine hold instead ([`crate::queue::missing_blocker_hold_reason`]),
673/// which puts it in front of `crate::triage::run_once`'s own walk the next
674/// time it runs - see that module's doc for why the choice is "ask a human",
675/// never "assume the missing dependency was satisfied and unblock anyway".
676fn resolve_blockers(queue: &Queue, questions: &Questions) {
677 for listed in queue.list() {
678 if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
679 continue;
680 }
681 let Ok(_claim) = queue.claim(&listed.id) else {
682 continue;
683 };
684 let Ok(mut task) = queue.get(&listed.id) else {
685 continue;
686 };
687 if task.status != TaskStatus::Blocked {
688 continue;
689 }
690 let missing = crate::queue::missing_blockers(queue, questions, &task.blocked_by);
691 if !missing.is_empty() {
692 task.hold_machine(Some(crate::queue::missing_blocker_hold_reason(
693 &task.blocked_by,
694 &missing,
695 )));
696 record(queue, &mut task);
697 continue;
698 }
699 let mut changed = false;
700 for id in task.blocked_by.clone() {
701 if let Ok(dep) = queue.get(&id) {
702 if dep.status == TaskStatus::Done {
703 task.unblock(&id);
704 changed = true;
705 }
706 continue;
707 }
708 if let Ok(q) = questions.get(&id)
709 && q.status == ask::QuestionStatus::Answered
710 {
711 let answer = match &q.answer {
712 Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
713 None => String::new(),
714 };
715 task.record_answer(q.summary.clone(), answer);
716 task.unblock(&id);
717 changed = true;
718 }
719 }
720 if changed {
721 record(queue, &mut task);
722 }
723 }
724}
725
726/// Retire an unanswered conductor question after its task no longer refers to
727/// it. Conductor questions use the task id in `Question::run`, so run-based
728/// cleanup cannot observe a manual release or completion.
729///
730/// Restricted to `Question::node == crate::conduct::NODE`: an ordinary run's
731/// own question also carries a `run`, and a run id that happens to collide
732/// with some task's id is not this loop's business — only a conductor
733/// question actually uses the task id that way. One `Questions::list()` scan
734/// is taken up front and matched against the in-memory task set, rather than
735/// calling `Questions::open_for` (a full disk scan on its own) once per task.
736fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
737 let tasks = queue.list();
738 let by_id: std::collections::BTreeMap<&str, &Task> =
739 tasks.iter().map(|t| (t.id.as_str(), t)).collect();
740 let referenced: std::collections::BTreeSet<&str> = tasks
741 .iter()
742 .flat_map(|task| task.blocked_by.iter().map(String::as_str))
743 .collect();
744
745 for mut question in questions.list() {
746 if !question.status.open() || question.node != crate::conduct::NODE {
747 continue;
748 }
749 // Keep questions a task still names, including when the reference
750 // moved to a dependent task.
751 if referenced.contains(question.id.as_str()) {
752 continue;
753 }
754 let Some(task) = by_id.get(question.run.as_str()) else {
755 continue;
756 };
757 question.abandon(format!(
758 "task {} no longer waits for this answer",
759 task.short()
760 ));
761 if let Err(e) = questions.put(&mut question) {
762 tracing::warn!(
763 "could not retire question {} for task {}: {e:#}",
764 question.short(),
765 task.short()
766 );
767 }
768 }
769}
770
771/// What a finished run tells the queue about the task it came from.
772///
773/// A struct rather than a fourth and fifth boolean argument: the two flags
774/// answer different questions about the same run, and a call site passing
775/// `(…, true, false)` is one transposition away from refunding attempts
776/// forever.
777#[derive(Debug, Clone, Copy)]
778pub struct Verdict {
779 /// Where the graph stopped.
780 pub status: RunStatus,
781 /// The run opened a pull request.
782 pub left_pr: bool,
783 /// At least one seat was lost to a rate limit.
784 pub quota_hit: bool,
785 /// The run parked at a node boundary because it was asked to.
786 pub parked: bool,
787 /// The run never produced a single candidate a judge could look at.
788 ///
789 /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
790 /// still have another candidate worth judging, in which case the loss was
791 /// not the reason nothing came of the run. This is `true` only when the
792 /// implement wave ended with nothing viable at all.
793 pub no_viable_candidates: bool,
794}
795
796/// Record a finished run against the task it came from.
797///
798/// Kept pure and separate from the loop because this mapping *is* the retry
799/// policy, and a policy that can only be exercised by spawning a graph is a
800/// policy nobody checks. The table:
801///
802/// | run status | task becomes | attempt spent |
803/// |---------------------------------------|---------------------|---------------|
804/// | parked at a boundary | `Failed` (requeued) | **no** |
805/// | `Merged`, `Ready` | `Done` | yes |
806/// | `Stalled`, quota hit | `Failed` (requeued) | **no** |
807/// | `Failed`, quota hit, no viable cand. | `Failed` (requeued) | **no** |
808/// | `Stalled`, no quota | `Failed`, or `Held` | yes |
809/// | `Blocked` with a PR | `Held` | yes |
810/// | `Blocked`, `Failed` otherwise | `Failed`, or `Held` | yes |
811/// | `VerifiedNoop` | `Held` | yes |
812/// | anything non-terminal | `Failed`, or `Held` | yes |
813///
814/// The `VerifiedNoop` row is independent of the `Failed`-quota row above it,
815/// deliberately: every candidate agreeing there is nothing to write is not a
816/// machine fact about a rate limit, it is an unverified claim about the
817/// *task* that a human still has to check — see [`RunStatus::VerifiedNoop`]'s
818/// own doc and [`Task::handed_off`]. `Held` rather than `Done` on purpose: the
819/// claim could be wrong (a misread instruction, a stale check), and closing
820/// the task automatically on an implementer's say-so would be the exact
821/// failure mode task 391f's own audit was raised to avoid. `attempt spent` is
822/// `yes` here for the same reason it is on the `Blocked`-with-a-PR row just
823/// above, which settles through the same [`Task::handed_off`]: `Held` is not
824/// `Failed`-and-requeued, so nothing retries this task on the same unverified
825/// claim regardless of whether the one already-spent attempt is refunded, and
826/// [`Task::release`] resets the count to zero anyway the moment a human looks
827/// at the evidence and lets it run again.
828///
829/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
830/// twice, together. A quorum lost to rate limits is a property of the machine
831/// and not of the task, so the attempt is refunded and a reset quota picks
832/// the work up where it stopped — and that is just as true when every
833/// implement seat lost the same race and `after_implement` bails with nothing
834/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
835/// machine fact. The `no_viable_candidates` guard is what keeps that row
836/// narrow: a `Failed` run that produced a real candidate which then lost for
837/// some other reason still spends the attempt, exactly like the quorum lost
838/// to judges that answered with the wrong shape is ordinary flakiness, and
839/// refunding *that* takes the bound off the retry loop entirely: run e633
840/// stalled with `quota: []` after two judges wrote unusable JSON, was
841/// refunded, and the next attempt paid for a fresh hour-long implement wave
842/// before it could fail the same way. `max_attempts` exists precisely so
843/// that cannot repeat forever.
844///
845/// A non-terminal status means `execute` returned while the graph was still
846/// mid-flight, which is a bug rather than a verdict; it is treated as a
847/// failure so that a task cannot loop on it either.
848///
849/// `left_pr` splits the `Blocked` row, and it is the difference between a run
850/// that failed and a run that finished into a gate. See [`Task::handed_off`].
851pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
852 // A parked run is the operator's own doing, and its work is intact on
853 // disk. The task goes back in line with its attempt refunded so the next
854 // loop resumes the same run - which `one_task` prefers over competing
855 // again - and so that swapping the binary a few times cannot exhaust a
856 // budget meant for agents that actually misbehaved.
857 if verdict.parked {
858 task.stall(detail);
859 return;
860 }
861 match verdict.status {
862 RunStatus::Merged | RunStatus::Ready => task.succeed(),
863 RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
864 RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
865 task.stall(detail)
866 }
867 RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
868 RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
869 RunStatus::Blocked => task.fail(detail, max_attempts),
870 RunStatus::VerifiedNoop => task.handed_off(detail),
871 other => task.fail(
872 format!(
873 "the graph stopped at `{}` without reaching a terminal status: {detail}",
874 label(other)
875 ),
876 max_attempts,
877 ),
878 }
879}
880
881/// Rewrite this task's now-moot earlier attempts — [`Task::superseded_attempts`]
882/// — from `Blocked`/`Stalled` to [`RunStatus::Superseded`], once the task
883/// itself has actually finished *and* its own last attempt is provably why:
884/// this loads that run and requires `Merged`/`Ready` before touching
885/// anything earlier in `runs`, since `Task::succeed` can also be called
886/// directly on a task whose last attempt never landed at all.
887///
888/// Called right after whatever call set `task.status` to
889/// [`TaskStatus::Done`] — this module's own `settle`'s callers below and
890/// `reclaim`'s, but also every other place a task can be closed by hand
891/// without the loop ever settling it itself: `magi task done`
892/// (`main::TaskCmd::Done`) and `POST /api/queue/{id}/done`
893/// (`web::queue_done`). Closing a task by hand — after confirming a manual
894/// GitHub merge, say, exactly the workflow this repository's own
895/// "Landing a run's winner by hand" documents — is just as much "this task's
896/// story is over" as a daemon-driven `Merged`/`Ready` is, and skipping it
897/// there would leave every earlier attempt stuck at `Blocked`/`Stalled`
898/// forever, which is the exact backlog this status exists to clear. `pub`
899/// for those two out-of-module callers; everything else about this stays
900/// internal bookkeeping.
901///
902/// A run something is still actually driving is left alone: a
903/// task cannot be `Done` while one of its *own* attempts is still in flight,
904/// so a live one at this point can only be an unrelated process — a manual
905/// `--resume` of this old, now-moot run — and rewriting under it would just
906/// be undone (back to `Blocked`/`Stalled`, or worse) the next time that
907/// process itself saves. This is the same `daemon_claims` + [`RunState::liveness`]
908/// pair `run_report`/`run_detail` use for the same question elsewhere:
909/// `is_working_on` alone only ever proves a *daemon* claim, not a `magi run
910/// --resume` invoked by hand outside it, which `liveness` also checks via
911/// the run's own recorded `driver_pid`. Anything not `Blocked` or `Stalled`
912/// (already terminal in some other way, or itself mid-run) is left untouched
913/// too.
914///
915/// Best-effort, like the rest of this module's bookkeeping: a load or save
916/// failure here is a `tracing::warn`, not a failed settle, and the next time
917/// this same task's completion is recorded — or a daemon restart replays
918/// `reclaim_orphaned_running` — is another chance to catch up. There is no
919/// separate reconciliation pass; if that gap ever matters in practice, one
920/// can be added then.
921///
922/// `home` is a parameter, not the process-global [`crate::run::home`], for
923/// the same reason [`RunState::save_under`] takes one: `web::queue_done`
924/// calls this with `ui.home`, which is `crate::run::home()` in a real
925/// process but a fixture's own directory under test — falling through to
926/// the global there would read and write through whichever home some other
927/// test in the same binary happened to pin into that `OnceLock` first, not
928/// the run this call actually means.
929pub fn supersede_prior_runs(task: &Task, home: &Path) {
930 let now = Timestamp::now();
931 // `Task::superseded_attempts` cannot tell a loop-driven `Done` (always
932 // right behind a `Merged`/`Ready` verdict) from one set directly by
933 // `magi task done`/its web equivalent/the conductor on a task whose last
934 // recorded attempt never actually landed - that requires reading the
935 // run itself, which is exactly what this does before trusting anything
936 // in `runs` is safe to relabel.
937 let last_run_succeeded = task
938 .runs
939 .last()
940 .and_then(|id| RunState::load_under(id, home).ok())
941 .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
942 for id in task.superseded_attempts(last_run_succeeded) {
943 let mut state = match RunState::load_under(id, home) {
944 Ok(s) => s,
945 Err(e) => {
946 tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
947 continue;
948 }
949 };
950 if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
951 continue;
952 }
953 let daemon_claims = is_working_on(home, id, now);
954 if state.liveness(daemon_claims) == Liveness::Live {
955 continue;
956 }
957 state.status = RunStatus::Superseded;
958 if let Err(e) = state.save_under(home) {
959 tracing::warn!("could not mark run {id} superseded: {e:#}");
960 }
961 }
962}
963
964/// Catch up every `Done` task [`supersede_prior_runs`] could not fully
965/// finish the moment it was called, because one of its earlier attempts was
966/// still live then - a `magi run --resume` invoked by hand on an old run,
967/// most likely.
968///
969/// That skip is correct at the time (rewriting under a run something is
970/// still actively saving would just be undone), but a task only ever
971/// reaches `Done` once, so without this nothing would ever look at it
972/// again: if that manual process later ends anywhere other than
973/// `Merged`/`Ready` - abandoned, or landed as another `Blocked` - the
974/// skipped attempt would sit at `Blocked`/`Stalled` forever, exactly the
975/// backlog this status exists to clear. Called on the same idle-only
976/// cadence as [`janitor`], next to it rather than folded into it: this
977/// walks `queue` and `janitor` never otherwise needs one.
978///
979/// Simply re-running [`supersede_prior_runs`] over every `Done` task with
980/// more than one attempt, every pass: each call is a handful of local file
981/// reads bounded by that task's own attempt count, the same order of cost
982/// [`clean::fold_due`] already pays scanning every run on disk on the same
983/// cadence, and a task already fully resolved costs one failed liveness
984/// check turned no-op the moment its lingering attempt is no longer live.
985fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
986 for task in queue.list() {
987 if task.status != TaskStatus::Done || task.runs.len() < 2 {
988 continue;
989 }
990 supersede_prior_runs(&task, home);
991 }
992}
993
994/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
995/// task ends up held.
996///
997/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
998/// dead daemon never got back to) share this, so the two cannot drift into
999/// disagreeing about which held tasks get a diagnostic.
1000fn settle_and_diagnose(
1001 task: &mut Task,
1002 verdict: Verdict,
1003 detail: &str,
1004 max_attempts: usize,
1005 state: &RunState,
1006) {
1007 settle(task, verdict, detail, max_attempts);
1008 if task.status == TaskStatus::Held {
1009 task.diagnostic = diagnostic(state);
1010 }
1011}
1012
1013/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
1014/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
1015/// by some other means entirely, like a manual `magi run` resume that
1016/// finishes the graph outside the queue's bookkeeping.
1017///
1018/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
1019/// `settle` is separate from `attempt`: a task recovered this way must land
1020/// exactly where a live daemon would have put it — the same policy table,
1021/// not a second one that quietly drifts from it — and that is only checkable
1022/// without spawning a real run.
1023fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize) {
1024 match last_run {
1025 Some(state) => {
1026 let verdict = Verdict {
1027 status: state.status,
1028 left_pr: state.pr.is_some(),
1029 quota_hit: !state.quota.is_empty(),
1030 parked: state.parked,
1031 no_viable_candidates: state.viable().is_empty(),
1032 };
1033 let detail = format!(
1034 "recovered a `running` task whose daemon never recorded the outcome: {}",
1035 describe(&state)
1036 );
1037 settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
1038 }
1039 None => {
1040 let why = "task was `running` with no live daemon and no readable \
1041 run to recover; held for a human to check what happened";
1042 task.last_error = Some(why.to_owned());
1043 // The phone shows `hold_reason`, so a task held by the machine
1044 // says why there too and not only in `last_error`.
1045 task.hold_machine(Some(why.to_owned()));
1046 }
1047 }
1048}
1049
1050/// Find every task left at `running` that no live process is actually
1051/// driving, and settle each one against whatever its last run became.
1052///
1053/// # Why a claim is proof, not a guess
1054///
1055/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
1056/// `running`, and the guard is held for the task's whole time in that status:
1057/// `attempt` does not return, and the loop does not move past the scope
1058/// holding the claim, until the run has settled. So a `running` task whose
1059/// lock is gone cannot have a live owner — this process or any other —
1060/// without needing a staleness threshold or a pid check the way
1061/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
1062/// task that never got as far as `running` at all. Taking the claim here is
1063/// the whole test: it either fails, because something really does hold it
1064/// and the task is left alone, or it succeeds, which is the proof — and it is
1065/// kept for the rest of the decision so nothing else can start a competing
1066/// run while this one is being written.
1067///
1068/// Called on every poll, not only at startup, for the reason
1069/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
1070/// keep noticing this, not only on the one morning it happened to restart.
1071fn reclaim_orphaned_running(queue: &Queue, max_attempts: usize) -> Vec<String> {
1072 let mut reclaimed = Vec::new();
1073 for listed in queue.list() {
1074 if listed.status != TaskStatus::Running {
1075 continue;
1076 }
1077 let Ok(_claim) = queue.claim(&listed.id) else {
1078 continue;
1079 };
1080 // Re-read under the claim: a release or an edit landed by a human
1081 // between the listing above and the claim just taken must not be
1082 // clobbered by a decision based on the stale copy.
1083 let Ok(mut task) = queue.get(&listed.id) else {
1084 continue;
1085 };
1086 if task.status != TaskStatus::Running {
1087 continue;
1088 }
1089 let last_run = task.runs.last().and_then(|id| RunState::load(id).ok());
1090 // `execute` normally abandons a run's own open questions the moment
1091 // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
1092 // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
1093 // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
1094 // with the question still `open`, because the process died before
1095 // reaching that call. `reclaim` itself stays pure on purpose (see its
1096 // own doc), so the same cleanup runs here instead, against the run
1097 // this reclaim is already reading. `settle_run` costs nothing when
1098 // `execute` already got there first.
1099 if let Some(state) = &last_run
1100 && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
1101 {
1102 tracing::warn!("abandon questions for {}: {e:#}", state.id);
1103 }
1104 reclaim(&mut task, last_run, max_attempts);
1105 if task.status == TaskStatus::Done {
1106 supersede_prior_runs(&task, &crate::run::home());
1107 }
1108 record(queue, &mut task);
1109 reclaimed.push(task.id.clone());
1110 }
1111 reclaimed
1112}
1113
1114/// Find every run whose `run.json` is provably dead — every seat it still
1115/// lists as [`crate::run::RunState::active`] has overrun its own timeout, and
1116/// [`crate::run::RunState::liveness`] reads [`crate::run::Liveness::Dead`],
1117/// not merely "no daemon claims it" — and fail it, clearing the leftover
1118/// active seats so the run stops reading as `implementing` (or whichever
1119/// node) forever.
1120///
1121/// [`reclaim_orphaned_running`] settles the *task* a dead daemon left
1122/// `running`, using whatever `run.json` already says — but nothing in that
1123/// path, nor in [`reclaim`], ever writes back to the run itself (`reclaim`
1124/// stays pure on purpose, see its own doc), so a `run.json` a killed process
1125/// never got back to sits exactly where it was left: `active` full of seats
1126/// nobody will ever answer for, `status` stuck on whatever node was in
1127/// flight. `magi show` already tells an operator this in prose (`no live
1128/// daemon claims this run right now`); this is what makes that fact durable
1129/// on disk, the same way a task's own `TaskStatus::Running` does not get to
1130/// stay stuck once nothing is driving it.
1131///
1132/// Runs on every poll, not only at startup, for the reason
1133/// [`sweep_stale_claims`] and [`reclaim_orphaned_running`] already are: a
1134/// daemon up for days must keep noticing a run some other, now-dead, daemon
1135/// left behind just as readily as one it trips over on the way up.
1136///
1137/// Walks `home.join("runs")` directly and reads each `run.json` on its own,
1138/// rather than the process-global [`RunState::load`] / [`crate::run::list_ids`] —
1139/// the same reason [`crate::clean`]'s housekeeping passes take an explicit
1140/// `runs` directory instead: `home` here is a parameter precisely so a test
1141/// can point it away from the operator's real history (see [`drive`]'s own
1142/// doc), and a scan that fell through to the global home anyway would walk
1143/// whichever directory some *other* process or test pinned into that
1144/// `OnceLock` first — mutating runs this call was never handed.
1145fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
1146 reclaim_abandoned_runs_with(
1147 home,
1148 now,
1149 crate::proc::pid_status,
1150 crate::proc::process_started_at,
1151 )
1152}
1153
1154/// [`reclaim_abandoned_runs`] with its `driver_pid` liveness/identity queries
1155/// supplied by the caller — mirrors [`sweep_stale_claims_with`], which exists
1156/// for the identical reason: this sweep's real damage (wiping a run's active
1157/// seats and failing it) has to be provable against an injected answer in a
1158/// test, not just the real process table.
1159fn reclaim_abandoned_runs_with<F, G>(
1160 home: &Path,
1161 now: Timestamp,
1162 query: F,
1163 identity: G,
1164) -> Vec<String>
1165where
1166 F: Fn(u32) -> Option<bool>,
1167 G: Fn(u32) -> Option<String>,
1168{
1169 let mut abandoned = Vec::new();
1170 for entry in std::fs::read_dir(home.join("runs"))
1171 .into_iter()
1172 .flatten()
1173 .flatten()
1174 {
1175 let id = entry.file_name().to_string_lossy().into_owned();
1176 if !crate::run::is_run_id(&id) {
1177 continue;
1178 }
1179 // Unreadable is `clean::fold_due`'s problem, not this one's — see
1180 // that module's docs for why a run this cannot parse is left alone
1181 // rather than guessed at. A different schema number is not that: this
1182 // touches only `status` and `active`, never a field whose meaning a
1183 // schema bump changed, so an old record's values serve this exactly
1184 // as well as a current one's (see `clean::read_state`'s own doc for
1185 // the same reasoning applied to folding).
1186 let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
1187 continue;
1188 };
1189 let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
1190 continue;
1191 };
1192 if state.status.done() || !state.active_all_overrun(now) {
1193 continue;
1194 }
1195 // Not `!is_working_on(..)` alone: that is only "no *daemon* claims
1196 // it", which is also the normal, healthy shape of a manual `magi
1197 // run` / `magi review` sharing this same home — this scan walks
1198 // every run on disk, not only ones this daemon itself started. Such
1199 // a run's active seats can legitimately sit past their own timeout
1200 // for a little while (the CLI finishing up, its result still being
1201 // collected) without the process driving it having died. `liveness`
1202 // is what actually tells the two apart, by corroborating
1203 // `driver_pid` against the process it names — see its own doc. Only
1204 // its strongest, provable answer licenses wiping this run's active
1205 // seats and failing it out from under whatever is still running it.
1206 let daemon_claims = is_working_on(home, &id, now);
1207 if state.liveness_with(daemon_claims, &query, &identity) != crate::run::Liveness::Dead {
1208 continue;
1209 }
1210 state.abandon("daemon");
1211 if let Err(e) = state.save_under(home) {
1212 tracing::warn!("could not persist abandoned run {id}: {e:#}");
1213 continue;
1214 }
1215 // This run never passes through `Runner::execute` again, so its end
1216 // is announced here.
1217 if let Some(notice) = notices::run_ended(&state) {
1218 notices::raise_in(home, notice);
1219 }
1220 // The seat that asked is gone for good now, exactly like any other
1221 // door `graph::Runner::settle_questions` closes the moment `status`
1222 // lands somewhere non-resumable - see that method's own doc. Nothing
1223 // else reaches this one before the next `janitor()` startup pass
1224 // (`clean::abandon_settled_questions`), and a daemon that stays up
1225 // for days must not leave an open question badging the operator
1226 // until it happens to restart.
1227 if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
1228 tracing::warn!("abandon questions for {id}: {e:#}");
1229 }
1230 abandoned.push(id);
1231 }
1232 abandoned
1233}
1234
1235/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
1236///
1237/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
1238/// sets, so there is one loop body rather than two that drift apart the first
1239/// time the retry policy changes on only one of them.
1240pub async fn serve(opts: Opts) -> Result<()> {
1241 serve_until(opts, Stop::new()).await
1242}
1243
1244/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
1245///
1246/// Neither a signal nor a `stop` abandons a run in flight. Killing the graph
1247/// mid-node leaves worktrees, branches and agent sessions behind, and every
1248/// agent call already paid for is lost; finishing the run costs the operator a
1249/// wait and saves them a cleanup. A stop therefore only sets a flag: the
1250/// current `execute` runs to its terminal status, the task's outcome is
1251/// recorded, and only then does the loop return. That window is what
1252/// [`Stop::finishing`] is for. An operator who genuinely wants the run dead
1253/// still has a second Ctrl-C, which the runtime turns into a process kill —
1254/// and the task left `Running` then tells the next daemon, and the next human,
1255/// where to look.
1256///
1257/// While the queue is empty the stop is honoured within one wakeup rather than
1258/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
1259/// caller that taps stop does not sit through the remainder of a sleep.
1260pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
1261 let signal = {
1262 let stop = stop.clone();
1263 tokio::spawn(async move {
1264 if tokio::signal::ctrl_c().await.is_ok() {
1265 stop.stop();
1266 tracing::info!("shutdown requested; a run in flight will be finished first");
1267 }
1268 })
1269 };
1270
1271 let worktrees_root = opts
1272 .worktrees_root
1273 .clone()
1274 .unwrap_or_else(crate::run::default_worktree_root);
1275 let outcome = drive(
1276 &opts,
1277 &Queue::open(),
1278 &status_path(),
1279 &crate::run::home(),
1280 &worktrees_root,
1281 &stop,
1282 )
1283 .await;
1284
1285 signal.abort();
1286 outcome
1287}
1288
1289/// The loop proper: setup, poll, teardown, with the queue and the status file
1290/// supplied rather than discovered.
1291///
1292/// All three of `home`, `worktrees_root` and the queue/status paths are
1293/// parameters rather than resolved here, for the same reason:
1294/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
1295/// so a unit test that pinned it would fight every other test in the binary,
1296/// and a loop that resolved its own worktree bay could only be exercised
1297/// against the operator's real `~/wt/<repo>` - publishing over a live
1298/// daemon's status file, claiming tasks out of a live backlog, and, since
1299/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
1300/// whatever the operator actually has on disk.
1301async fn drive(
1302 opts: &Opts,
1303 queue: &Queue,
1304 status_file: &Path,
1305 home: &Path,
1306 worktrees_root: &Path,
1307 stop: &Stop,
1308) -> Result<()> {
1309 // The status file is a *snapshot*, not a stream of events: a reader only
1310 // ever wants the latest values, and every tick rewrites the whole file
1311 // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
1312 // while an mpsc channel would force the loop to re-send unchanged fields on
1313 // every heartbeat — or the heartbeat to keep its own shadow copy of them —
1314 // for no gain. The lock is only ever held across a field assignment, never
1315 // across an await.
1316 let status = Arc::new(Mutex::new(Status::new()));
1317 write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
1318 let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
1319
1320 // Read once at startup, not per task: how many runs this loop drives at
1321 // once is a property of the machine running it, not of whichever
1322 // repository a given task happens to name - see
1323 // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
1324 // fact in the same sense the agent roster is.
1325 let daemon_cfg = prepare(&opts.repo, opts)
1326 .map(|c| c.daemon)
1327 .unwrap_or_default();
1328 let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
1329
1330 tracing::info!(
1331 "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
1332 queue.root().display(),
1333 opts.poll.as_secs(),
1334 opts.max_attempts,
1335 concurrency,
1336 if daemon_cfg.pause_for_interrupts {
1337 ", interrupts enabled"
1338 } else {
1339 ""
1340 }
1341 );
1342
1343 // `--once` drains an already-idle queue without reaching the idle wait,
1344 // but must still perform the startup cleanup.
1345 janitor(&opts.repo, opts, home, worktrees_root).await;
1346 resweep_superseded_attempts(queue, home);
1347
1348 let outcome = poll(
1349 opts,
1350 queue,
1351 &status,
1352 home,
1353 worktrees_root,
1354 stop,
1355 DispatchLimits {
1356 max_concurrent: concurrency,
1357 pause_for_interrupts: daemon_cfg.pause_for_interrupts,
1358 },
1359 )
1360 .await;
1361
1362 beat.abort();
1363 clear_status_at(status_file);
1364 outcome
1365}
1366
1367/// Refresh the status file on a fixed tick.
1368///
1369/// Separate from the loop because a run takes tens of minutes: a status file
1370/// written only between tasks would look stale for the whole of every run, and
1371/// a reader would report the daemon dead exactly while it was busiest.
1372async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
1373 loop {
1374 tokio::time::sleep(HEARTBEAT).await;
1375 let snapshot = {
1376 let mut guard = lock(&status);
1377 guard.updated_at = Timestamp::now();
1378 guard.clone()
1379 };
1380 if let Err(e) = write_status_to(&path, &snapshot) {
1381 // A failed heartbeat must not take the daemon down: the loop is the
1382 // product, the status file is only the window onto it.
1383 tracing::warn!("could not refresh the daemon status file: {e:#}");
1384 }
1385 }
1386}
1387
1388/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
1389/// if so, whether that wait is over.
1390#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1391enum LandResume {
1392 /// The task's last run is not parked on a land approval; schedule it
1393 /// like any other candidate.
1394 NotLanding,
1395 /// Parked in `land`, waiting on a question nobody has answered yet.
1396 /// Left alone: attempting it now would only re-observe the same pull
1397 /// request and park again, spending a `gh` call on a decision that has
1398 /// not changed since the last time this was checked.
1399 StillWaiting,
1400 /// Parked in `land`, and the question is settled - answered or
1401 /// abandoned. Resuming this is the one kind of candidate that must not
1402 /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
1403 Ready,
1404}
1405
1406/// Classify a runnable candidate by whether it is parked on a land-merge
1407/// approval. Read-only - no claim taken, nothing written - so it is cheap
1408/// enough to call on every candidate, every poll.
1409fn land_resume_state(task: &Task) -> LandResume {
1410 let Some(run_id) = task.runs.last() else {
1411 return LandResume::NotLanding;
1412 };
1413 let Ok(state) = RunState::load(run_id) else {
1414 return LandResume::NotLanding;
1415 };
1416 if state.status != RunStatus::Landing || !state.parked {
1417 return LandResume::NotLanding;
1418 }
1419 let store = ask::Questions::open();
1420 let waiting = store
1421 .list()
1422 .into_iter()
1423 .filter(|q| &q.run == run_id && q.node == land::APPROVAL_NODE)
1424 .max_by(|a, b| a.id.cmp(&b.id));
1425 let Some(mut q) = waiting else {
1426 return LandResume::Ready;
1427 };
1428 if !q.status.open() {
1429 return LandResume::Ready;
1430 }
1431 // `ask::ask_and_wait`'s own deadline is what used to retire a question
1432 // nobody ever answered; land's approval bypasses that wait entirely (see
1433 // `land::approval_gate`), so the same deadline has to be enforced here
1434 // instead, or `graph.answer_timeout` silently stops meaning anything for
1435 // a land approval and a run can sit `StillWaiting` forever with nobody
1436 // told to look at it.
1437 let timeout = Duration::from_secs(state.config.graph.answer_timeout);
1438 let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
1439 if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
1440 q.abandon(format!(
1441 "no answer within {}s of asking",
1442 timeout.as_secs().max(1)
1443 ));
1444 // If this can't be persisted, do not treat the wait as settled on a
1445 // guess: fall through and try again next poll.
1446 if store.put(&mut q).is_ok() {
1447 return LandResume::Ready;
1448 }
1449 }
1450 LandResume::StillWaiting
1451}
1452
1453/// How often the loop rechecks for new work while something it already
1454/// started is still running, rather than sleeping out the whole
1455/// [`Opts::poll`] interval.
1456///
1457/// Short on purpose: this is what lets a land-merge approval that comes back
1458/// while another task is mid-competition be noticed and resumed within a
1459/// fraction of a second, not within the next multi-second poll.
1460const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
1461
1462/// How often [`poll`] rechecks the shared build cache against its cap at a
1463/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
1464/// waiting for the queue to run dry.
1465///
1466/// A queue that never empties means the `janitor` call at the bottom of this
1467/// loop's fully-idle branch can go unreached for as long as the backlog
1468/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
1469/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
1470/// 81.8 GiB an idle-only check let it reach before this existed, and it is
1471/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
1472/// backlog of short tasks does not pay for that walk on every poll.
1473const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
1474
1475/// Frees one attempt's concurrency slot - `Stop`'s busy count and its entry
1476/// in `Status::current` - on drop, so both are released even if the attempt
1477/// panics rather than returning.
1478///
1479/// A `Drop` impl rather than statements written after the `.await` it
1480/// guards: a panic unwinds straight past code placed "after" a call, and
1481/// `Runner::execute`'s chain reaches deep enough into agent-output parsing
1482/// that ruling a panic out there is not a bet this loop can make. Without
1483/// this, one panicking run would leave [`Stop::busy_now`] stuck `true`
1484/// forever - the idle branch in [`poll`], and with it the janitor, would
1485/// never run again - and a ghost entry in `Status::current` naming a task
1486/// nothing is still working on.
1487struct InFlightGuard<'a> {
1488 status: &'a Arc<Mutex<Status>>,
1489 stop: &'a Stop,
1490 task_id: &'a str,
1491}
1492
1493impl Drop for InFlightGuard<'_> {
1494 fn drop(&mut self) {
1495 lock(self.status).current.retain(|c| c.task != self.task_id);
1496 self.stop.exit();
1497 }
1498}
1499
1500/// State of [`poll`]'s own interrupt-scheduling sequence - see
1501/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
1502/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
1503/// both kept free of `Task`'s non-identity fields on purpose: every decision
1504/// here turns only on task ids and which ones are in flight, so the "never
1505/// more than one run at once" and "exactly one resume" invariants can be
1506/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
1507/// queue - which is exactly the coverage this feature's first two attempts
1508/// were missing.
1509///
1510/// Deliberately in-memory only, not written to disk anywhere: a daemon
1511/// restart mid-sequence loses track of which run it had asked to park and
1512/// which task was meant to run first, and simply falls back to `Idle` -
1513/// see [`drive`]'s own setup. The parked run itself is not lost - it is
1514/// sitting in the queue exactly like any other resumable, interrupted task,
1515/// `RunStatus::resumable` and [`Task::interrupt`] both intact on disk - it
1516/// just resumes on the ordinary priority order rather than guaranteed to go
1517/// first. Giving that guarantee a crash-proof memory would mean a new queue
1518/// field and a recovery ordering to go with it, which is exactly the
1519/// complexity this feature's constraints rule out for the one property that
1520/// actually matters: at most one run, ever, at once.
1521#[derive(Debug, Clone, PartialEq, Eq)]
1522enum Interrupt {
1523 /// No interrupt sequence in progress. Ordinary dispatch applies.
1524 Idle,
1525 /// `interrupt_task` is runnable and exactly one other run is in flight;
1526 /// `parked` names that one task's id. Dispatch is withheld from
1527 /// everyone, including `interrupt_task` itself, until it has left
1528 /// flight - only then is `interrupt_task` let through.
1529 ///
1530 /// `parked` is a `Vec` rather than a bare id for symmetry with
1531 /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
1532 /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
1533 /// when exactly one run is in flight, so it is guaranteed to hold
1534 /// exactly one entry in practice - see that branch's own doc for why
1535 /// more than one is deliberately never attempted.
1536 Parking {
1537 parked: Vec<String>,
1538 interrupt_task: String,
1539 },
1540 /// `interrupt_task` is dispatched and in flight alone. Dispatch is
1541 /// withheld from everyone until it leaves flight - merged, failed, held,
1542 /// it makes no difference - at which point the sequence moves to
1543 /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
1544 /// going straight to `Idle` would hand `parked` back to ordinary
1545 /// priority-order dispatch, where a higher-priority task filed in the
1546 /// meantime could start ahead of it.
1547 Running {
1548 parked: Vec<String>,
1549 interrupt_task: String,
1550 },
1551 /// `interrupt_task` left flight; `parked` still names the one run this
1552 /// sequence owes a resume. Dispatch is withheld from everyone except
1553 /// that task - see [`interrupt_gate`] - so the resume this feature
1554 /// promises is never raced by, or run alongside, an unrelated candidate.
1555 /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
1556 /// own doc on abandonment - the moment it is no longer runnable at all.
1557 Resuming { parked: Vec<String> },
1558}
1559
1560/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
1561/// and `runnable` are read-only snapshots of this tick's reality, and the
1562/// only side effect the caller still owes the world is asking whichever
1563/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
1564/// site.
1565///
1566/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
1567/// accepted rather than a narrower type because that is what [`poll`] already
1568/// has on hand from [`runnable`], and building a second, smaller list on
1569/// every tick just to satisfy this signature would cost more than it proves.
1570///
1571/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
1572/// back to a task they are waiting on no longer being [`runnable`] - held,
1573/// blocked, deleted, or finished by some other means entirely, all of which
1574/// an operator can do to a task sitting in the queue with no claim on it at
1575/// all, at any moment, interrupt sequence or not. Without this check the
1576/// sequence would wait forever for a dispatch that can never come, and
1577/// `interrupt_gate` would withhold every other task in the queue right along
1578/// with it - a single `magi task hold` on the wrong id turning into a
1579/// daemon that never dispatches anything again.
1580fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
1581 match state {
1582 Interrupt::Idle => {
1583 // Not just "something to interrupt": exactly one thing. More
1584 // than one run in flight only happens above the default
1585 // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
1586 // one resume, never run alongside anything else" only because
1587 // it is only ever seeded with exactly one id - see
1588 // `Interrupt::Resuming`'s own doc on why releasing more than one
1589 // parked id back to ordinary dispatch cannot be made safe
1590 // against that same setting's own extra concurrency slots.
1591 // Waiting here for the herd to settle to one is the
1592 // simplification this feature's own constraints ask for rather
1593 // than a second concurrency model to reconcile with the first.
1594 if in_flight.len() != 1 {
1595 return Interrupt::Idle;
1596 }
1597 match runnable.iter().find(|t| t.interrupt) {
1598 Some(t) => Interrupt::Parking {
1599 parked: in_flight.to_vec(),
1600 interrupt_task: t.id.clone(),
1601 },
1602 None => Interrupt::Idle,
1603 }
1604 }
1605 Interrupt::Parking {
1606 parked,
1607 interrupt_task,
1608 } => {
1609 if in_flight.iter().any(|id| parked.contains(id)) {
1610 // Still waiting for what was in flight to actually stop.
1611 Interrupt::Parking {
1612 parked,
1613 interrupt_task,
1614 }
1615 } else if in_flight.contains(&interrupt_task) {
1616 Interrupt::Running {
1617 parked,
1618 interrupt_task,
1619 }
1620 } else if runnable.iter().any(|t| t.id == interrupt_task) {
1621 // The parked run(s) are gone, but the interrupt task has not
1622 // been dispatched yet on this tick - `interrupt_gate` is
1623 // what lets it through next.
1624 Interrupt::Parking {
1625 parked,
1626 interrupt_task,
1627 }
1628 } else {
1629 // The interrupt task itself is no longer runnable - see this
1630 // function's own doc on abandonment. The parked run(s) still
1631 // get their guaranteed resume; there is simply no interrupt
1632 // to run ahead of them any longer.
1633 Interrupt::Resuming { parked }
1634 }
1635 }
1636 Interrupt::Running {
1637 parked,
1638 interrupt_task,
1639 } => {
1640 if in_flight.contains(&interrupt_task) {
1641 Interrupt::Running {
1642 parked,
1643 interrupt_task,
1644 }
1645 } else {
1646 // The interrupt task's own run reached a terminal status,
1647 // whichever one - this is the *only* trigger that moves the
1648 // sequence on, driven straight off the same in-flight
1649 // bookkeeping `poll` already reaps every tick, not a second,
1650 // independent poll of anything.
1651 Interrupt::Resuming { parked }
1652 }
1653 }
1654 Interrupt::Resuming { parked } => {
1655 if in_flight.iter().any(|id| parked.contains(id)) {
1656 // One of the parked runs has been dispatched - the resume
1657 // this sequence owed is fulfilled. Whatever else is left in
1658 // `parked` (ordinarily nothing, at the default concurrency
1659 // of one) rejoins ordinary priority-order dispatch, same as
1660 // any other runnable task.
1661 Interrupt::Idle
1662 } else if runnable.iter().any(|t| parked.contains(&t.id)) {
1663 Interrupt::Resuming { parked }
1664 } else {
1665 // Abandonment (see this function's own doc): nothing left in
1666 // `parked` is even runnable any longer.
1667 Interrupt::Idle
1668 }
1669 }
1670 }
1671}
1672
1673/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
1674/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
1675/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
1676/// indistinguishable from any other runnable task - exactly the "off does
1677/// nothing" this feature promises.
1678fn advance_interrupt_tick(
1679 enabled: bool,
1680 state: Interrupt,
1681 in_flight: &[String],
1682 runnable: &[Task],
1683) -> Interrupt {
1684 if !enabled {
1685 return Interrupt::Idle;
1686 }
1687 advance_interrupt(state, in_flight, runnable)
1688}
1689
1690/// Which of this tick's runnable candidates the interrupt sequence actually
1691/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
1692/// each half is assertable on its own: this is the half that keeps a
1693/// competition and an interrupt from ever running at the same moment.
1694fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
1695 match state {
1696 Interrupt::Idle => candidates,
1697 Interrupt::Parking {
1698 parked,
1699 interrupt_task,
1700 } => {
1701 if in_flight.iter().any(|id| parked.contains(id)) {
1702 Vec::new()
1703 } else {
1704 candidates
1705 .into_iter()
1706 .filter(|t| &t.id == interrupt_task)
1707 .collect()
1708 }
1709 }
1710 Interrupt::Running { .. } => Vec::new(),
1711 // At most one: even if `parked` names more than one id (more than
1712 // one run was in flight when the sequence began, only possible
1713 // above the default `max_concurrent_runs = 1`), only the first match
1714 // is offered. Capping this to a single candidate - not merely to
1715 // `parked`'s own ids - is what makes "exactly one resume, never two
1716 // dispatched together" true regardless of how many ordinary slots
1717 // happen to be free this tick.
1718 Interrupt::Resuming { parked } => candidates
1719 .into_iter()
1720 .find(|t| parked.contains(&t.id))
1721 .into_iter()
1722 .collect(),
1723 }
1724}
1725
1726/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
1727/// bundled into one parameter so `poll`'s own signature stays readable -
1728/// see [`drive`]'s call site for where these are actually read.
1729struct DispatchLimits {
1730 /// How many *ordinary* candidates run at once. See
1731 /// [`crate::config::Daemon::max_concurrent_runs`].
1732 max_concurrent: usize,
1733 /// See [`crate::config::Daemon::pause_for_interrupts`].
1734 pause_for_interrupts: bool,
1735}
1736
1737/// Which semaphore, if any, dispatching a candidate should draw its permit
1738/// from.
1739///
1740/// Pure and separate from [`poll`]'s loop body for the same reason
1741/// [`advance_interrupt`] is: the choice between "skip the ordinary pool
1742/// entirely", "spend the one urgent slot" and "spend an ordinary slot" is
1743/// exactly the policy this feature adds, and a policy only exercisable by
1744/// running the whole loop is a policy nobody checks.
1745#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1746enum PermitKind {
1747 /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
1748 /// Checked first - a task can be both a land resume and marked
1749 /// [`Task::urgent`], and the resume's own "must not queue behind
1750 /// anything" guarantee takes precedence.
1751 None,
1752 /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
1753 /// (never in addition to trying) the ordinary pool. This is what lets
1754 /// an urgent task dispatch while every ordinary slot is already checked
1755 /// out, and what stops a second urgent task from opening a third run: it
1756 /// waits on this same one-slot semaphore rather than falling through to
1757 /// the ordinary one.
1758 Urgent,
1759 /// The ordinary `max_concurrent_runs` pool - unaffected by either of the
1760 /// above.
1761 Ordinary,
1762}
1763
1764/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
1765/// own boolean, already computed by the caller from [`land_resume_state`].
1766fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
1767 if priority {
1768 PermitKind::None
1769 } else if urgent {
1770 PermitKind::Urgent
1771 } else {
1772 PermitKind::Ordinary
1773 }
1774}
1775
1776/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
1777/// teardown and cannot skip the teardown on an early return.
1778///
1779/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
1780/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
1781/// land approval that has since been answered is dispatched outside that
1782/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
1783/// the whole point of parking there is that it must not queue behind
1784/// whatever else the loop happens to be running, even at the default of one.
1785/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
1786/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
1787/// these exemptions is still subject to the interrupt gate below, urgent
1788/// included: a land-resume or urgent candidate is exactly as much "something
1789/// else running" as an ordinary one from the interrupt sequence's point of
1790/// view, and letting either slip through while a run is being parked, or
1791/// while the interrupt task itself has the floor, is precisely the second
1792/// run 75dd's own "at most one run, ever, at once" guarantee must never
1793/// allow - see [`Interrupt`]'s own doc.
1794async fn poll(
1795 opts: &Opts,
1796 queue: &Queue,
1797 status: &Arc<Mutex<Status>>,
1798 home: &Path,
1799 worktrees_root: &Path,
1800 stop: &Stop,
1801 limits: DispatchLimits,
1802) -> Result<()> {
1803 let DispatchLimits {
1804 max_concurrent,
1805 pause_for_interrupts,
1806 } = limits;
1807 // Only consulted by `once`, where a task that just failed is still
1808 // `runnable` and would otherwise be picked up again inside the same drain.
1809 // In the long-running mode a later poll retrying a failed task is the point,
1810 // and the attempt counter is what bounds it.
1811 let mut attempted: Vec<String> = Vec::new();
1812 let sem = Arc::new(tokio::sync::Semaphore::new(max_concurrent));
1813 // One extra, permanent slot for `--urgent` tasks (see `Task::urgent`),
1814 // entirely separate from `sem`: an urgent candidate must dispatch
1815 // alongside whatever `sem` already has checked out, never by waiting for
1816 // one of those ordinary slots to free up and never by growing
1817 // `max_concurrent_runs` itself. Sized at one, not unbounded - see
1818 // `permit_kind`'s own doc - so a second `--urgent` task queues behind the
1819 // first on this same slot rather than opening a third run.
1820 let urgent_sem = Arc::new(tokio::sync::Semaphore::new(1));
1821 // A quota hit is a fact about the machine, not the task that happened to
1822 // surface it, and every other *ordinary* candidate is no less likely to
1823 // hit the same wall - see the warning below. A land-merge resume is
1824 // exempt: it is a human decision finishing, not a fresh competition, and
1825 // must not sit out a quota cooldown it did not cause.
1826 let quota_cooldown_until: Arc<Mutex<Option<Timestamp>>> = Arc::new(Mutex::new(None));
1827 let mut inflight: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
1828 let mut conductor = Conductor::new();
1829 // See `maybe_prune_cache_between_runs`'s own doc: this is the cache check
1830 // a congested queue would otherwise starve of the fully-idle branch below.
1831 let mut cache_last_checked: Option<Timestamp> = None;
1832 // See `Interrupt`'s own doc: in-memory only, advanced once per tick.
1833 let mut interrupt = Interrupt::Idle;
1834 // The `Pause` handed to each dispatched candidate's own `Runner` - see
1835 // `attempt`'s new parameter - kept here so the tick that decides to park
1836 // a run for an interrupt can reach that specific run's handle and no
1837 // other's. Pruned to whatever is still in flight at the top of every
1838 // tick, so a finished attempt's handle does not linger.
1839 let mut interrupt_pauses: std::collections::HashMap<String, crate::graph::Pause> =
1840 std::collections::HashMap::new();
1841
1842 while !stop.stopped() {
1843 lock(status).polls += 1;
1844
1845 // Reap whatever finished since the last tick without blocking on
1846 // anything still running. `InFlightGuard` already released the slot
1847 // even if the spawned attempt panicked; this only surfaces that it
1848 // happened, since a panic swallowed here otherwise leaves no trace.
1849 while let Some(result) = inflight.try_join_next() {
1850 if let Err(e) = result {
1851 tracing::error!("a spawned attempt did not finish cleanly: {e}");
1852 notices::raise(Notice::error(
1853 "loop:attempt",
1854 "A queued attempt ended abnormally; check the task it was running.",
1855 ));
1856 }
1857 }
1858
1859 let swept = sweep_stale_claims(queue, STALE_CLAIM);
1860 if !swept.is_empty() {
1861 tracing::warn!(
1862 "swept {} stale claim(s) left behind by an earlier daemon: {}",
1863 swept.len(),
1864 swept.join(", ")
1865 );
1866 }
1867 // Capture stalled work before reclaiming it. A dead daemon's ordinary
1868 // lock is swept and reclaimed in this same poll, but the conductor
1869 // must still see that it was stranded rather than only its mechanical
1870 // terminal state.
1871 let now = Timestamp::now();
1872
1873 // No run this daemon spawned is mid-compile right now, whether or
1874 // not another candidate is about to start - see
1875 // `maybe_prune_cache_between_runs`'s own doc for why this cannot
1876 // wait for the queue to run dry.
1877 if !stop.busy_now() {
1878 maybe_prune_cache_between_runs(
1879 &opts.repo,
1880 opts,
1881 home,
1882 stop,
1883 &mut cache_last_checked,
1884 now,
1885 )
1886 .await;
1887 }
1888
1889 let stalled = stalled_tasks(queue, home, now);
1890 let stalled_ids: std::collections::BTreeSet<_> =
1891 stalled.iter().map(|task| task.id.clone()).collect();
1892 let reclaimed = reclaim_orphaned_running(queue, opts.max_attempts);
1893 if !reclaimed.is_empty() {
1894 tracing::warn!(
1895 "reclaimed {} task(s) left `running` by a daemon that never \
1896 recorded the outcome: {}",
1897 reclaimed.len(),
1898 reclaimed.join(", ")
1899 );
1900 }
1901 let abandoned_runs = reclaim_abandoned_runs(home, now);
1902 if !abandoned_runs.is_empty() {
1903 tracing::warn!(
1904 "failed {} run(s) left behind by a killed process, past every \
1905 active seat's own timeout: {}",
1906 abandoned_runs.len(),
1907 abandoned_runs.join(", ")
1908 );
1909 }
1910
1911 // `home`, not `ask::Questions::open()`'s own process-global default:
1912 // `poll` is handed its home explicitly precisely so a test can point
1913 // it elsewhere, the same reason `Queue::at` and the status file path
1914 // are parameters rather than resolved here - see `drive`'s own doc.
1915 let questions = Questions::at(home.join("questions"));
1916
1917 // Deterministic: no model, run before the conductor sees anything so
1918 // its input reflects the queue's current, already-resolved state.
1919 resolve_blockers(queue, &questions);
1920 reconcile_task_questions(queue, &questions);
1921
1922 // The conductor gets one look per cycle, right before the loop takes
1923 // its next task, and only when there is something new to look at -
1924 // see `Conductor::worth_a_look`'s own doc for why "stalled is
1925 // non-empty" is the wrong test. Checked before `prepare` so an
1926 // unchanged cycle never pays for a synchronous config load.
1927 let finished: Vec<Task> = finished_tasks(queue)
1928 .into_iter()
1929 .filter(|task| !stalled_ids.contains(&task.id))
1930 .collect();
1931 let queued = queued_tasks(queue);
1932 // An empty queue has nothing to arrange. In particular, do not let
1933 // the conductor's initial snapshot cause synchronous config I/O
1934 // between the caller's stop notification and the idle wait below.
1935 if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
1936 && conductor.worth_a_look(queue, &stalled, &finished)
1937 {
1938 match prepare(&opts.repo, opts) {
1939 Ok(cfg) => {
1940 conductor
1941 .maybe_run(
1942 &cfg,
1943 &opts.repo,
1944 queue,
1945 &questions,
1946 home,
1947 &queued,
1948 &stalled,
1949 &finished,
1950 opts.max_attempts,
1951 )
1952 .await;
1953 }
1954 Err(e) => {
1955 tracing::warn!("conductor: no config: {e:#}");
1956 notices::raise(Notice::warn(
1957 "loop:no-config",
1958 "The loop could not read this repository's config, so held tasks are not being triaged.",
1959 ));
1960 }
1961 }
1962 }
1963
1964 let candidates: Vec<Task> = runnable(queue)
1965 .into_iter()
1966 .filter(|t| !opts.once || !attempted.contains(&t.id))
1967 .collect();
1968
1969 // A task id only stays a key here while its attempt is genuinely in
1970 // flight; `status.current` is the same liveness fact `InFlightGuard`
1971 // maintains for the phone's own status file, so this piggybacks on
1972 // it rather than tracking a second copy of the same thing.
1973 let in_flight: Vec<String> = lock(status)
1974 .current
1975 .iter()
1976 .map(|c| c.task.clone())
1977 .collect();
1978 interrupt_pauses.retain(|id, _| in_flight.contains(id));
1979
1980 interrupt =
1981 advance_interrupt_tick(pause_for_interrupts, interrupt, &in_flight, &candidates);
1982 if let Interrupt::Parking {
1983 parked,
1984 interrupt_task,
1985 } = &interrupt
1986 {
1987 let reason = format!(
1988 "task {} asked to run first",
1989 crate::run::short_of(interrupt_task)
1990 );
1991 for id in parked {
1992 if let Some(pause) = interrupt_pauses.get(id) {
1993 pause.park_because(reason.clone());
1994 }
1995 }
1996 }
1997 let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
1998
1999 let cooling_down =
2000 lock("a_cooldown_until).is_some_and(|until| Timestamp::now() < until);
2001
2002 let mut started_any = false;
2003 for candidate in candidates {
2004 if stop.stopped() {
2005 break;
2006 }
2007
2008 let resume = land_resume_state(&candidate);
2009 if resume == LandResume::StillWaiting {
2010 continue;
2011 }
2012 let priority = resume == LandResume::Ready;
2013
2014 if !priority && cooling_down {
2015 continue;
2016 }
2017 let permit = match permit_kind(priority, candidate.urgent) {
2018 PermitKind::None => None,
2019 PermitKind::Urgent => match Arc::clone(&urgent_sem).try_acquire_owned() {
2020 Ok(p) => Some(p),
2021 // The one urgent slot is already spoken for by another
2022 // `--urgent` task's run. Keep looking rather than falling
2023 // back to the ordinary pool - see `PermitKind::Urgent`'s
2024 // own doc - a later candidate might still be an ordinary
2025 // task with a free slot, or another priority resume.
2026 Err(_) => continue,
2027 },
2028 PermitKind::Ordinary => match Arc::clone(&sem).try_acquire_owned() {
2029 Ok(p) => Some(p),
2030 // No ordinary slot free right now. A later candidate in
2031 // this same list might still be a priority resume or an
2032 // urgent task, so keep looking rather than stopping here.
2033 Err(_) => continue,
2034 },
2035 };
2036
2037 // A claim we cannot take means another daemon, or a human running
2038 // `magi run`, got there first. That is not the task's fault and
2039 // must not spend one of its attempts: move to the next candidate
2040 // rather than recording a failure.
2041 let Ok(claim) = queue.claim(&candidate.id) else {
2042 tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
2043 continue;
2044 };
2045 // Re-read under the claim: the task on disk may have been held or
2046 // edited between the listing and the lock.
2047 let mut task = match queue.get(&candidate.id) {
2048 Ok(t) if t.status.runnable() => t,
2049 Ok(_) => continue,
2050 Err(e) => {
2051 tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
2052 continue;
2053 }
2054 };
2055 let task_id = task.id.clone();
2056 attempted.push(task_id.clone());
2057 lock(status).idle = false;
2058 // A stop asked for from here on is "finishing", not "stopped": the
2059 // run gets to reach a terminal status before the loop returns.
2060 stop.enter();
2061 started_any = true;
2062
2063 // A fresh, unshared handle - never `stop.pause()` - so parking
2064 // this run for an interrupt cannot leak into any other run this
2065 // loop ever drives. See `Pause`'s own doc.
2066 let run_pause = crate::graph::Pause::new();
2067 interrupt_pauses.insert(task_id.clone(), run_pause.clone());
2068
2069 let opts = opts.clone();
2070 let queue = queue.clone();
2071 let status = Arc::clone(status);
2072 let stop = stop.clone();
2073 let quota_cooldown_until = Arc::clone("a_cooldown_until);
2074 inflight.spawn(async move {
2075 // Held for the whole attempt: dropping either at the end of
2076 // this task is what releases the claim and, for an ordinary
2077 // candidate, frees its concurrency slot back to the loop.
2078 let _claim = claim;
2079 let _permit = permit;
2080 // See `InFlightGuard`: this must survive a panic inside `attempt`.
2081 let _inflight = InFlightGuard {
2082 status: &status,
2083 stop: &stop,
2084 task_id: &task_id,
2085 };
2086 let quota = attempt(&opts, &queue, &status, &stop, run_pause, &mut task).await;
2087 lock(&status).completed += 1;
2088 // A quota loss is a fact about the machine, not this task, and
2089 // the next ordinary candidate the loop offers is no less
2090 // likely to hit the same wall: without a cooldown here a
2091 // whole backlog can be run - and failed - in the seconds it
2092 // takes each attempt to notice the CLI is out of quota.
2093 let now = Timestamp::now();
2094 if let Some(until) = cooldown_until("a, now) {
2095 let wait = until.as_second() - now.as_second();
2096 *lock("a_cooldown_until) = Some(until);
2097 let hint = quota
2098 .iter()
2099 .find(|q| q.reset.is_some())
2100 .and_then(|q| q.reset.as_deref());
2101 match hint {
2102 Some(h) => tracing::warn!(
2103 "quota hit; waiting {wait}s before taking another ordinary task \
2104 (CLI reported reset: {h})"
2105 ),
2106 None => tracing::warn!(
2107 "quota hit; waiting {wait}s before taking another ordinary task \
2108 (no reset hint reported)"
2109 ),
2110 }
2111 }
2112 });
2113 }
2114
2115 if started_any {
2116 continue;
2117 }
2118
2119 if stop.busy_now() {
2120 // Something started on an earlier tick is still running. Recheck
2121 // soon rather than sleeping out the whole poll interval - a freed
2122 // slot, or a land approval answered mid-run, must not sit idle
2123 // for it.
2124 stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
2125 continue;
2126 }
2127
2128 // Truly idle: nothing new to start and nothing still running.
2129 lock(status).idle = true;
2130 if opts.once {
2131 // A one-shot drain must perform the same post-work cleanup as a
2132 // daemon that reached a normal idle interval. The startup pass
2133 // cannot see runs or cache files produced by this drain.
2134 janitor(&opts.repo, opts, home, worktrees_root).await;
2135 resweep_superseded_attempts(queue, home);
2136 triage_held(queue, home, opts).await;
2137 break;
2138 }
2139 stop.idle(opts.poll).await;
2140 if stop.stopped() {
2141 continue;
2142 }
2143 // Housekeeping only after a full quiet interval. Running it before
2144 // the first idle wait can block the executor while an operator's
2145 // stop request is waiting to be scheduled, defeating Stop's retained
2146 // wake permit. No run can start while this branch is active, so the
2147 // janitor still never races an in-flight compile.
2148 janitor(&opts.repo, opts, home, worktrees_root).await;
2149 resweep_superseded_attempts(queue, home);
2150 triage_held(queue, home, opts).await;
2151 }
2152
2153 // Never return while a run is still in flight, whichever way the loop
2154 // above exited: a stop only sets a flag - see `serve_until` - and
2155 // returning here while `inflight` still holds spawned work would abandon
2156 // it exactly as a mid-node kill would.
2157 while let Some(result) = inflight.join_next().await {
2158 if let Err(e) = result {
2159 tracing::error!("a spawned attempt did not finish cleanly: {e}");
2160 notices::raise(Notice::error(
2161 "loop:attempt",
2162 "A queued attempt ended abnormally; check the task it was running.",
2163 ));
2164 }
2165 }
2166 Ok(())
2167}
2168
2169/// Run one claimed task to a terminal status and record the outcome.
2170///
2171/// Every transition is flushed to the queue as it happens, so the state on disk
2172/// is what actually occurred rather than what this process still intends to
2173/// write.
2174async fn attempt(
2175 opts: &Opts,
2176 queue: &Queue,
2177 status: &Arc<Mutex<Status>>,
2178 stop: &Stop,
2179 interrupt_pause: crate::graph::Pause,
2180 task: &mut Task,
2181) -> Vec<QuotaLoss> {
2182 let repo = repo_for(task, &opts.repo);
2183 tracing::info!(
2184 "task {} — {} (repo {})",
2185 task.short(),
2186 task.title,
2187 repo.display()
2188 );
2189
2190 let mut config = match prepare(&repo, opts) {
2191 Ok(c) => c,
2192 Err(e) => {
2193 // A setup failure spends an attempt even though no run was minted.
2194 // Without that, a task naming a repository that does not exist
2195 // would be retried at every poll for as long as the daemon lives.
2196 task.attempts += 1;
2197 task.fail(format!("config: {e:#}"), opts.max_attempts);
2198 record(queue, task);
2199 return Vec::new();
2200 }
2201 };
2202 apply_solo(&mut config, task);
2203
2204 // The free-space gate, checked *before* anything is minted: a task that
2205 // waits out a full disk costs nothing yet, and must not spend an attempt
2206 // or start a run the machine cannot finish. Held tasks stay in the list
2207 // for the human to see, and `magi task release` re-queues them when space
2208 // comes back - the same recovery as any other hold. A volume whose free
2209 // space cannot be measured closes the gate too: starting a run blind on a
2210 // disk that may be full is how the machine ends up with 6.7 GB free.
2211 if let Some(reason) = disk_gate(&repo, &config) {
2212 task.last_error = Some(reason.clone());
2213 task.hold_machine(Some(reason.clone()));
2214 record(queue, task);
2215 tracing::warn!("holding {} for want of disk space: {reason}", task.short());
2216 // Stable wording - the free-space figures live in the task's hold
2217 // reason, and changing numbers would relight the bell every poll.
2218 notices::raise(
2219 Notice::warn(
2220 &format!("disk:{}", repo.display()),
2221 "A task was held for want of free disk space; free some, then release it from the queue.",
2222 )
2223 .link(Link::Task {
2224 id: task.id.clone(),
2225 }),
2226 );
2227 return Vec::new();
2228 }
2229
2230 // A resumable run of this task is carried on, never re-competed. The
2231 // candidates are built and paid for, and a fresh competition races a
2232 // second implementation against them.
2233 //
2234 // Two runs paid for that lesson. Run 01c2 was blocked and the loop
2235 // started 3cbf on the same task a moment later, duplicating two and a
2236 // half hours of agent work. Then b25f stalled on a judge that timed out
2237 // and one that answered with no JSON - `quota: 0`, so nothing the machine
2238 // was to blame for - and 4043 started **one second** later, buying three
2239 // fresh implementations to reach the same panel. `RunStatus::resumable`
2240 // rather than `!done()` is what catches the second case: a stall is
2241 // terminal, and its cheap recovery re-asks only the absent seats.
2242 //
2243 // A load failure is warned about rather than silently read as "not
2244 // resumable": the alternative is exactly what let a schema mismatch on
2245 // run `eba2` fall through to a full re-competition with nobody told why.
2246 // `crate::conduct` is what actually offers a better answer than
2247 // `Runner::start` here (see `Recovery::Review`), once this task's next
2248 // failure shows it up as `held`/`failed` with the run state unreadable.
2249 let unfinished = (!task.fresh_start)
2250 .then(|| unfinished_run(&task.runs, task.short()))
2251 .flatten();
2252 // `crate::conduct` chose `Review` for this task on an earlier cycle: its
2253 // branch survived, and this reopens exactly that branch as a
2254 // review-only pass rather than resuming or competing again. Consumed
2255 // (cleared) here whichever way this goes, so it never outlives this one
2256 // attempt - see `queue::Task::review_branch`.
2257 let review_branch = task.review_branch.take();
2258 let branch_exists = match &review_branch {
2259 Some(branch) => crate::git::branch_exists(&repo, branch)
2260 .await
2261 .unwrap_or(false),
2262 None => false,
2263 };
2264 let starter = choose_starter(
2265 review_branch.as_deref(),
2266 branch_exists,
2267 unfinished.as_deref(),
2268 );
2269 let started = match &starter {
2270 Starter::Review(branch) => {
2271 tracing::info!(
2272 "task {} reopens `{branch}` as a review-only pass",
2273 task.short()
2274 );
2275 Runner::review(&repo, branch, config).await
2276 }
2277 Starter::Resume(id) => {
2278 tracing::info!("resuming run {id} rather than competing again");
2279 Runner::resume(id).map(|mut r| {
2280 if let Some(instruction) =
2281 prepare_instruction(&starter, Some(&r.state.instruction), task)
2282 {
2283 r.state.instruction = instruction;
2284 }
2285 r
2286 })
2287 }
2288 Starter::Start => {
2289 if let Some(branch) = &review_branch {
2290 tracing::warn!(
2291 "conductor chose review for task {} but branch `{branch}` no longer \
2292 exists; requeuing as a fresh competition instead",
2293 task.short()
2294 );
2295 }
2296 let instruction = prepare_instruction(&starter, None, task)
2297 .unwrap_or_else(|| task.instruction.clone());
2298 Runner::start(&repo, instruction, config).await
2299 }
2300 };
2301 let mut runner = match started {
2302 Ok(r) => r,
2303 Err(e) => {
2304 task.attempts += 1;
2305 task.fail(format!("could not start the run: {e:#}"), opts.max_attempts);
2306 record(queue, task);
2307 return Vec::new();
2308 }
2309 };
2310 // A stop that means "park" reaches the graph through this handle.
2311 runner.on_pause(stop.pause());
2312 // `poll`'s interrupt scheduler reaches this one run - and no other -
2313 // through this handle. See `Pause`'s own doc for why these are never
2314 // the same one.
2315 runner.watch_interrupt(interrupt_pause);
2316
2317 // `start` has minted the run, so the task can now point at it. Persisting
2318 // `Running` before `execute` is what makes a crash mid-run legible.
2319 let run = runner.state.id.clone();
2320 task.start(run.clone());
2321 record(queue, task);
2322 lock(status).current.push(Current {
2323 task: task.id.clone(),
2324 run,
2325 });
2326
2327 // `RunState::quota` is the run's whole history across every resume, so
2328 // only what this execution added may arm the cooldown or earn a refund.
2329 let quota_before = runner.state.quota.clone();
2330 let detail = match runner.execute().await {
2331 Ok(()) => describe(&runner.state),
2332 Err(e) => format!("{e:#}"),
2333 };
2334 let fresh = losses_this_attempt("a_before, &runner.state.quota);
2335 let verdict = Verdict {
2336 status: runner.state.status,
2337 // A run that opened a pull request handed its work over, whatever the
2338 // gate then decided about merging it.
2339 left_pr: runner.state.pr.is_some(),
2340 // Only a rate limit earns the task its attempt back - and only one
2341 // suffered now: a refund justified by a previous session's loss is
2342 // the same mistake as re-arming the cooldown from it. A stalled run
2343 // resumed without hitting quota again therefore spends its attempt,
2344 // like any other failure of the task's own.
2345 quota_hit: !fresh.is_empty(),
2346 // A run that parked was asked to stop; that is not a failure and must
2347 // not spend an attempt, or replacing the binary a few times would
2348 // exhaust a task's budget without an agent ever misbehaving.
2349 parked: runner.state.parked,
2350 // A quota loss that left nothing viable is the same machine fact as a
2351 // `Stalled` quota loss; see `settle`'s doc table.
2352 no_viable_candidates: runner.state.viable().is_empty(),
2353 };
2354 settle_and_diagnose(task, verdict, &detail, opts.max_attempts, &runner.state);
2355 if task.status == TaskStatus::Done {
2356 supersede_prior_runs(task, &crate::run::home());
2357 }
2358 record(queue, task);
2359 tracing::info!(
2360 "task {} is {} after run {} ({})",
2361 task.short(),
2362 task.status.as_str(),
2363 runner.state.short(),
2364 label(runner.state.status)
2365 );
2366 fresh
2367}
2368
2369/// The quota losses `after` holds that `before` did not: what one execution
2370/// suffered, as opposed to the run's history.
2371///
2372/// Compared by value rather than by length or position because
2373/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
2374/// the vector can shrink and shift under a resume. A retried seat that hits
2375/// quota again is a `push` with a new `at`, so it shows up as new here.
2376/// `reclaim` deliberately keeps reading the whole history: after a crash there
2377/// is no attempt boundary to diff against.
2378fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
2379 after
2380 .iter()
2381 .filter(|q| !before.contains(q))
2382 .cloned()
2383 .collect()
2384}
2385
2386/// When the loop-wide quota cooldown should end, given this attempt's losses;
2387/// `None` when there were none. Reset-hint parsing and the cap live here.
2388fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
2389 if quota.is_empty() {
2390 return None;
2391 }
2392 let with_hint = quota.iter().find(|q| q.reset.is_some());
2393 let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
2394 let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
2395 let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
2396 Some(
2397 now.checked_add(jiff::SignedDuration::from_secs(secs))
2398 .unwrap_or(Timestamp::MAX),
2399 )
2400}
2401
2402/// Cut this attempt's candidate count to one when the task asked to run
2403/// alone.
2404///
2405/// Pure and separate from [`attempt`] so the one thing this feature changes -
2406/// which `candidates` a `solo` task's run is built with - can be asserted
2407/// without minting a run: `attempt` drives `graph::Runner`, which spawns real
2408/// agent CLIs, and no test may do that. `config` is mutated in place, taken by
2409/// value from the caller's own copy, so a repository's `magi.toml` on disk is
2410/// never touched - only the `Config` this one attempt hands to `Runner::start`.
2411fn apply_solo(config: &mut Config, task: &Task) {
2412 if task.solo {
2413 config.graph.candidates = 1;
2414 }
2415}
2416
2417/// Load the config for a task's repository, with the merge override applied.
2418fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
2419 let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
2420 if let Some(mode) = &opts.merge {
2421 config.merge.mode = merge_mode(mode)?;
2422 }
2423 Ok(config)
2424}
2425
2426/// Prune the shared build cache back under its cap at a safe boundary
2427/// between runs, so a queue that never empties - and so never reaches
2428/// [`poll`]'s fully-idle branch, where the ordinary [`janitor`] pass lives -
2429/// does not leave the cache to grow unchecked for as long as the backlog
2430/// lasts.
2431///
2432/// Called from [`poll`] only when `stop.busy_now()` is already `false`: the
2433/// same liveness fact the idle branch's own janitor call rests on - no run
2434/// this daemon spawned is still mid-compile - so pruning here races nothing.
2435/// The caller must not call this while a run is in flight; there is no
2436/// second `busy_now()` check inside this function, on purpose, because there
2437/// is nothing left to check that `busy_now()` has not already answered.
2438///
2439/// A stop that has already been asked for *is* checked here, for a different
2440/// reason. [`clean::prune_cache_if_over_limit`] walks the whole cache
2441/// synchronously before it decides anything, so the poll loop cannot get back
2442/// to its own `stopped()` test until that walk is over — and a loop already
2443/// on its way out must not make the operator wait out housekeeping it is
2444/// about to stop needing. This is the same call the idle branch makes when it
2445/// rechecks `stop.stopped()` after its wait before reaching [`janitor`], and
2446/// it matters more here: `busy_now()` is false throughout, so
2447/// [`Stop::finishing`] would report a stop as already landed while the walk
2448/// still held the loop. Nothing is lost by skipping — the cap is a standing
2449/// policy, and the next daemon's startup pass measures the same cache.
2450///
2451/// Rate-limited by [`CACHE_CHECK_INTERVAL_SECS`] rather than run on every
2452/// poll: a busy loop reaches this the instant one run's `InFlightGuard` drops
2453/// and the next has not yet claimed a task, which can be every few
2454/// milliseconds, and re-walking a multi-gigabyte cache that often would cost
2455/// more than the growth it is guarding against.
2456async fn maybe_prune_cache_between_runs(
2457 repo: &Path,
2458 opts: &Opts,
2459 home: &Path,
2460 stop: &Stop,
2461 last_checked: &mut Option<Timestamp>,
2462 now: Timestamp,
2463) {
2464 if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
2465 return;
2466 }
2467 *last_checked = Some(now);
2468 let cfg = match prepare(repo, opts) {
2469 Ok(cfg) => cfg,
2470 Err(e) => {
2471 tracing::warn!("cache check: no config: {e:#}");
2472 return;
2473 }
2474 };
2475 match clean::prune_cache_if_over_limit(&cfg, home) {
2476 Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
2477 "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
2478 pruned.files,
2479 pruned.freed
2480 ),
2481 Ok(_) => {}
2482 Err(e) => {
2483 tracing::warn!("housekeep: prune cache: {e:#}");
2484 notices::raise_in(
2485 home,
2486 Notice::warn(
2487 "housekeep:cache",
2488 "Pruning the shared build cache failed; disk usage may keep growing.",
2489 ),
2490 );
2491 }
2492 }
2493}
2494
2495/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
2496/// now, given when it last did (if ever). Pure, so the cadence is asserted
2497/// directly rather than by waiting out real minutes in a test.
2498fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
2499 last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
2500}
2501
2502/// The disk janitor, with its housekeeping logged rather than fatal.
2503///
2504/// Called only at the loop's idle points, for the reason the caller documents:
2505/// a prune racing a live compile would delete files mid-build. The config is
2506/// re-read on every call because the repository that just ran may not be the
2507/// daemon's own default, and the cache directory is a repository fact.
2508///
2509/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
2510/// and [`crate::run::default_worktree_root`] read here, for the same reason
2511/// [`drive`] takes its queue and status file rather than resolving them: a
2512/// test driving the loop must not reach through to the operator's real home
2513/// or worktree bay just because the janitor runs on every idle tick.
2514/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
2515/// to get wrong silently - a test's `home` was already isolated, but nothing
2516/// exercised the parameter next to it, so a real worktree bay stayed wired in
2517/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
2518/// it for real, every test in this file that drives the loop at all started
2519/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
2520async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
2521 let cfg = match prepare(repo, opts) {
2522 Ok(cfg) => cfg,
2523 Err(e) => {
2524 tracing::warn!("housekeep: no config: {e:#}");
2525 return;
2526 }
2527 };
2528 // A run's own worktree lives under `config.graph.worktree_root` when the
2529 // repository sets one - the same precedence `RunState::worktree_root`
2530 // uses - and `worktrees_root` only stands in for the *default* an
2531 // unconfigured repository resolves to (see this function's own
2532 // parameter, or the test fixture wiring one to a fake path). Housekeeping
2533 // that always swept the default regardless of this override would never
2534 // see, and so never reclaim, a single worktree for a repository that
2535 // relocated them elsewhere.
2536 let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
2537 let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
2538 // Reported whenever there is anything to say, not only when `folded > 0`:
2539 // the incident this exists to prevent was 90 of 93 runs skipped and 0
2540 // folded, on every single pass, for months - a report gated on `folded`
2541 // would have stayed silent through every one of them.
2542 if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
2543 let mut extra = Vec::new();
2544 if out.unreadable > 0 {
2545 extra.push(format!("{} unreadable", out.unreadable));
2546 }
2547 if out.orphaned_worktrees > 0 {
2548 extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
2549 }
2550 let detail = if extra.is_empty() {
2551 String::new()
2552 } else {
2553 format!(" ({})", extra.join(", "))
2554 };
2555 tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
2556 }
2557 if out.external_merges_recorded > 0 {
2558 tracing::info!(
2559 "housekeep: recorded {} run(s) as merged externally",
2560 out.external_merges_recorded
2561 );
2562 }
2563 if out.cache_files > 0 {
2564 tracing::info!(
2565 "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
2566 out.cache_files,
2567 out.cache_freed
2568 );
2569 }
2570 if out.questions_abandoned > 0 {
2571 tracing::info!(
2572 "housekeep: abandoned {} question(s) left open by a finished run",
2573 out.questions_abandoned
2574 );
2575 }
2576}
2577
2578/// Run [`triage::run_once`] and log whatever it did, the same "only when
2579/// there is something to say" rule [`janitor`] follows for its own report.
2580///
2581/// Called at the same idle points as [`janitor`] - once per full poll
2582/// interval, never mid-attempt - for the same reason: it is not liveness
2583/// critical, and a task's own `hold_reason` string is the one thing this
2584/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
2585/// tick for no benefit.
2586async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
2587 let questions = Questions::at(home.join("questions"));
2588 let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
2589 if report.is_empty() {
2590 return;
2591 }
2592 if !report.quarantined.is_empty() {
2593 tracing::info!(
2594 "triage: held {} blocked task(s) whose blocked-on task or \
2595 question no longer exists: {}",
2596 report.quarantined.len(),
2597 report.quarantined.join(", ")
2598 );
2599 }
2600 if !report.resumed.is_empty() {
2601 tracing::info!(
2602 "triage: resumed {} held task(s) whose machine hold had resolved: {}",
2603 report.resumed.len(),
2604 report.resumed.join(", ")
2605 );
2606 }
2607 if !report.asked.is_empty() {
2608 tracing::info!(
2609 "triage: asked about {} held task(s): {}",
2610 report.asked.len(),
2611 report.asked.join(", ")
2612 );
2613 }
2614 if !report.answered.is_empty() {
2615 tracing::info!(
2616 "triage: applied {} operator answer(s): {}",
2617 report.answered.len(),
2618 report.answered.join(", ")
2619 );
2620 }
2621}
2622
2623/// The free-space gate: what stands between this task and a new run, if
2624/// anything. `Some(reason)` holds the task; `None` lets it start.
2625///
2626/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
2627/// the operator opted out. A measurement failure is a gate, not a pass: both
2628/// sides of "cannot tell" are served by not starting.
2629fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
2630 disk_gate_with(repo, config, crate::disk::free_bytes)
2631}
2632
2633/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
2634/// test can assert the exact wiring `attempt` runs - config's threshold in,
2635/// task-holding reason out - without asking the real machine's disk anything.
2636fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
2637 repo: &Path,
2638 config: &Config,
2639 free_bytes: F,
2640) -> Option<String> {
2641 let min = config.disk.min_free_bytes;
2642 if min == 0 {
2643 return None;
2644 }
2645 match free_bytes(repo) {
2646 Ok(free) => crate::disk::gate(free, min),
2647 Err(e) => Some(format!(
2648 "could not measure free space on {} ({e}); the disk gate refuses \
2649 to let a run start blind",
2650 repo.display()
2651 )),
2652 }
2653}
2654
2655/// How long to wait before offering another task when a run lost a seat to a
2656/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
2657/// could read, or carried nothing at all. Long enough that a quota outage
2658/// cannot burn through a whole backlog in the few seconds each doomed attempt
2659/// takes to fail; short enough that a quota which clears early is not left
2660/// idle for the fallback's sake.
2661const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
2662
2663/// Longest a parsed reset hint may push the wait out to. The hint comes from
2664/// the CLI's own words, not a contract, so a parsing slip that lands a day
2665/// away must not leave the loop asleep for a day.
2666const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
2667
2668/// How long [`poll`] should wait before offering the next task, after a run
2669/// lost at least one seat to a rate limit.
2670///
2671/// Pure and separate from the loop so the policy can be exercised without a
2672/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
2673/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
2674/// nothing to parse, or the parsed time has already passed; `cap` bounds how
2675/// far a parsed hint is trusted to push the wait out.
2676fn quota_wait(
2677 reset_at: Option<Timestamp>,
2678 now: Timestamp,
2679 fallback: Duration,
2680 cap: Duration,
2681) -> Duration {
2682 match reset_at {
2683 Some(at) if at > now => {
2684 let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
2685 Duration::from_secs(secs).min(cap)
2686 }
2687 _ => fallback,
2688 }
2689}
2690
2691/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
2692///
2693/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
2694/// explains why parsing it exactly "would be a bug factory" — so this only
2695/// recognises the shapes actually observed in the wild, and returns `None`
2696/// for anything else rather than guess at a format nobody has seen.
2697///
2698/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
2699/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
2700/// said it, not from whenever this loop happens to read it: anchoring on `now`
2701/// would push the reset later on every read and would read an already-elapsed
2702/// reset as still in the future. (A long hint is still clamped by
2703/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
2704fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
2705 parse_reset_hint_zoned(text, now)
2706 .or_else(|| parse_reset_hint_dated(text))
2707 .or_else(|| parse_reset_hint_relative(text, recorded))
2708}
2709
2710/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
2711/// optional but at least one required, in that order. A bare number or any
2712/// unknown unit is refused.
2713fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
2714 let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
2715 let mut rest = rest.trim();
2716 if rest.is_empty() {
2717 return None;
2718 }
2719 let mut total: i64 = 0;
2720 let mut matched = false;
2721 for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
2722 if let Some((digits, tail)) = rest.split_once(unit)
2723 && !digits.is_empty()
2724 && digits.bytes().all(|b| b.is_ascii_digit())
2725 {
2726 total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
2727 rest = tail;
2728 matched = true;
2729 }
2730 }
2731 if !rest.is_empty() || !matched {
2732 return None;
2733 }
2734 recorded
2735 .checked_add(jiff::SignedDuration::from_secs(total))
2736 .ok()
2737}
2738
2739/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
2740/// case-insensitive) into a 24-hour hour and minute. Shared by every
2741/// reset-hint shape below.
2742fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
2743 let clock = clock.trim().to_lowercase();
2744 let (digits, pm) = clock
2745 .strip_suffix("am")
2746 .map(|d| (d, false))
2747 .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
2748 let (h, m) = digits.trim().split_once(':')?;
2749 let mut hour: i8 = h.trim().parse().ok()?;
2750 let minute: i8 = m.trim().parse().ok()?;
2751 if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
2752 return None;
2753 }
2754 if pm && hour != 12 {
2755 hour += 12;
2756 } else if !pm && hour == 12 {
2757 hour = 0;
2758 }
2759 Some((hour, minute))
2760}
2761
2762/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
2763/// and a zone, never a date. A clock reading already past today is read as
2764/// tomorrow's: a CLI naming a same-day reset that has already gone by means
2765/// the window rolled over while nothing was watching.
2766fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
2767 let open = text.find('(')?;
2768 let close = text.rfind(')')?;
2769 if close <= open {
2770 return None;
2771 }
2772 let zone = text[open + 1..close].trim();
2773 let (hour, minute) = parse_12h_clock(&text[..open])?;
2774 let tz = jiff::tz::TimeZone::get(zone).ok()?;
2775 let candidate = now
2776 .to_zoned(tz)
2777 .with()
2778 .hour(hour)
2779 .minute(minute)
2780 .second(0)
2781 .millisecond(0)
2782 .microsecond(0)
2783 .nanosecond(0)
2784 .build()
2785 .ok()?;
2786 let mut at = candidate.timestamp();
2787 if at <= now {
2788 at += jiff::SignedDuration::from_hours(24);
2789 }
2790 Some(at)
2791}
2792
2793/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
2794/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
2795/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
2796/// "already past today" correction to make: the year already disambiguates
2797/// it. Scanned as a five-word window so it can be pulled out of the middle
2798/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
2799/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
2800/// any other timestamp with no zone attached.
2801fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
2802 let words: Vec<&str> = text.split_whitespace().collect();
2803 if words.len() < 5 {
2804 return None;
2805 }
2806 (0..=words.len() - 5)
2807 .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
2808}
2809
2810/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
2811/// parenthesis right after the window is refused rather than ignored — it
2812/// reads as an explicit zone annotation on a shape that otherwise carries
2813/// none, and guessing UTC anyway would be exactly the silent misread this
2814/// module's parsing otherwise avoids.
2815fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
2816 if trailing.is_some_and(|next| next.starts_with('(')) {
2817 return None;
2818 }
2819 let month = month_number(window[0])?;
2820 let day_token = window[1].strip_suffix(',')?.to_lowercase();
2821 let day_digits = ["st", "nd", "rd", "th"]
2822 .iter()
2823 .find_map(|suffix| day_token.strip_suffix(*suffix))?;
2824 let day: i8 = day_digits.parse().ok()?;
2825 let year_token = window[2];
2826 if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
2827 return None;
2828 }
2829 let year: i16 = year_token.parse().ok()?;
2830 // The am/pm word carries the sentence's own trailing punctuation, e.g.
2831 // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
2832 // reusing the same 12-hour clock reader the bracketed shape uses.
2833 let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
2834 let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
2835 let date = jiff::civil::Date::new(year, month, day).ok()?;
2836 let candidate = date
2837 .at(hour, minute, 0, 0)
2838 .to_zoned(jiff::tz::TimeZone::UTC)
2839 .ok()?;
2840 Some(candidate.timestamp())
2841}
2842
2843/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
2844/// case-insensitively, into a 1-based month number.
2845fn month_number(name: &str) -> Option<i8> {
2846 const NAMES: [&str; 12] = [
2847 "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
2848 ];
2849 let lower = name.to_lowercase();
2850 NAMES
2851 .iter()
2852 .position(|n| *n == lower.as_str())
2853 .map(|i| i as i8 + 1)
2854}
2855
2856/// Resuming a `Blocked` run that already spent every review round its own
2857/// config allowed cannot make progress: `graph::Runner`'s review loop walks
2858/// `(reviews.len()+1)..=max_rounds`, which is empty once `reviews.len()` has
2859/// reached `max_rounds`, so `execute` would settle straight back to
2860/// `Blocked` without asking anyone anything. Read-only against a state this
2861/// build never mutates — `src/graph.rs` stays untouched — but without this
2862/// check, [`unfinished_run`] would keep reporting such a run as still
2863/// "unfinished", and `crate::conduct::Recovery::Requeue` (whose whole
2864/// promise is a fresh competition when a design needs to change) would
2865/// silently resume the exhausted run instead, spending an attempt on a
2866/// cycle that cannot change anything.
2867fn exhausted_review_budget(state: &RunState) -> bool {
2868 state.status == RunStatus::Blocked && state.reviews.len() >= state.config.graph.review_rounds
2869}
2870
2871/// This task's *most recent* run, if resuming it would actually make
2872/// progress. `short` is only for the warning's own message.
2873///
2874/// Only ever `runs.last()` — never a search back through older history.
2875/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
2876/// mint, oldest first, and every entry before the last one was already
2877/// superseded at the moment it was minted: the daemon only ever starts a new
2878/// run when the previous one was not worth resuming (unresumable, exhausted,
2879/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
2880/// opens a fresh review-only run alongside an older, already-failed
2881/// competition. Searching further back would let an old run that merely
2882/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
2883/// behind, say — get resumed instead of the fresh competition
2884/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
2885/// nothing asked to revisit.
2886///
2887/// Two runs paid for the "prefer resuming over restarting" half of this
2888/// lesson, which is why this still checks `runs.last()` rather than always
2889/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
2890/// task a moment later, duplicating two and a half hours of agent work. Then
2891/// b25f stalled on a judge that timed out and one that answered with no JSON
2892/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
2893/// **one second** later, buying three fresh implementations to reach the
2894/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
2895/// the second case: a stall is terminal, and its cheap recovery re-asks only
2896/// the absent seats. [`exhausted_review_budget`] is the other half: a run
2897/// that is technically `resumable()` but provably cannot progress must not
2898/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
2899/// no-op instead of the fresh competition it promises.
2900///
2901/// A load failure is warned about rather than silently read as "not
2902/// resumable": the alternative is exactly what let a schema mismatch on run
2903/// `eba2` fall through to a full re-competition with nobody told why.
2904/// `crate::conduct` is what actually offers a better answer than
2905/// `Runner::start` here (see `Recovery::Review`), once this task's next
2906/// failure shows it up as `held`/`failed` with the run state unreadable.
2907fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
2908 unfinished_run_with(runs, short, RunState::load)
2909}
2910
2911/// [`unfinished_run`] with an injected state reader. Tests provide their
2912/// fixtures directly rather than touching the process-global run home.
2913fn unfinished_run_with<F>(runs: &[String], short: &str, load: F) -> Option<String>
2914where
2915 F: FnOnce(&str) -> Result<RunState>,
2916{
2917 let id = runs.last()?;
2918 match load(id) {
2919 Ok(s) if s.status.resumable() && !exhausted_review_budget(&s) => Some(id.clone()),
2920 Ok(_) => None,
2921 Err(e) => {
2922 tracing::warn!("could not read run {id} for task {short}: {e:#}");
2923 None
2924 }
2925 }
2926}
2927
2928/// Which of the three ways [`attempt`] can mint or continue a run this task
2929/// should use.
2930#[derive(Debug, Clone, PartialEq, Eq)]
2931enum Starter {
2932 /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
2933 /// and that still exists.
2934 Review(String),
2935 /// `crate::graph::Runner::resume` on an unfinished run of this task.
2936 Resume(String),
2937 /// `crate::graph::Runner::start`: a fresh competition.
2938 Start,
2939}
2940
2941/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
2942/// this attempt should use. Pure, and separate from [`attempt`], so the
2943/// routing itself is assertable without spawning a real graph or a git
2944/// process: `attempt`'s own `crate::git::branch_exists` call has already
2945/// happened by the time this is called.
2946///
2947/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
2948/// whose branch is gone falls all the way through to [`Starter::Start`], not
2949/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
2950/// old (likely `Blocked`) run in the first place, and a branch that vanished
2951/// out from under that choice is not evidence resuming it would fare better.
2952fn choose_starter(
2953 review_branch: Option<&str>,
2954 branch_exists: bool,
2955 unfinished: Option<&str>,
2956) -> Starter {
2957 match review_branch {
2958 Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
2959 Some(_) => Starter::Start,
2960 None => match unfinished {
2961 Some(id) => Starter::Resume(id.to_owned()),
2962 None => Starter::Start,
2963 },
2964 }
2965}
2966
2967/// Which repository a task runs in. A task that names none — the normal case
2968/// for one filed from a phone — runs in the daemon's own default.
2969fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
2970 if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
2971 return fallback.to_path_buf();
2972 }
2973 task.repo.clone()
2974}
2975
2976/// The header [`append_answers`] appends operator answers under. Shared with
2977/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
2978/// rather than grown a new block on every resume.
2979const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
2980
2981/// Render the first `count` answers in the block appended to an instruction.
2982fn answers_block(task: &Task, count: usize) -> String {
2983 let mut s = ANSWERS_HEADER.to_owned();
2984 for a in &task.answers[..count] {
2985 s.push_str(&format!("- {}: {}\n", a.question, a.answer));
2986 }
2987 s
2988}
2989
2990/// Append every answer `crate::conduct` has collected for `task` onto `base`,
2991/// in the shape both [`instruction_for`] and [`resumed_instruction`] use.
2992fn append_answers(base: &str, task: &Task) -> String {
2993 if task.answers.is_empty() {
2994 return base.to_owned();
2995 }
2996 let mut s = base.to_owned();
2997 s.push_str(&answers_block(task, task.answers.len()));
2998 s
2999}
3000
3001/// Drop the prior answer block only when it is exactly the suffix this task
3002/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
3003/// the task author is ordinary instruction text, not a block to remove.
3004fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
3005 for count in (1..=task.answers.len()).rev() {
3006 let block = answers_block(task, count);
3007 if let Some(base) = instruction.strip_suffix(&block) {
3008 return base;
3009 }
3010 }
3011 instruction
3012}
3013
3014/// The instruction handed to `Runner::start`: the task's own text, plus any
3015/// operator answers `crate::conduct` collected for it (see
3016/// [`Task::answers`]), so a decision the operator actually made reaches the
3017/// implementers rather than only clearing the block that was waiting on it.
3018///
3019/// Appended rather than merged into [`Task::instruction`] itself, so the
3020/// task's own record stays exactly what its author wrote.
3021fn instruction_for(task: &Task) -> String {
3022 append_answers(&task.instruction, task)
3023}
3024
3025/// The instruction a resumed run should carry on with: whatever it already
3026/// had, refreshed with the task's *current* operator answers.
3027///
3028/// A resumable run's own `RunState::instruction` predates any answer
3029/// `crate::conduct` collects after the run parks, so resuming it unchanged —
3030/// the behaviour before this function existed — silently drops the very
3031/// decision the operator made to unblock it. Re-stripping any block this
3032/// function appended on an earlier resume before re-appending the current
3033/// list (rather than blindly appending again) is what keeps a task resumed
3034/// three times over three answered questions from carrying the same answer
3035/// three times.
3036fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
3037 append_answers(strip_answers_block(old_instruction, task), task)
3038}
3039
3040/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
3041/// answers before handing it to `Runner` — the actual boundary between
3042/// [`choose_starter`]'s routing and the graph, factored out so it is
3043/// assertable without a real repository, git branch, or agent CLI.
3044///
3045/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
3046/// instruction from the reviewed branch's own commit log because there is no
3047/// task statement to speak of for hand-written work, and splicing operator
3048/// answers into that text would contradict the very message it sends
3049/// reviewers ("there is no task statement").
3050fn prepare_instruction(
3051 starter: &Starter,
3052 old_instruction: Option<&str>,
3053 task: &Task,
3054) -> Option<String> {
3055 match starter {
3056 Starter::Start => Some(instruction_for(task)),
3057 Starter::Resume(_) => Some(resumed_instruction(
3058 old_instruction.expect("a resumed run always has a prior instruction"),
3059 task,
3060 )),
3061 Starter::Review(_) => None,
3062 }
3063}
3064
3065/// Persist a transition. A queue write failure is logged rather than fatal: the
3066/// run already happened, and taking the daemon down would only add a lost
3067/// backlog to a full disk.
3068fn record(queue: &Queue, task: &mut Task) {
3069 if let Err(e) = queue.put(task) {
3070 tracing::error!("could not record task {}: {e:#}", task.short());
3071 notices::raise(Notice::error(
3072 "loop:record",
3073 "The loop could not save a task's state; check the disk.",
3074 ));
3075 }
3076}
3077
3078/// Every runnable task, in the order the loop should try them.
3079///
3080/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
3081/// tail exists so that a claim somebody else holds costs the loop the next
3082/// candidate rather than a whole poll interval of idleness.
3083fn runnable(queue: &Queue) -> Vec<Task> {
3084 let mut tasks: Vec<Task> = queue
3085 .list()
3086 .into_iter()
3087 .filter(|t| t.status.runnable())
3088 .collect();
3089 tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
3090 tasks
3091}
3092
3093/// Why a run ended where it did, in one line, for [`Task::last_error`].
3094///
3095/// A stalled run names the seats the quota took out: "out of quota" is not
3096/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
3097/// agent to replace or which plan to top up.
3098///
3099/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
3100/// purpose: unlike `label`'s other callers (an internal log line, an
3101/// already-a-bug fallback message), this string becomes `Task::last_error`
3102/// verbatim, which the phone renders in the same alarm-styled box an
3103/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
3104/// `.err` styling. A bare `verified_noop` there would read exactly like the
3105/// failure this whole feature exists to tell apart from one.
3106fn describe(state: &RunState) -> String {
3107 let mut detail = if state.status == RunStatus::Stalled {
3108 let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
3109 seats.sort_unstable();
3110 seats.dedup();
3111 if seats.is_empty() {
3112 "the judging panel lost its quorum".to_owned()
3113 } else {
3114 format!(
3115 "the judging panel lost its quorum; quota took out {}",
3116 seats.join(", ")
3117 )
3118 }
3119 } else {
3120 format!("run ended {}", state.status.display_label())
3121 };
3122 if let Some(last) = state.events.last() {
3123 detail.push_str(&format!(" ({}: {})", last.node, last.message));
3124 }
3125 detail.push_str(&format!(" [run {}]", state.id));
3126 detail
3127}
3128
3129/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
3130///
3131/// The task file lives in the backlog indefinitely; a diagnostic is an
3132/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
3133/// stay small regardless of how much a gate command or a candidate printed.
3134const DIAGNOSTIC_MAX: usize = 4_000;
3135
3136/// Tail kept from a single failing command's output inside a diagnostic.
3137/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
3138/// pointer for a human deciding whether to go read the full artifact by hand,
3139/// not a replacement for reading it.
3140const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
3141
3142/// Assemble a bounded diagnostic excerpt from a held task's own run, so
3143/// `magi task show` says more than the one-line reason in [`describe`].
3144///
3145/// The one-liner answers "where did the run stop"; this answers "what would a
3146/// human have found opening `artifacts/` by hand" — the point of the whole
3147/// feature is the case that one-liner actively misleads on: a run held as "no
3148/// candidate produced a change" can mean the implementer actually finished
3149/// the task (opened a PR, merged it, tagged a release) and only left a clean
3150/// local worktree behind, which reads as "nothing happened" unless someone
3151/// goes and reads what the agent actually said. `None` when the run carries
3152/// none of the three shapes this recognises — an ordinary run held for
3153/// something not diagnosable from `RunState` alone still explains itself
3154/// through `Task::last_error`.
3155fn diagnostic(state: &RunState) -> Option<String> {
3156 let mut parts: Vec<String> = Vec::new();
3157
3158 // Gate failure: which check(s), and the tail of what each printed.
3159 for o in state.gate.iter().filter(|o| !o.ok()) {
3160 parts.push(format!(
3161 "gate `{}` failed ({:?}):\n{}",
3162 o.command,
3163 o.code,
3164 crate::run::tail(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
3165 ));
3166 }
3167
3168 // The land loop gave up because the fixer declined while checks were
3169 // still red: the message already names them (see `land::run`).
3170 if let Some(last) = state
3171 .events
3172 .iter()
3173 .rev()
3174 .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
3175 {
3176 parts.push(last.message.clone());
3177 }
3178
3179 // No viable candidate: every implementer's own final word, sanitized the
3180 // same way a judge would have read it, so a run that actually finished
3181 // the job does not read as an unexplained failure. A verified no-op is
3182 // called out ahead of its own summary and apart from an ordinary
3183 // failure's `why` — this is the one candidate shape whose diagnostic a
3184 // human is expected to actually judge, not just skim.
3185 if state.viable().is_empty() {
3186 for c in &state.candidates {
3187 if let Some(evidence) = &c.verified_noop {
3188 parts.push(format!(
3189 "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
3190 c.label
3191 ));
3192 } else if !c.summary.trim().is_empty() {
3193 parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
3194 } else if let Some(why) = &c.failed {
3195 parts.push(format!("candidate {}: {why}", c.label));
3196 }
3197 }
3198 }
3199
3200 if parts.is_empty() {
3201 return None;
3202 }
3203 // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
3204 // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
3205 // back slightly over. Leave it enough room to always land under the
3206 // limit.
3207 Some(crate::run::tail(
3208 &parts.join("\n\n"),
3209 DIAGNOSTIC_MAX.saturating_sub(100),
3210 ))
3211}
3212
3213/// Stable lower-case name for a run status, for an internal log line and the
3214/// "graph stopped without reaching a terminal status" bug message in
3215/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
3216/// doc for why that one reads [`RunStatus::display_label`] instead. One
3217/// definition of a status's name, on the type that owns it: this table used
3218/// to live here as a second copy, and a status renamed in one place would
3219/// have gone on reading correctly in the other.
3220fn label(status: RunStatus) -> &'static str {
3221 status.as_str()
3222}
3223
3224/// Parse a merge mode override.
3225fn merge_mode(mode: &str) -> Result<MergeMode> {
3226 match mode {
3227 "none" => Ok(MergeMode::None),
3228 "local" => Ok(MergeMode::Local),
3229 "pr" => Ok(MergeMode::Pr),
3230 other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
3231 }
3232}
3233
3234/// Take the status lock, recovering from a poisoned one.
3235///
3236/// A panic elsewhere must not silently stop the heartbeat: the status is plain
3237/// data, and the worst a poisoned lock can hold is a stale timestamp.
3238fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
3239 mutex
3240 .lock()
3241 .unwrap_or_else(std::sync::PoisonError::into_inner)
3242}
3243
3244#[cfg(test)]
3245mod tests {
3246 use super::*;
3247 use crate::queue::{Source, TaskStatus};
3248 use crate::run::{Candidate, CommandOutcome};
3249 use pretty_assertions::assert_eq;
3250
3251 fn task() -> Task {
3252 Task::new(
3253 "add retries".to_owned(),
3254 "add retries".to_owned(),
3255 PathBuf::from("/repo"),
3256 Source::Human,
3257 )
3258 }
3259
3260 /// A runnable task marked to interrupt, with an id fixed for assertions
3261 /// rather than the random one [`Task::new`] mints.
3262 fn interrupt_task(id: &str) -> Task {
3263 let mut t = task();
3264 t.id = id.to_owned();
3265 t.interrupt = true;
3266 t
3267 }
3268
3269 /// An ordinary runnable task with an id fixed for assertions.
3270 fn task_with_id(id: &str) -> Task {
3271 let mut t = task();
3272 t.id = id.to_owned();
3273 t
3274 }
3275
3276 /// A runnable task marked `--urgent`, with an id fixed for assertions.
3277 fn urgent_task(id: &str) -> Task {
3278 let mut t = task();
3279 t.id = id.to_owned();
3280 t.urgent = true;
3281 t
3282 }
3283
3284 /// The land-resume exemption wins outright, whether or not the candidate
3285 /// also happens to be marked [`Task::urgent`]: a resume's own "must not
3286 /// queue behind anything" guarantee cannot be weaker just because the
3287 /// same task was also filed with `--urgent`.
3288 #[test]
3289 fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
3290 assert_eq!(permit_kind(true, false), PermitKind::None);
3291 assert_eq!(permit_kind(true, true), PermitKind::None);
3292 }
3293
3294 /// The one property this whole feature exists for: `--urgent` draws from
3295 /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
3296 /// ordinary candidate draws from the ordinary pool exactly as before,
3297 /// untouched by the urgent slot's existence.
3298 #[test]
3299 fn permit_kind_separates_urgent_from_ordinary() {
3300 assert_eq!(permit_kind(false, true), PermitKind::Urgent);
3301 assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
3302 }
3303
3304 /// The exact wiring `attempt` runs before minting anything: a config's
3305 /// `min_free_bytes` in, a task-holding reason naming both numbers out.
3306 /// Free space is injected rather than asked of the real disk - the point
3307 /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
3308 /// is deterministic on every machine this test runs on, never dependent
3309 /// on how full the CI runner's own disk happens to be.
3310 #[test]
3311 fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
3312 let cfg = Config::default();
3313 let repo = Path::new("/any/repo/path");
3314
3315 let reason =
3316 disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
3317 assert!(reason.contains("1024"), "{reason}");
3318 assert!(
3319 reason.contains(&cfg.disk.min_free_bytes.to_string()),
3320 "{reason}"
3321 );
3322
3323 assert_eq!(
3324 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
3325 None,
3326 "exactly at the floor is open"
3327 );
3328 assert_eq!(
3329 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
3330 None,
3331 "comfortably above the floor is open"
3332 );
3333 }
3334
3335 #[test]
3336 fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
3337 let mut cfg = Config::default();
3338 cfg.disk.min_free_bytes = 0;
3339 let repo = Path::new("/any/repo/path");
3340 assert_eq!(
3341 disk_gate_with(repo, &cfg, |_| Ok(0)),
3342 None,
3343 "a zero floor never measures at all"
3344 );
3345 }
3346
3347 #[test]
3348 fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
3349 let cfg = Config::default();
3350 let repo = Path::new("/any/repo/path");
3351 let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
3352 .expect("a measurement failure must close the gate, not open it");
3353 assert!(reason.contains("could not measure"), "{reason}");
3354 }
3355
3356 #[test]
3357 fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
3358 let ordinary = task();
3359 let next = advance_interrupt(
3360 Interrupt::Idle,
3361 std::slice::from_ref(&ordinary.id),
3362 std::slice::from_ref(&ordinary),
3363 );
3364 assert_eq!(next, Interrupt::Idle);
3365 }
3366
3367 #[test]
3368 fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
3369 // Nothing to interrupt - this is just an ordinary candidate, and the
3370 // loop's normal dispatch will pick it up like any other.
3371 let marked = interrupt_task("marked");
3372 let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
3373 assert_eq!(next, Interrupt::Idle);
3374 }
3375
3376 #[test]
3377 fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
3378 let marked = interrupt_task("marked");
3379 let next = advance_interrupt(
3380 Interrupt::Idle,
3381 &["running".to_owned()],
3382 std::slice::from_ref(&marked),
3383 );
3384 assert_eq!(
3385 next,
3386 Interrupt::Parking {
3387 parked: vec!["running".to_owned()],
3388 interrupt_task: "marked".to_owned(),
3389 }
3390 );
3391 }
3392
3393 /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
3394 /// one run can be in flight when a task becomes runnable and marked.
3395 /// Parking all of them would mean `Resuming` later has more than one id
3396 /// to release back to ordinary dispatch, which cannot be made safe
3397 /// against that same setting's own extra concurrency slots letting two
3398 /// of them start together - see `advance_interrupt`'s own `Idle` branch.
3399 /// The simplification the task's own constraints ask for: do not begin
3400 /// a sequence at all until the herd settles back to exactly one.
3401 #[test]
3402 fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
3403 let marked = interrupt_task("marked");
3404
3405 let two = advance_interrupt(
3406 Interrupt::Idle,
3407 &["a".to_owned(), "b".to_owned()],
3408 std::slice::from_ref(&marked),
3409 );
3410 assert_eq!(two, Interrupt::Idle);
3411
3412 let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
3413 assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
3414 }
3415
3416 #[test]
3417 fn parking_holds_until_every_parked_id_has_actually_left_flight() {
3418 let state = Interrupt::Parking {
3419 parked: vec!["running".to_owned()],
3420 interrupt_task: "marked".to_owned(),
3421 };
3422 // Still in flight: no change.
3423 let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
3424 assert_eq!(still_going, state);
3425
3426 // Left flight, but the interrupt task has not been dispatched yet on
3427 // this tick - stays `Parking` so `interrupt_gate` can let it through,
3428 // as long as it is still runnable.
3429 let stopped_but_not_yet_dispatched =
3430 advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
3431 assert_eq!(stopped_but_not_yet_dispatched, state);
3432
3433 // Left flight, and the interrupt task is now in flight itself.
3434 let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
3435 assert_eq!(
3436 dispatched,
3437 Interrupt::Running {
3438 parked: vec!["running".to_owned()],
3439 interrupt_task: "marked".to_owned(),
3440 }
3441 );
3442 }
3443
3444 #[test]
3445 fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
3446 let state = Interrupt::Running {
3447 parked: vec!["running".to_owned()],
3448 interrupt_task: "marked".to_owned(),
3449 };
3450 let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
3451 assert_eq!(still_running, state);
3452
3453 // Whatever it ended as - merged, failed, held - is not this
3454 // function's concern: leaving flight is the only trigger, driven
3455 // straight off the same in-flight list `poll` already reaps. It does
3456 // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
3457 // why that would let an unrelated task start ahead of, or alongside,
3458 // the guaranteed resume.
3459 let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
3460 assert_eq!(
3461 ended,
3462 Interrupt::Resuming {
3463 parked: vec!["running".to_owned()]
3464 }
3465 );
3466 }
3467
3468 #[test]
3469 fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
3470 let state = Interrupt::Resuming {
3471 parked: vec!["running".to_owned()],
3472 };
3473 let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
3474 assert_eq!(still_waiting, state);
3475
3476 let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
3477 assert_eq!(dispatched, Interrupt::Idle);
3478 }
3479
3480 /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
3481 /// or otherwise moved on by an operator with no claim standing in the
3482 /// way - must not wedge the sequence (and so the whole loop's dispatch,
3483 /// via `interrupt_gate`) waiting forever for a dispatch that can never
3484 /// come. The parked run still gets its resume.
3485 #[test]
3486 fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
3487 {
3488 let state = Interrupt::Parking {
3489 parked: vec!["running".to_owned()],
3490 interrupt_task: "marked".to_owned(),
3491 };
3492 // `marked` has been held/blocked/deleted since the sequence began:
3493 // it no longer appears in `runnable` at all.
3494 let next = advance_interrupt(state, &[], &[]);
3495 assert_eq!(
3496 next,
3497 Interrupt::Resuming {
3498 parked: vec!["running".to_owned()]
3499 },
3500 "abandoning the interrupt must not abandon the resume it owes"
3501 );
3502 }
3503
3504 /// The same abandonment, one step later: `Resuming` itself must not wait
3505 /// forever for a parked task that has since become unrunnable.
3506 #[test]
3507 fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
3508 let state = Interrupt::Resuming {
3509 parked: vec!["running".to_owned()],
3510 };
3511 let next = advance_interrupt(state, &[], &[]);
3512 assert_eq!(
3513 next,
3514 Interrupt::Idle,
3515 "nothing is left to wait for; the loop must not stay wedged"
3516 );
3517 }
3518
3519 #[test]
3520 fn disabled_by_config_the_sequence_can_never_leave_idle() {
3521 let marked = interrupt_task("marked");
3522 let next = advance_interrupt_tick(
3523 false,
3524 Interrupt::Idle,
3525 &["running".to_owned()],
3526 std::slice::from_ref(&marked),
3527 );
3528 assert_eq!(
3529 next,
3530 Interrupt::Idle,
3531 "an unmarked, unconfigured daemon must behave exactly as before"
3532 );
3533 }
3534
3535 #[test]
3536 fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
3537 let state = Interrupt::Parking {
3538 parked: vec!["running".to_owned()],
3539 interrupt_task: "marked".to_owned(),
3540 };
3541 let candidates = vec![interrupt_task("marked"), task()];
3542 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
3543 assert!(
3544 allowed.is_empty(),
3545 "nothing may dispatch - not even the interrupt task itself - \
3546 until the parked run has actually stopped"
3547 );
3548 }
3549
3550 /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
3551 /// grow a special case for it: an urgent candidate that is not the
3552 /// interrupt task withholds exactly like an ordinary one for as long as
3553 /// the parked run it is racing has not actually left flight. A version
3554 /// of this feature once bypassed the gate for urgent candidates, on the
3555 /// theory that a genuinely separate concurrency lane could not collide
3556 /// with 75dd's own; it could, and did - the bypassed task dispatched
3557 /// alongside a run 75dd's own state machine had only *asked* to park,
3558 /// not yet confirmed gone, which is exactly the second run
3559 /// `Interrupt::Parking`'s own doc says must never happen. There is no
3560 /// tick during Parking/Running/Resuming where letting an extra
3561 /// candidate through is safe, urgent or not - the parked run may still
3562 /// be genuinely mid-call.
3563 #[test]
3564 fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
3565 for state in [
3566 Interrupt::Parking {
3567 parked: vec!["running".to_owned()],
3568 interrupt_task: "marked".to_owned(),
3569 },
3570 Interrupt::Running {
3571 parked: vec!["running".to_owned()],
3572 interrupt_task: "marked".to_owned(),
3573 },
3574 Interrupt::Resuming {
3575 parked: vec!["running".to_owned()],
3576 },
3577 ] {
3578 let candidates = vec![
3579 interrupt_task("marked"),
3580 urgent_task("hot"),
3581 task_with_id("ordinary"),
3582 ];
3583 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
3584 assert!(
3585 !allowed.iter().any(|t| t.id == "hot"),
3586 "an urgent candidate must wait out the same gate as anything \
3587 else while the run it would run alongside has not actually \
3588 left flight, for state {state:?}: {allowed:?}"
3589 );
3590 }
3591 }
3592
3593 /// The one case where marking a task `--urgent` and `interrupt` at once
3594 /// is not redundant: once the interrupt sequence's own guaranteed
3595 /// resume/dispatch actually admits the task, it is unaffected by also
3596 /// carrying `urgent` - `interrupt_gate` decides purely on identity,
3597 /// never on the urgent flag.
3598 #[test]
3599 fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
3600 let state = Interrupt::Resuming {
3601 parked: vec!["hot".to_owned()],
3602 };
3603 let candidates = vec![urgent_task("hot"), task()];
3604 let allowed = interrupt_gate(&state, &[], candidates);
3605 assert_eq!(
3606 allowed.iter().filter(|t| t.id == "hot").count(),
3607 1,
3608 "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
3609 );
3610 }
3611
3612 #[test]
3613 fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
3614 let state = Interrupt::Parking {
3615 parked: vec!["running".to_owned()],
3616 interrupt_task: "marked".to_owned(),
3617 };
3618 let other = task();
3619 let candidates = vec![interrupt_task("marked"), other.clone()];
3620 let allowed = interrupt_gate(&state, &[], candidates);
3621 assert_eq!(allowed.len(), 1);
3622 assert_eq!(allowed[0].id, "marked");
3623 }
3624
3625 #[test]
3626 fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
3627 let state = Interrupt::Running {
3628 parked: vec!["running".to_owned()],
3629 interrupt_task: "marked".to_owned(),
3630 };
3631 let candidates = vec![task(), task()];
3632 let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
3633 assert!(allowed.is_empty());
3634 }
3635
3636 /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
3637 /// sequence began (only reachable above the default
3638 /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
3639 /// never both in the same tick, which is what "exactly one resume, no
3640 /// simultaneous run" actually requires structurally rather than by
3641 /// coincidence of how many ordinary slots happen to be free.
3642 #[test]
3643 fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
3644 let state = Interrupt::Resuming {
3645 parked: vec!["a".to_owned(), "c".to_owned()],
3646 };
3647 let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
3648 let allowed = interrupt_gate(&state, &[], candidates);
3649 assert_eq!(
3650 allowed.len(),
3651 1,
3652 "at most one candidate may be offered while resuming: {allowed:?}"
3653 );
3654 assert_eq!(allowed[0].id, "a");
3655 }
3656
3657 #[test]
3658 fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
3659 let state = Interrupt::Resuming {
3660 parked: vec!["a".to_owned()],
3661 };
3662 let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
3663 assert!(allowed.is_empty());
3664 }
3665
3666 /// The invariant the completion criteria ask for by name: across a whole
3667 /// simulated sequence, there is never a tick where the gate would let
3668 /// through both the parked run's resume and the interrupt task, and
3669 /// exactly one candidate resumes the instant the interrupt task's run
3670 /// ends - never zero, never more than one.
3671 #[test]
3672 fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
3673 let running = task(); // id: whatever `Task::new` minted
3674 let marked = interrupt_task("marked");
3675
3676 let mut state = Interrupt::Idle;
3677 // Tick 1: `running` is in flight, `marked` becomes runnable.
3678 let in_flight = vec![running.id.clone()];
3679 state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
3680 let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
3681 assert!(gated.is_empty(), "still waiting on `running` to park");
3682
3683 // Tick 2: `running` parked and left flight; nothing dispatched yet.
3684 state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
3685 let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
3686 assert_eq!(
3687 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
3688 vec!["marked"],
3689 "only the interrupt task may be offered to the dispatcher now"
3690 );
3691
3692 // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
3693 state = advance_interrupt_tick(
3694 true,
3695 state,
3696 &["marked".to_owned()],
3697 std::slice::from_ref(&running),
3698 );
3699 let gated = interrupt_gate(
3700 &state,
3701 &["marked".to_owned()],
3702 vec![marked.clone(), running.clone()],
3703 );
3704 assert!(
3705 gated.is_empty(),
3706 "the parked run must not be offered back while the interrupt \
3707 task is still running"
3708 );
3709
3710 // Tick 4: `marked`'s run reached a terminal status and left flight.
3711 // A higher-priority ordinary task `other` is also runnable now - it
3712 // must not be let through instead of, or alongside, `running`.
3713 let other = task_with_id("other");
3714 state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
3715 assert_eq!(
3716 state,
3717 Interrupt::Resuming {
3718 parked: vec![running.id.clone()]
3719 }
3720 );
3721 let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
3722 assert_eq!(
3723 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
3724 vec![running.id.as_str()],
3725 "exactly the parked run resumes - not the unrelated task, even \
3726 though it was offered first"
3727 );
3728
3729 // Tick 5: `running` is now in flight (dispatched from tick 4's
3730 // gate). Only now does the sequence end and ordinary dispatch fully
3731 // resume.
3732 state = advance_interrupt_tick(
3733 true,
3734 state,
3735 std::slice::from_ref(&running.id),
3736 std::slice::from_ref(&other),
3737 );
3738 assert_eq!(state, Interrupt::Idle);
3739 let gated = interrupt_gate(
3740 &state,
3741 std::slice::from_ref(&running.id),
3742 vec![other.clone()],
3743 );
3744 assert_eq!(
3745 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
3746 vec![other.id.as_str()],
3747 "ordinary dispatch is unrestricted again"
3748 );
3749 }
3750
3751 #[test]
3752 fn every_run_status_settles_the_task_it_came_from() {
3753 // run status, resulting task status, attempts still standing after one
3754 let table = [
3755 (RunStatus::Merged, TaskStatus::Done, 1),
3756 (RunStatus::Ready, TaskStatus::Done, 1),
3757 (RunStatus::Stalled, TaskStatus::Failed, 0),
3758 (RunStatus::Blocked, TaskStatus::Failed, 1),
3759 (RunStatus::Failed, TaskStatus::Failed, 1),
3760 (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
3761 (RunStatus::Prep, TaskStatus::Failed, 1),
3762 (RunStatus::Implementing, TaskStatus::Failed, 1),
3763 (RunStatus::Judging, TaskStatus::Failed, 1),
3764 (RunStatus::Deliberating, TaskStatus::Failed, 1),
3765 (RunStatus::Voting, TaskStatus::Failed, 1),
3766 (RunStatus::Reviewing, TaskStatus::Failed, 1),
3767 (RunStatus::Gating, TaskStatus::Failed, 1),
3768 ];
3769 for (run, want, attempts) in table {
3770 let mut t = task();
3771 t.start("20260902-000000-aaaa".to_owned());
3772 settle(
3773 &mut t,
3774 Verdict {
3775 status: run,
3776 left_pr: false,
3777 parked: false,
3778 quota_hit: matches!(run, RunStatus::Stalled),
3779 no_viable_candidates: false,
3780 },
3781 "why",
3782 2,
3783 );
3784 assert_eq!(t.status, want, "task status after {}", label(run));
3785 assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
3786 }
3787 }
3788
3789 #[test]
3790 fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
3791 let mut stalled = task();
3792 stalled.start("20260902-000000-aaaa".to_owned());
3793 settle(
3794 &mut stalled,
3795 Verdict {
3796 status: RunStatus::Stalled,
3797 left_pr: false,
3798 parked: false,
3799 quota_hit: true,
3800 no_viable_candidates: false,
3801 },
3802 "quota",
3803 1,
3804 );
3805 assert_eq!(stalled.attempts, 0);
3806 assert!(
3807 stalled.status.runnable(),
3808 "a machine problem must leave the task in line"
3809 );
3810
3811 let mut blocked = task();
3812 blocked.start("20260902-000000-aaaa".to_owned());
3813 settle(
3814 &mut blocked,
3815 Verdict {
3816 status: RunStatus::Blocked,
3817 left_pr: false,
3818 parked: false,
3819 quota_hit: false,
3820 no_viable_candidates: false,
3821 },
3822 "findings open",
3823 1,
3824 );
3825 assert_eq!(blocked.attempts, 1);
3826 assert_eq!(
3827 blocked.status,
3828 TaskStatus::Held,
3829 "the last attempt hands the task to a human"
3830 );
3831 }
3832
3833 #[test]
3834 fn a_run_that_opened_a_pull_request_is_never_re_competed() {
3835 // Attempts to spare: without the pull request this task would go
3836 // straight back in line and run the whole competition again.
3837 let mut delivered = task();
3838 delivered.start("20260903-080619-01c2".to_owned());
3839 settle(
3840 &mut delivered,
3841 Verdict {
3842 status: RunStatus::Blocked,
3843 left_pr: true,
3844 parked: false,
3845 quota_hit: false,
3846 no_viable_candidates: false,
3847 },
3848 "no check status",
3849 4,
3850 );
3851 assert_eq!(
3852 delivered.status,
3853 TaskStatus::Held,
3854 "a pull request waiting on CI or a person is not a retryable failure"
3855 );
3856 assert!(
3857 !delivered.status.runnable(),
3858 "the loop must not pick this task up again"
3859 );
3860 assert_eq!(
3861 delivered.last_error.as_deref(),
3862 Some("no check status"),
3863 "the operator needs to be told what the gate was waiting for"
3864 );
3865
3866 // The same status without a pull request is a plain failure, and with
3867 // attempts left it is retried.
3868 let mut empty_handed = task();
3869 empty_handed.start("20260903-080619-01c2".to_owned());
3870 settle(
3871 &mut empty_handed,
3872 Verdict {
3873 status: RunStatus::Blocked,
3874 left_pr: false,
3875 parked: false,
3876 quota_hit: false,
3877 no_viable_candidates: false,
3878 },
3879 "findings open",
3880 4,
3881 );
3882 assert_eq!(empty_handed.status, TaskStatus::Failed);
3883 assert!(empty_handed.status.runnable());
3884 }
3885
3886 #[test]
3887 fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
3888 // Every candidate agreed, with evidence, that nothing belonged in the
3889 // worktree. That is not a confirmed success to close automatically -
3890 // a human still has to check the claim - and it is not an ordinary
3891 // failure either, so this settles exactly like a pull request nobody
3892 // merged yet: `Held`, same as `Blocked` with a PR.
3893 let mut noop = task();
3894 noop.start("20260912-131304-391f".to_owned());
3895 settle(
3896 &mut noop,
3897 Verdict {
3898 status: RunStatus::VerifiedNoop,
3899 left_pr: false,
3900 parked: false,
3901 quota_hit: false,
3902 no_viable_candidates: true,
3903 },
3904 "candidate A: already fixed by b32cfc4, on main",
3905 4,
3906 );
3907 assert_eq!(
3908 noop.status,
3909 TaskStatus::Held,
3910 "an unverified claim is a request for a human, not a failure"
3911 );
3912 assert!(
3913 !noop.status.runnable(),
3914 "the loop must not requeue this on the same unverified claim"
3915 );
3916 // `Task::release` resets attempts to zero the moment a human looks at
3917 // the evidence and lets it run again, so it does not matter here
3918 // whether the one attempt already spent stays spent - what matters is
3919 // that nothing retries this task unattended in the meantime.
3920 assert_eq!(noop.attempts, 1);
3921 }
3922
3923 #[test]
3924 fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
3925 // Parking is the operator asking for the process back - to replace the
3926 // binary, most of all. The run's work is intact on disk, so this is
3927 // not a failed attempt, and charging for it would mean a few upgrades
3928 // could exhaust a budget meant for agents that misbehaved.
3929 let mut parked = task();
3930 parked.start("20260903-183634-2d98".to_owned());
3931 settle(
3932 &mut parked,
3933 Verdict {
3934 status: RunStatus::Implementing,
3935 left_pr: false,
3936 quota_hit: false,
3937 parked: true,
3938 no_viable_candidates: false,
3939 },
3940 "parked after `implementing`",
3941 2,
3942 );
3943 assert_eq!(parked.attempts, 0, "a park is refunded");
3944 assert!(
3945 parked.status.runnable(),
3946 "and the task stays in line so the next loop resumes its run"
3947 );
3948 assert_eq!(
3949 parked.last_error.as_deref(),
3950 Some("parked after `implementing`"),
3951 "the card says where it stopped"
3952 );
3953
3954 // Without the park flag the same non-terminal status is what it always
3955 // was: `execute` returning mid-flight, which is a bug and spends an
3956 // attempt so a task cannot loop on it forever.
3957 let mut broken = task();
3958 broken.start("20260903-183634-2d98".to_owned());
3959 settle(
3960 &mut broken,
3961 Verdict {
3962 status: RunStatus::Implementing,
3963 left_pr: false,
3964 quota_hit: false,
3965 parked: false,
3966 no_viable_candidates: false,
3967 },
3968 "returned mid-flight",
3969 2,
3970 );
3971 assert_eq!(broken.attempts, 1);
3972 }
3973
3974 #[test]
3975 fn only_a_rate_limit_buys_the_task_its_attempt_back() {
3976 // Run e633: quorum lost because two judges answered with the wrong
3977 // JSON shape, `quota: []`. Refunding that takes the bound off the
3978 // retry loop, and each retry pays for a fresh hour-long implement
3979 // wave before it can fail the same way.
3980 let mut flaky = task();
3981 flaky.start("20260903-123023-e633".to_owned());
3982 settle(
3983 &mut flaky,
3984 Verdict {
3985 status: RunStatus::Stalled,
3986 left_pr: false,
3987 parked: false,
3988 quota_hit: false,
3989 no_viable_candidates: false,
3990 },
3991 "verdict rests on 1 of 3 judges",
3992 2,
3993 );
3994 assert_eq!(
3995 flaky.attempts, 1,
3996 "flakiness spends an attempt, so `max_attempts` still bounds it"
3997 );
3998 assert!(flaky.status.runnable(), "and it is still worth retrying");
3999
4000 // The same status, lost to a rate limit, is the machine's fault.
4001 let mut limited = task();
4002 limited.start("20260903-123023-e633".to_owned());
4003 settle(
4004 &mut limited,
4005 Verdict {
4006 status: RunStatus::Stalled,
4007 left_pr: false,
4008 parked: false,
4009 quota_hit: true,
4010 no_viable_candidates: false,
4011 },
4012 "judge-2, judge-3 out of quota",
4013 2,
4014 );
4015 assert_eq!(limited.attempts, 0, "a quota window is refunded");
4016 assert!(limited.status.runnable());
4017
4018 // And the bound really binds: a task that keeps stalling on flakiness
4019 // reaches a human instead of running the roster forever.
4020 let mut worn = task();
4021 for _ in 0..2 {
4022 worn.release();
4023 }
4024 worn.start("20260903-123023-e633".to_owned());
4025 worn.attempts = 2;
4026 settle(
4027 &mut worn,
4028 Verdict {
4029 status: RunStatus::Stalled,
4030 left_pr: false,
4031 parked: false,
4032 quota_hit: false,
4033 no_viable_candidates: false,
4034 },
4035 "no quorum again",
4036 2,
4037 );
4038 assert_eq!(worn.status, TaskStatus::Held);
4039 assert!(!worn.status.runnable());
4040 }
4041
4042 #[test]
4043 fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
4044 // The implement wave loses every seat to the same rate limit and
4045 // `after_implement` bails with nothing viable, which surfaces as
4046 // `Failed` rather than `Stalled`. That is the same machine fact the
4047 // `Stalled`-quota row already refunds, and must be refunded the same
4048 // way, or a quota outage quietly holds every task it touches instead
4049 // of leaving them in line for the reset.
4050 let mut wiped_out = task();
4051 wiped_out.start("20260907-025000-a1b2".to_owned());
4052 settle(
4053 &mut wiped_out,
4054 Verdict {
4055 status: RunStatus::Failed,
4056 left_pr: false,
4057 parked: false,
4058 quota_hit: true,
4059 no_viable_candidates: true,
4060 },
4061 "no candidate produced a change; nothing to judge",
4062 2,
4063 );
4064 assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
4065 assert!(
4066 wiped_out.status.runnable(),
4067 "a machine problem must leave the task in line"
4068 );
4069
4070 // This is the exemption that must stay narrow: a candidate that did
4071 // produce a change, and then failed for some other reason, still
4072 // spends the attempt even though a seat elsewhere hit its quota.
4073 // Otherwise every ordinary failure that happens to share a run with
4074 // an unrelated rate limit would be refunded for free.
4075 let mut partial_progress = task();
4076 partial_progress.start("20260907-025500-c3d4".to_owned());
4077 settle(
4078 &mut partial_progress,
4079 Verdict {
4080 status: RunStatus::Failed,
4081 left_pr: false,
4082 parked: false,
4083 quota_hit: true,
4084 no_viable_candidates: false,
4085 },
4086 "gate failed on the winning candidate",
4087 2,
4088 );
4089 assert_eq!(
4090 partial_progress.attempts, 1,
4091 "a candidate that actually produced a change spends the attempt \
4092 even though some other seat hit its quota"
4093 );
4094 assert!(partial_progress.status.runnable());
4095 }
4096
4097 #[test]
4098 fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
4099 // `reclaim` builds its own `Verdict` from a `RunState` it loads off
4100 // disk, and that construction must reach the same conclusion as the
4101 // one `attempt` builds from a live run, or a crash at exactly the
4102 // wrong moment gives a recovered task a different policy than one a
4103 // daemon finished settling itself.
4104 let mut t = task();
4105 t.start("20260907-025000-a1b2".to_owned());
4106 let mut state = run_state(RunStatus::Failed);
4107 state.quota.push(QuotaLoss {
4108 seat: "cand-a".to_owned(),
4109 node: "implement".to_owned(),
4110 at: Timestamp::now(),
4111 reset: None,
4112 });
4113 assert!(
4114 state.viable().is_empty(),
4115 "no candidate was added, so nothing is viable"
4116 );
4117 reclaim(&mut t, Some(state), 2);
4118 assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
4119 assert!(t.status.runnable());
4120 }
4121
4122 #[test]
4123 fn a_held_task_is_never_offered_to_the_loop() {
4124 let dir = tempfile::tempdir().unwrap();
4125 let queue = Queue::at(dir.path().to_path_buf());
4126 for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
4127 let mut t = task();
4128 t.id = format!("2026090{n}-000000-000{n}");
4129 t.priority = priority;
4130 queue.put(&mut t).unwrap();
4131 }
4132 let mut held = task();
4133 held.id = "20260909-000000-9999".to_owned();
4134 held.priority = 99;
4135 held.hold_machine(None);
4136 queue.put(&mut held).unwrap();
4137
4138 let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
4139 assert_eq!(order.len(), 3);
4140 assert!(!order.contains(&held.id));
4141 assert_eq!(
4142 order.first().cloned(),
4143 queue.next_runnable().map(|t| t.id),
4144 "the loop's first candidate is exactly what the queue offers"
4145 );
4146 assert_eq!(
4147 order,
4148 vec![
4149 "20260902-000000-0002".to_owned(),
4150 "20260903-000000-0003".to_owned(),
4151 "20260901-000000-0001".to_owned(),
4152 ],
4153 "priority first, then oldest, so nothing starves"
4154 );
4155 }
4156
4157 #[test]
4158 fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
4159 let dir = tempfile::tempdir().unwrap();
4160 let queue = Queue::at(dir.path().to_path_buf());
4161 let mut old = task();
4162 old.id = "20260101-000000-old0".to_owned();
4163 queue.put(&mut old).unwrap();
4164 let mut fresh = task();
4165 fresh.id = "20260101-000000-new0".to_owned();
4166 queue.put(&mut fresh).unwrap();
4167
4168 // No parseable pid at all, so age is the only signal there is to
4169 // check - unlike a real `Queue::claim`, which always names a real,
4170 // and therefore alive, pid this test cannot fake as dead.
4171 std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
4172 std::thread::sleep(Duration::from_millis(60));
4173 let live = queue.claim(&fresh.id).unwrap();
4174
4175 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
4176 assert_eq!(swept, vec![old.id.clone()]);
4177 assert!(
4178 queue.claim(&old.id).is_ok(),
4179 "an unparseable lock older than the threshold is swept"
4180 );
4181 assert!(
4182 queue.claim(&fresh.id).is_err(),
4183 "a live pid protects its lock regardless of age"
4184 );
4185 drop(live);
4186 }
4187
4188 #[test]
4189 fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
4190 // The regression this guards: `sweep` now runs concurrently with
4191 // every attempt this daemon itself has spawned (see
4192 // `InFlightGuard`), not only between them the way a single
4193 // sequential loop once did. A run that legitimately outlives
4194 // `older_than` still has this very process's own live pid sitting in
4195 // its own lock file on every later sweep, and deciding by age alone
4196 // would delete that still-valid claim out from under the attempt
4197 // that holds it - which `reclaim_orphaned_running` would then read
4198 // as abandoned and hand to a second, competing attempt.
4199 let dir = tempfile::tempdir().unwrap();
4200 let queue = Queue::at(dir.path().to_path_buf());
4201 let mut t = task();
4202 t.id = "20260101-000000-live".to_owned();
4203 queue.put(&mut t).unwrap();
4204
4205 let claim = queue.claim(&t.id).unwrap();
4206 std::thread::sleep(Duration::from_millis(60));
4207
4208 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
4209 assert!(
4210 swept.is_empty(),
4211 "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
4212 );
4213 assert!(
4214 queue.claim(&t.id).is_err(),
4215 "the lock still protects its task"
4216 );
4217 drop(claim);
4218 }
4219
4220 /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
4221 /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
4222 fn injected_dead_pid() -> u32 {
4223 std::process::id().checked_add(1).unwrap_or(1)
4224 }
4225
4226 #[test]
4227 fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
4228 let dir = tempfile::tempdir().unwrap();
4229 let queue = Queue::at(dir.path().to_path_buf());
4230 let mut t = task();
4231 t.id = "20260101-000000-dead".to_owned();
4232 queue.put(&mut t).unwrap();
4233 let dead_pid = injected_dead_pid();
4234
4235 // Written directly rather than through `Queue::claim`, which would
4236 // stamp this test process's own very much alive pid and defeat the
4237 // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
4238 // like moments after it died, not six hours later.
4239 std::fs::write(
4240 dir.path().join(format!("{}.lock", t.id)),
4241 dead_pid.to_string(),
4242 )
4243 .unwrap();
4244
4245 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
4246 pid != dead_pid
4247 });
4248 assert_eq!(
4249 swept,
4250 vec![t.id.clone()],
4251 "a dead owner is reclaimed immediately, not after STALE_CLAIM"
4252 );
4253 assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
4254 }
4255
4256 #[test]
4257 fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
4258 let dir = tempfile::tempdir().unwrap();
4259 let queue = Queue::at(dir.path().to_path_buf());
4260 let mut t = task();
4261 t.id = "20260101-000000-late".to_owned();
4262 queue.put(&mut t).unwrap();
4263 let dead_pid = injected_dead_pid();
4264
4265 // Tick one, standing in for the sweep `poll` already runs at
4266 // startup: nothing to find yet.
4267 assert!(
4268 sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
4269 "nothing has claimed the task yet"
4270 );
4271
4272 // A second daemon claims the task and dies before it ever writes
4273 // `running`, well after this loop's own startup sweep already ran.
4274 std::fs::write(
4275 dir.path().join(format!("{}.lock", t.id)),
4276 dead_pid.to_string(),
4277 )
4278 .unwrap();
4279
4280 // Tick two, standing in for a poll long into this daemon's uptime:
4281 // the same function, called again, notices what only just appeared -
4282 // proving the sweep is not a one-shot startup check.
4283 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
4284 pid != dead_pid
4285 });
4286 assert_eq!(swept, vec![t.id.clone()]);
4287 }
4288
4289 #[test]
4290 fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
4291 // `reclaim_orphaned_running` looks up the task's last run, which
4292 // touches `run::home()`; the first call anywhere in this binary wins,
4293 // so this is a no-op if another test already pinned one, and either
4294 // way the run id below is never written under it.
4295 crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4296 let dir = tempfile::tempdir().unwrap();
4297 let queue = Queue::at(dir.path().to_path_buf());
4298 let mut t = task();
4299 t.id = "20260101-000000-crsh".to_owned();
4300 t.status = TaskStatus::Running;
4301 t.attempts = 1;
4302 // No `run.json` behind this id: standing in for a run this test does
4303 // not need to make readable, since the point is the lock, not the
4304 // recovery table `reclaim` already has its own tests for.
4305 t.runs.push("20260904-000000-4043".to_owned());
4306 queue.put(&mut t).unwrap();
4307 let dead_pid = injected_dead_pid();
4308
4309 // The crashed daemon's own claim, naming a pid nothing on the
4310 // machine holds anymore.
4311 std::fs::write(
4312 dir.path().join(format!("{}.lock", t.id)),
4313 dead_pid.to_string(),
4314 )
4315 .unwrap();
4316
4317 // Before the lock is swept the task looks claimed, and
4318 // `reclaim_orphaned_running` must leave it alone - this is exactly
4319 // the bug: a `running` task stranded behind a dead daemon's lock,
4320 // invisible to the claim-as-proof check because the lock outlived
4321 // the process that wrote it.
4322 assert!(reclaim_orphaned_running(&queue, 2).is_empty());
4323 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
4324
4325 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
4326 pid != dead_pid
4327 });
4328 assert_eq!(swept, vec![t.id.clone()]);
4329
4330 let reclaimed = reclaim_orphaned_running(&queue, 2);
4331 assert_eq!(reclaimed, vec![t.id.clone()]);
4332 let after = queue.get(&t.id).unwrap();
4333 assert_eq!(
4334 after.status,
4335 TaskStatus::Held,
4336 "no run.json to recover from, so a human is asked"
4337 );
4338 assert_eq!(
4339 after.runs,
4340 vec!["20260904-000000-4043".to_owned()],
4341 "the crashed run's id is kept as evidence, not discarded"
4342 );
4343 }
4344
4345 #[test]
4346 fn a_lock_is_kept_when_the_process_query_is_unavailable() {
4347 let dir = tempfile::tempdir().unwrap();
4348 let queue = Queue::at(dir.path().to_path_buf());
4349 let mut t = task();
4350 t.id = "20260101-000000-unknown".to_owned();
4351 queue.put(&mut t).unwrap();
4352 let dead_pid = injected_dead_pid();
4353 std::fs::write(
4354 dir.path().join(format!("{}.lock", t.id)),
4355 dead_pid.to_string(),
4356 )
4357 .unwrap();
4358
4359 let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
4360 assert!(swept.is_empty(), "an unknown pid must keep its lock");
4361 assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
4362 }
4363
4364 fn run_state(status: RunStatus) -> RunState {
4365 let mut state = RunState::new(
4366 PathBuf::from("/repo"),
4367 "main".to_owned(),
4368 "abc1234def".to_owned(),
4369 "add retries".to_owned(),
4370 Config::default(),
4371 );
4372 state.status = status;
4373 state
4374 }
4375
4376 fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
4377 Candidate {
4378 index: 0,
4379 label,
4380 agent: "claude".to_owned(),
4381 branch: format!("magi/x/{label}"),
4382 worktree: PathBuf::from("/repo"),
4383 summary: summary.to_owned(),
4384 stat: String::new(),
4385 files: 0,
4386 commits: usize::from(!empty),
4387 empty,
4388 failed: failed.map(str::to_owned),
4389 verified_noop: None,
4390 duration_ms: 0,
4391 folded: false,
4392 }
4393 }
4394
4395 #[test]
4396 fn diagnostic_names_the_failing_gate_checks_and_their_output() {
4397 let mut state = run_state(RunStatus::Blocked);
4398 state.gate = vec![
4399 CommandOutcome {
4400 command: "cargo make check".to_owned(),
4401 code: Some(0),
4402 output_tail: "ok".to_owned(),
4403 duration_ms: 0,
4404 resource_blocked: false,
4405 },
4406 CommandOutcome {
4407 command: "cargo test".to_owned(),
4408 code: Some(101),
4409 output_tail: "thread 'x' panicked: assertion failed".to_owned(),
4410 duration_ms: 0,
4411 resource_blocked: false,
4412 },
4413 ];
4414 let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
4415 assert!(d.contains("cargo test"), "{d}");
4416 assert!(
4417 !d.contains("cargo make check"),
4418 "a passing check is not a diagnostic: {d}"
4419 );
4420 assert!(d.contains("assertion failed"), "{d}");
4421 }
4422
4423 #[test]
4424 fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
4425 let mut state = run_state(RunStatus::Blocked);
4426 state.event(
4427 "land",
4428 "stopped: the fixer produced no commit while 2 check(s) were failing \
4429 (build, lint); stopping instead of looping on an unchanged tree",
4430 );
4431 let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
4432 assert!(d.contains("build"), "{d}");
4433 assert!(d.contains("lint"), "{d}");
4434 assert!(d.contains("fixer produced no commit"), "{d}");
4435 }
4436
4437 #[test]
4438 fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
4439 // `describe`'s output becomes `Task::last_error` verbatim, and the
4440 // phone renders that in the same alarm-styled box an ordinary
4441 // failure gets. A bare `verified_noop` there would read exactly like
4442 // the failure this status exists to be told apart from.
4443 let state = run_state(RunStatus::VerifiedNoop);
4444 let d = describe(&state);
4445 assert!(
4446 d.contains("agent-verified no-op"),
4447 "expected the display label, not the wire spelling: {d}"
4448 );
4449 assert!(!d.contains("verified_noop"), "{d}");
4450 }
4451
4452 #[test]
4453 fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
4454 // The whole point of the feature: a run held as "no candidate produced
4455 // a change" can mean the implementer actually finished the task and
4456 // only left a clean local tree behind - see AGENTS.md on this exact
4457 // failure mode. The diagnostic has to carry what the agent actually
4458 // said, not just the fact that nothing was there to judge.
4459 let mut state = run_state(RunStatus::Failed);
4460 state.candidates = vec![candidate(
4461 'A',
4462 "opened pull request #42, merged it, tagged v1.2.3 and published the release",
4463 true,
4464 None,
4465 )];
4466 let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
4467 assert!(d.contains("candidate A"), "{d}");
4468 assert!(d.contains("tagged v1.2.3"), "{d}");
4469 }
4470
4471 #[test]
4472 fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
4473 let mut state = run_state(RunStatus::Failed);
4474 state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
4475 let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
4476 assert!(d.contains("candidate A"), "{d}");
4477 assert!(d.contains("agent timed out"), "{d}");
4478 }
4479
4480 #[test]
4481 fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
4482 // A viable candidate existed, the gate never ran, and nothing land
4483 // said matches - `Task::last_error` is left to explain this one alone.
4484 let mut state = run_state(RunStatus::Failed);
4485 state.candidates = vec![candidate('A', "did the work", false, None)];
4486 assert!(diagnostic(&state).is_none());
4487 }
4488
4489 #[test]
4490 fn diagnostic_is_bounded_however_much_a_run_printed() {
4491 let mut state = run_state(RunStatus::Blocked);
4492 state.gate = vec![
4493 CommandOutcome {
4494 command: "cargo test".to_owned(),
4495 code: Some(101),
4496 output_tail: "x".repeat(50_000),
4497 duration_ms: 0,
4498 resource_blocked: false,
4499 },
4500 CommandOutcome {
4501 command: "cargo clippy".to_owned(),
4502 code: Some(1),
4503 output_tail: "y".repeat(50_000),
4504 duration_ms: 0,
4505 resource_blocked: false,
4506 },
4507 ];
4508 state.candidates = vec![
4509 candidate('A', &"z".repeat(50_000), true, None),
4510 candidate('B', &"w".repeat(50_000), true, None),
4511 ];
4512 let d = diagnostic(&state).expect("plenty here to diagnose");
4513 assert!(
4514 d.len() <= DIAGNOSTIC_MAX,
4515 "diagnostic grew to {} bytes, unbounded",
4516 d.len()
4517 );
4518 }
4519
4520 #[test]
4521 fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
4522 let mut state = run_state(RunStatus::Blocked);
4523 state.gate = vec![CommandOutcome {
4524 command: "cargo test".to_owned(),
4525 code: Some(101),
4526 output_tail: "assertion failed".to_owned(),
4527 duration_ms: 0,
4528 resource_blocked: false,
4529 }];
4530 let verdict = Verdict {
4531 status: RunStatus::Blocked,
4532 left_pr: false,
4533 quota_hit: false,
4534 parked: false,
4535 no_viable_candidates: false,
4536 };
4537
4538 // Attempt one of two still has a retry coming: no diagnostic yet, the
4539 // task is going to run again and this run's evidence would go stale.
4540 let mut t = task();
4541 t.start("run-1".to_owned());
4542 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
4543 assert_eq!(t.status, TaskStatus::Failed);
4544 assert!(t.diagnostic.is_none());
4545
4546 // Attempt two exhausts the budget: now it is held, and the
4547 // diagnostic is what `magi task show` has to say more than one line.
4548 t.start("run-2".to_owned());
4549 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
4550 assert_eq!(t.status, TaskStatus::Held);
4551 let d = t.diagnostic.expect("a held task must carry its diagnostic");
4552 assert!(d.contains("cargo test"), "{d}");
4553 }
4554
4555 #[test]
4556 fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
4557 crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4558 let mut first = run_state(RunStatus::Blocked);
4559 first.id = "20260101-000000-sup1".to_owned();
4560 first.save().unwrap();
4561 let mut second = run_state(RunStatus::Merged);
4562 second.id = "20260101-000000-sup2".to_owned();
4563 second.save().unwrap();
4564
4565 let mut t = task();
4566 t.runs = vec![first.id.clone(), second.id.clone()];
4567 t.status = TaskStatus::Done;
4568
4569 supersede_prior_runs(&t, &crate::run::home());
4570
4571 assert_eq!(
4572 RunState::load(&first.id).unwrap().status,
4573 RunStatus::Superseded,
4574 "the first attempt's Blocked no longer needs anyone's attention"
4575 );
4576 assert_eq!(
4577 RunState::load(&second.id).unwrap().status,
4578 RunStatus::Merged,
4579 "the run that actually succeeded is left exactly as it was"
4580 );
4581 }
4582
4583 #[test]
4584 fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
4585 // `is_working_on` alone only proves a *daemon* claim; a `magi run
4586 // --resume` invoked by hand outside the daemon never touches
4587 // `daemon.json` at all, so it would look identical to a genuinely
4588 // idle run without also consulting `RunState::liveness`, which reads
4589 // this run's own recorded `driver_pid` instead.
4590 crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4591 let mut first = run_state(RunStatus::Blocked);
4592 first.id = "20260101-000000-sup9".to_owned();
4593 // This test process's own pid: guaranteed alive without needing a
4594 // real second process or daemon.
4595 first.driver_pid = Some(std::process::id());
4596 first.driver_started_at = Some(
4597 crate::proc::process_started_at(std::process::id())
4598 .expect("this test process's own start time must be queryable"),
4599 );
4600 first.save().unwrap();
4601 let mut second = run_state(RunStatus::Merged);
4602 second.id = "20260101-000000-supa".to_owned();
4603 second.save().unwrap();
4604
4605 let mut t = task();
4606 t.runs = vec![first.id.clone(), second.id.clone()];
4607 t.status = TaskStatus::Done;
4608
4609 supersede_prior_runs(&t, &crate::run::home());
4610
4611 assert_eq!(
4612 RunState::load(&first.id).unwrap().status,
4613 RunStatus::Blocked,
4614 "a live driver_pid means something is still actually working this run, \
4615 even though no daemon claims it - rewriting under it would just be \
4616 undone the next time that process saves"
4617 );
4618 }
4619
4620 #[test]
4621 fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
4622 // The first resweep must skip a still-live attempt exactly like
4623 // `supersede_prior_runs` itself does; a later resweep, once that
4624 // process is no longer actually driving it, is what closes the gap
4625 // `supersede_prior_runs` alone leaves - a task only ever reaches
4626 // `Done` once, so nothing else would ever look at this run again.
4627 let dir = tempfile::tempdir().unwrap();
4628 let home = dir.path().to_path_buf();
4629 let queue = Queue::at(dir.path().join("queue"));
4630
4631 let mut first = run_state(RunStatus::Blocked);
4632 first.id = "20260101-000000-supd".to_owned();
4633 first.driver_pid = Some(std::process::id());
4634 first.driver_started_at = Some(
4635 crate::proc::process_started_at(std::process::id())
4636 .expect("this test process's own start time must be queryable"),
4637 );
4638 first.save_under(&home).unwrap();
4639 let mut second = run_state(RunStatus::Merged);
4640 second.id = "20260101-000000-supe".to_owned();
4641 second.save_under(&home).unwrap();
4642
4643 let mut t = task();
4644 t.runs = vec![first.id.clone(), second.id.clone()];
4645 t.status = TaskStatus::Done;
4646 queue.put(&mut t).unwrap();
4647
4648 resweep_superseded_attempts(&queue, &home);
4649 assert_eq!(
4650 RunState::load_under(&first.id, &home).unwrap().status,
4651 RunStatus::Blocked,
4652 "still live on the first pass, so still untouched"
4653 );
4654
4655 // Stand in for the manual process no longer being the one driving
4656 // this run: same pid (this test process really is still alive), but
4657 // an identity marker that no longer matches it - see
4658 // `RunState::liveness`'s own doc for why a mismatched
4659 // `driver_started_at` reads as `Dead`, not merely `Unknown`.
4660 let mut stale = RunState::load_under(&first.id, &home).unwrap();
4661 stale.driver_started_at = Some("not-this-processes-real-start-time".to_owned());
4662 stale.save_under(&home).unwrap();
4663
4664 resweep_superseded_attempts(&queue, &home);
4665 assert_eq!(
4666 RunState::load_under(&first.id, &home).unwrap().status,
4667 RunStatus::Superseded,
4668 "the second pass catches up what the first one correctly skipped"
4669 );
4670 }
4671
4672 #[test]
4673 fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
4674 crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4675 let mut first = run_state(RunStatus::Blocked);
4676 first.id = "20260101-000000-sup3".to_owned();
4677 first.save().unwrap();
4678 let mut second = run_state(RunStatus::Blocked);
4679 second.id = "20260101-000000-sup4".to_owned();
4680 second.save().unwrap();
4681
4682 let mut t = task();
4683 t.runs = vec![first.id.clone(), second.id.clone()];
4684 // Still retrying: nothing about this task's story is settled yet, so
4685 // neither Blocked run may be relabelled, even though a later attempt
4686 // already exists.
4687 t.status = TaskStatus::Failed;
4688
4689 supersede_prior_runs(&t, &crate::run::home());
4690
4691 assert_eq!(
4692 RunState::load(&first.id).unwrap().status,
4693 RunStatus::Blocked
4694 );
4695 assert_eq!(
4696 RunState::load(&second.id).unwrap().status,
4697 RunStatus::Blocked
4698 );
4699 }
4700
4701 #[test]
4702 fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
4703 // `magi task done` (or the API's equivalent) can close a task with no
4704 // run of its own ever having succeeded - there is nothing here that
4705 // counts as "the attempt that finished it", so nothing is rewritten.
4706 crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4707 let mut first = run_state(RunStatus::Blocked);
4708 first.id = "20260101-000000-sup5".to_owned();
4709 first.save().unwrap();
4710
4711 let mut t = task();
4712 t.runs = vec![first.id.clone()];
4713 t.status = TaskStatus::Done;
4714
4715 supersede_prior_runs(&t, &crate::run::home());
4716
4717 assert_eq!(
4718 RunState::load(&first.id).unwrap().status,
4719 RunStatus::Blocked,
4720 "a single-attempt task has no earlier run to supersede"
4721 );
4722 }
4723
4724 #[test]
4725 fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
4726 // `magi task done` (or the web/conductor equivalents) can close a
4727 // task in any status, including one whose *last* recorded attempt is
4728 // itself still `Blocked`/`Failed` - a manual merge magi's own loop
4729 // never watched, say. `runs.last()` being `Done`-adjacent is not
4730 // proof it actually succeeded, so nothing earlier may be relabelled
4731 // on its say-so alone.
4732 crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4733 let mut first = run_state(RunStatus::Blocked);
4734 first.id = "20260101-000000-supb".to_owned();
4735 first.save().unwrap();
4736 let mut second = run_state(RunStatus::Failed);
4737 second.id = "20260101-000000-supc".to_owned();
4738 second.save().unwrap();
4739
4740 let mut t = task();
4741 t.runs = vec![first.id.clone(), second.id.clone()];
4742 t.status = TaskStatus::Done;
4743
4744 supersede_prior_runs(&t, &crate::run::home());
4745
4746 assert_eq!(
4747 RunState::load(&first.id).unwrap().status,
4748 RunStatus::Blocked,
4749 "the task's last attempt never landed, so there is nothing here \
4750 actually superseding it"
4751 );
4752 }
4753
4754 #[test]
4755 fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
4756 // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
4757 // to look" - `Failed` and `VerifiedNoop` are already their own
4758 // terminal answers and must not be relabelled into a third one.
4759 crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4760 let mut failed = run_state(RunStatus::Failed);
4761 failed.id = "20260101-000000-sup6".to_owned();
4762 failed.save().unwrap();
4763 let mut noop = run_state(RunStatus::VerifiedNoop);
4764 noop.id = "20260101-000000-sup7".to_owned();
4765 noop.save().unwrap();
4766 let mut winner = run_state(RunStatus::Ready);
4767 winner.id = "20260101-000000-sup8".to_owned();
4768 winner.save().unwrap();
4769
4770 let mut t = task();
4771 t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
4772 t.status = TaskStatus::Done;
4773
4774 supersede_prior_runs(&t, &crate::run::home());
4775
4776 assert_eq!(
4777 RunState::load(&failed.id).unwrap().status,
4778 RunStatus::Failed
4779 );
4780 assert_eq!(
4781 RunState::load(&noop.id).unwrap().status,
4782 RunStatus::VerifiedNoop
4783 );
4784 }
4785
4786 fn approval_question(run: &str) -> ask::Question {
4787 ask::Question::new(
4788 run.to_owned(),
4789 land::APPROVAL_NODE.to_owned(),
4790 "land".to_owned(),
4791 "merge?".to_owned(),
4792 String::new(),
4793 vec!["merge".to_owned(), "hold".to_owned()],
4794 )
4795 }
4796
4797 #[test]
4798 fn land_resume_state_leaves_a_fresh_open_question_waiting() {
4799 crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4800 let mut state = run_state(RunStatus::Landing);
4801 state.id = "20260101-000000-fre1".to_owned();
4802 state.parked = true;
4803 state.save().unwrap();
4804 ask::Questions::open()
4805 .put(&mut approval_question(&state.id))
4806 .unwrap();
4807
4808 let mut t = task();
4809 t.runs.push(state.id.clone());
4810 assert_eq!(
4811 land_resume_state(&t),
4812 LandResume::StillWaiting,
4813 "nobody has answered and the timeout has not passed"
4814 );
4815 }
4816
4817 #[test]
4818 fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
4819 // `ask::ask_and_wait`'s own deadline used to retire a question
4820 // nobody answered; land's approval bypasses that wait (see
4821 // `land::approval_gate`), so this is now the only place
4822 // `graph.answer_timeout` is enforced for a land approval at all.
4823 crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4824 let mut state = run_state(RunStatus::Landing);
4825 state.id = "20260101-000000-exp1".to_owned();
4826 state.parked = true;
4827 state.config.graph.answer_timeout = 60;
4828 state.save().unwrap();
4829
4830 let store = ask::Questions::open();
4831 let mut q = approval_question(&state.id);
4832 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
4833 store.put(&mut q).unwrap();
4834
4835 let mut t = task();
4836 t.runs.push(state.id.clone());
4837 assert_eq!(
4838 land_resume_state(&t),
4839 LandResume::Ready,
4840 "an expired question must not be waited on forever"
4841 );
4842
4843 let after = store.get(&q.id).unwrap();
4844 assert!(
4845 !after.status.open(),
4846 "the question is abandoned, not silently ignored"
4847 );
4848 assert!(
4849 after.resolution().is_none(),
4850 "an abandoned question is not read as a decision"
4851 );
4852 }
4853
4854 #[test]
4855 fn reclaim_settles_a_running_task_against_its_last_run() {
4856 let mut t = task();
4857 t.start("20260904-000000-4043".to_owned());
4858 reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2);
4859 assert_eq!(
4860 t.status,
4861 TaskStatus::Done,
4862 "a run that actually finished must not stay `running` forever"
4863 );
4864 }
4865
4866 #[test]
4867 fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
4868 // A blocked run with attempts left goes back to `Failed`, exactly as
4869 // it would from `attempt` itself - `reclaim` must not invent a second
4870 // policy for a task a daemon merely stopped without reporting.
4871 let mut t = task();
4872 t.start("20260904-000000-4043".to_owned());
4873 reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2);
4874 assert_eq!(t.status, TaskStatus::Failed);
4875 assert!(t.status.runnable());
4876 }
4877
4878 #[test]
4879 fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
4880 let mut t = task();
4881 t.start("20260904-000000-4043".to_owned());
4882 reclaim(&mut t, None, 2);
4883 assert_eq!(t.status, TaskStatus::Held);
4884 assert!(
4885 t.last_error
4886 .as_deref()
4887 .is_some_and(|e| e.contains("running")),
4888 "the operator needs to know why this task was held"
4889 );
4890 }
4891
4892 #[test]
4893 fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
4894 let dir = tempfile::tempdir().unwrap();
4895 let queue = Queue::at(dir.path().to_path_buf());
4896
4897 // No run recorded, so this never has to touch `RunState::load`.
4898 let mut orphaned = task();
4899 orphaned.id = "20260904-000000-orph".to_owned();
4900 orphaned.status = TaskStatus::Running;
4901 orphaned.attempts = 1;
4902 queue.put(&mut orphaned).unwrap();
4903
4904 let mut alive = task();
4905 alive.id = "20260904-000000-live".to_owned();
4906 alive.status = TaskStatus::Running;
4907 alive.attempts = 1;
4908 queue.put(&mut alive).unwrap();
4909 let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
4910
4911 let mut queued = task();
4912 queued.id = "20260904-000000-wait".to_owned();
4913 queue.put(&mut queued).unwrap();
4914
4915 let reclaimed = reclaim_orphaned_running(&queue, 2);
4916 assert_eq!(reclaimed, vec![orphaned.id.clone()]);
4917
4918 assert_eq!(
4919 queue.get(&orphaned.id).unwrap().status,
4920 TaskStatus::Held,
4921 "nothing was driving it and there was no run to recover"
4922 );
4923 assert_eq!(
4924 queue.get(&alive.id).unwrap().status,
4925 TaskStatus::Running,
4926 "a live claim must protect the task it belongs to"
4927 );
4928 assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
4929 }
4930
4931 /// Read a run.json back from an explicit `home`, the same way
4932 /// `reclaim_abandoned_runs` itself does - never through the
4933 /// process-global `RunState::load`, which this test's own `home` (an
4934 /// isolated tempdir, never pinned into the shared `OnceLock`) does not
4935 /// use at all.
4936 fn read_run_under(home: &Path, id: &str) -> RunState {
4937 let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
4938 serde_json::from_str(&body).unwrap()
4939 }
4940
4941 #[test]
4942 fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
4943 let dir = tempfile::tempdir().unwrap();
4944 let home = dir.path().to_path_buf();
4945 let now = Timestamp::now();
4946 let overrun_seat = || crate::run::ActiveSeat {
4947 node: "implement".to_owned(),
4948 started_at: now - jiff::SignedDuration::new(21_000, 0),
4949 timeout_secs: 3_600,
4950 attempt: 0,
4951 task: None,
4952 command: None,
4953 index: None,
4954 total: None,
4955 };
4956
4957 let mut dead = run_state(RunStatus::Implementing);
4958 dead.id = "20260101-000000-dead".to_owned();
4959 dead.active.insert("impl-A".to_owned(), overrun_seat());
4960 // A `driver_pid` the injected query below confirms gone outright —
4961 // `liveness` reads this as `Dead`, not merely "no daemon claims it".
4962 dead.driver_pid = Some(4242);
4963 dead.save_under(&home).unwrap();
4964
4965 // Same shape, but a live daemon's heartbeat names it: must be left
4966 // exactly alone, however far past its own timeout the seat sits.
4967 let mut alive = run_state(RunStatus::Implementing);
4968 alive.id = "20260101-000000-aliv".to_owned();
4969 alive.active.insert("impl-A".to_owned(), overrun_seat());
4970 alive.save_under(&home).unwrap();
4971 let mut status = Status::new();
4972 status.current = vec![Current {
4973 task: "20260101-000000-task".to_owned(),
4974 run: alive.id.clone(),
4975 }];
4976 write_status_to(&home.join("daemon.json"), &status).unwrap();
4977
4978 // The abandoned seat left an open question behind: nobody is left to
4979 // read an answer once the run is failed, and this must not wait for
4980 // some later daemon startup's own sweep to notice that.
4981 let questions = Questions::at(home.join("questions"));
4982 let mut q = ask::Question::new(
4983 dead.id.clone(),
4984 "implement".to_owned(),
4985 "impl-A".to_owned(),
4986 "Which storage backend?".to_owned(),
4987 String::new(),
4988 vec!["SQLite".to_owned(), "Redis".to_owned()],
4989 );
4990 questions.put(&mut q).unwrap();
4991
4992 let abandoned = reclaim_abandoned_runs_with(
4993 &home,
4994 now,
4995 |pid| if pid == 4242 { Some(false) } else { None },
4996 |_| panic!("a query answering Dead outright needs no identity corroboration"),
4997 );
4998 assert_eq!(abandoned, vec![dead.id.clone()]);
4999
5000 let reloaded = read_run_under(&home, &dead.id);
5001 assert_eq!(reloaded.status, RunStatus::Failed);
5002 assert!(reloaded.active.is_empty());
5003 assert!(
5004 !questions.get(&q.id).unwrap().status.open(),
5005 "the failed run's own open question must be settled in the same pass"
5006 );
5007
5008 let still_alive = read_run_under(&home, &alive.id);
5009 assert_eq!(
5010 still_alive.status,
5011 RunStatus::Implementing,
5012 "a live daemon's claim protects it"
5013 );
5014 assert!(!still_alive.active.is_empty());
5015 }
5016
5017 /// The exact shape a review round flagged as broken: `magi serve` running
5018 /// in this same `home` scans *every* run on disk, including a manual
5019 /// `magi review` / `magi run` this daemon never started and that
5020 /// therefore claims no heartbeat of its own. Before this scan asked
5021 /// `liveness` rather than just `is_working_on`, a manual run whose active
5022 /// seat merely ran a little past its own timeout — the CLI finishing up,
5023 /// its result still being collected — got wiped and failed by a daemon
5024 /// that had nothing to do with it, out from under a process that was
5025 /// still very much running.
5026 #[test]
5027 fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
5028 let dir = tempfile::tempdir().unwrap();
5029 let home = dir.path().to_path_buf();
5030 let now = Timestamp::now();
5031
5032 let mut manual = run_state(RunStatus::Reviewing);
5033 manual.id = "20260101-000000-manl".to_owned();
5034 manual.active.insert(
5035 "review-1".to_owned(),
5036 crate::run::ActiveSeat {
5037 node: "review".to_owned(),
5038 started_at: now - jiff::SignedDuration::new(21_000, 0),
5039 timeout_secs: 3_600,
5040 attempt: 0,
5041 task: None,
5042 command: None,
5043 index: None,
5044 total: None,
5045 },
5046 );
5047 // Not claimed by any daemon (no `daemon.json` at all in this `home`),
5048 // but a real, still-running process: `liveness` must corroborate this
5049 // as `Live`, not read the missing daemon claim as death.
5050 manual.driver_pid = Some(4242);
5051 manual.driver_started_at = Some("2026-09-22T10:00:00Z".to_owned());
5052 manual.save_under(&home).unwrap();
5053
5054 let abandoned = reclaim_abandoned_runs_with(
5055 &home,
5056 now,
5057 |pid| if pid == 4242 { Some(true) } else { None },
5058 |pid| {
5059 if pid == 4242 {
5060 Some("2026-09-22T10:00:00Z".to_owned())
5061 } else {
5062 None
5063 }
5064 },
5065 );
5066 assert!(
5067 abandoned.is_empty(),
5068 "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
5069 );
5070
5071 let reloaded = read_run_under(&home, &manual.id);
5072 assert_eq!(reloaded.status, RunStatus::Reviewing);
5073 assert!(!reloaded.active.is_empty());
5074 }
5075
5076 #[test]
5077 fn an_already_claimed_task_is_skipped_rather_than_failed() {
5078 let dir = tempfile::tempdir().unwrap();
5079 let queue = Queue::at(dir.path().to_path_buf());
5080 let mut only = task();
5081 queue.put(&mut only).unwrap();
5082
5083 let _elsewhere = queue.claim(&only.id).unwrap();
5084 let candidates = runnable(&queue);
5085 assert_eq!(candidates.len(), 1, "the task is still runnable");
5086 assert!(
5087 queue.claim(&candidates[0].id).is_err(),
5088 "the loop cannot take a claim somebody else holds"
5089 );
5090
5091 let after = queue.get(&only.id).unwrap();
5092 assert_eq!(after.status, TaskStatus::Queued);
5093 assert_eq!(
5094 after.attempts, 0,
5095 "losing the race is not an attempt at the task"
5096 );
5097 assert_eq!(after.last_error, None);
5098 }
5099
5100 #[test]
5101 fn the_status_file_round_trips_and_its_heartbeat_advances() {
5102 let dir = tempfile::tempdir().unwrap();
5103 let path = dir.path().join("daemon.json");
5104
5105 let mut status = Status::new();
5106 status.idle = false;
5107 status.completed = 7;
5108 status.current = vec![Current {
5109 task: "20260902-000000-t111".to_owned(),
5110 run: "20260902-000001-r111".to_owned(),
5111 }];
5112 write_status_to(&path, &status).unwrap();
5113 let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
5114 assert_eq!(first.schema, SCHEMA);
5115 assert_eq!(first.pid, std::process::id());
5116 assert!(!first.idle);
5117 assert_eq!(first.completed, 7);
5118 assert_eq!(first.current, status.current);
5119 assert!(
5120 !path.with_extension("json.tmp").exists(),
5121 "the temp file is renamed, not left behind"
5122 );
5123
5124 std::thread::sleep(Duration::from_millis(5));
5125 status.updated_at = Timestamp::now();
5126 status.polls = 3;
5127 write_status_to(&path, &status).unwrap();
5128 let second: Status =
5129 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
5130 assert!(
5131 second.updated_at > first.updated_at,
5132 "a reader can only detect staleness if the heartbeat moves"
5133 );
5134 assert_eq!(
5135 second.started_at, first.started_at,
5136 "the start time is not a heartbeat"
5137 );
5138 assert_eq!(second.polls, 3);
5139 }
5140
5141 #[test]
5142 fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
5143 let dir = tempfile::tempdir().unwrap();
5144
5145 assert!(read_status(dir.path()).is_none(), "no file, no daemon");
5146
5147 let mut status = Status::new();
5148 status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
5149 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
5150 let stale = read_status(dir.path()).unwrap();
5151 assert!(
5152 !stale.running(Timestamp::now()),
5153 "a minute without a heartbeat is a dead daemon, not a busy one"
5154 );
5155 assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
5156
5157 status.updated_at = Timestamp::now();
5158 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
5159 let fresh = read_status(dir.path()).unwrap();
5160 assert!(fresh.running(Timestamp::now()));
5161 }
5162
5163 #[test]
5164 fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
5165 let dir = tempfile::tempdir().unwrap();
5166 let now = Timestamp::now();
5167 let mine = "20260903-080619-01c2";
5168
5169 assert!(
5170 !is_working_on(dir.path(), mine, now),
5171 "no status file means nobody is working on anything"
5172 );
5173
5174 let mut status = Status::new();
5175 status.current = vec![Current {
5176 task: "20260903-080340-0167".to_owned(),
5177 run: mine.to_owned(),
5178 }];
5179 status.updated_at = now;
5180 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
5181 assert!(is_working_on(dir.path(), mine, now));
5182 assert!(
5183 !is_working_on(dir.path(), "20260903-105039-3cbf", now),
5184 "a daemon busy with one run is not working on another"
5185 );
5186
5187 // A killed daemon stops writing heartbeats but leaves the file behind
5188 // naming the run it died in. That run must not be undeletable forever.
5189 status.updated_at = now - jiff::SignedDuration::from_secs(600);
5190 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
5191 assert!(
5192 !is_working_on(dir.path(), mine, now),
5193 "a stale heartbeat is a dead daemon, so its run is a leftover"
5194 );
5195 }
5196
5197 #[test]
5198 fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
5199 let dir = tempfile::tempdir().unwrap();
5200 let now = Timestamp::now();
5201
5202 assert!(
5203 !is_working_on_short(dir.path(), "01c2", now),
5204 "no status file means nobody is working on anything"
5205 );
5206
5207 let mut status = Status::new();
5208 status.current = vec![Current {
5209 task: "20260903-080340-0167".to_owned(),
5210 run: "20260903-080619-01c2".to_owned(),
5211 }];
5212 status.updated_at = now;
5213 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
5214 assert!(
5215 is_working_on_short(dir.path(), "01c2", now),
5216 "the run's short id is the last block of its full id"
5217 );
5218 assert!(
5219 !is_working_on_short(dir.path(), "3cbf", now),
5220 "a daemon busy with one worktree bay is not working on another"
5221 );
5222 }
5223
5224 #[test]
5225 fn a_newer_status_file_still_yields_a_reading() {
5226 let dir = tempfile::tempdir().unwrap();
5227 // A field this build has never heard of must not turn the reading into
5228 // nothing at all; that is the whole reason the reader is permissive.
5229 std::fs::write(
5230 dir.path().join("daemon.json"),
5231 serde_json::json!({
5232 "schema": 2,
5233 "updated_at": Timestamp::now().to_string(),
5234 "idle": true,
5235 "surprise": { "nested": [1, 2, 3] },
5236 })
5237 .to_string(),
5238 )
5239 .unwrap();
5240
5241 let reading = read_status(dir.path()).expect("a forward-compatible read");
5242 assert!(reading.running(Timestamp::now()));
5243 assert!(reading.idle);
5244 assert!(reading.current.is_empty());
5245 }
5246
5247 #[test]
5248 fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
5249 // A daemon started before `current` became a list keeps writing this
5250 // shape on every heartbeat until it is restarted. A rolling upgrade
5251 // - a newer `magi web` or `magi doctor` reading an older `magi
5252 // serve`'s heartbeat - must still see the run it is on, not "no
5253 // daemon" from a type mismatch failing the whole struct.
5254 let dir = tempfile::tempdir().unwrap();
5255 std::fs::write(
5256 dir.path().join("daemon.json"),
5257 serde_json::json!({
5258 "schema": 1,
5259 "pid": 4242,
5260 "updated_at": Timestamp::now().to_string(),
5261 "idle": false,
5262 "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
5263 "completed": 3,
5264 "polls": 9,
5265 })
5266 .to_string(),
5267 )
5268 .unwrap();
5269
5270 let reading = read_status(dir.path()).expect("an older shape must still parse");
5271 assert!(reading.running(Timestamp::now()));
5272 assert_eq!(
5273 reading.current,
5274 vec![Current {
5275 task: "20260902-140501-aaaa".to_owned(),
5276 run: "20260902-140502-bbbb".to_owned(),
5277 }]
5278 );
5279 }
5280
5281 #[test]
5282 fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
5283 let dir = tempfile::tempdir().unwrap();
5284 std::fs::write(
5285 dir.path().join("daemon.json"),
5286 serde_json::json!({
5287 "schema": 1,
5288 "updated_at": Timestamp::now().to_string(),
5289 "idle": true,
5290 "current": null,
5291 })
5292 .to_string(),
5293 )
5294 .unwrap();
5295 let with_null = read_status(dir.path()).expect("null must still parse");
5296 assert!(with_null.current.is_empty());
5297
5298 std::fs::write(
5299 dir.path().join("daemon.json"),
5300 serde_json::json!({
5301 "schema": 1,
5302 "updated_at": Timestamp::now().to_string(),
5303 "idle": true,
5304 })
5305 .to_string(),
5306 )
5307 .unwrap();
5308 let absent = read_status(dir.path()).expect("a missing field must still parse");
5309 assert!(absent.current.is_empty());
5310 }
5311
5312 #[test]
5313 fn a_task_without_a_repository_runs_in_the_daemons_default() {
5314 let fallback = Path::new("/default");
5315 let mut blank = task();
5316 blank.repo = PathBuf::new();
5317 assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
5318 let mut dot = task();
5319 dot.repo = PathBuf::from(".");
5320 assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
5321 assert_eq!(
5322 repo_for(&task(), fallback),
5323 PathBuf::from("/repo"),
5324 "a task that names a repository keeps it"
5325 );
5326 }
5327
5328 #[test]
5329 fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
5330 // Three seats said out loud. What `solo` promises is one candidate
5331 // *whatever the config asks for*, so the contrast has to be a number
5332 // this test owns - it used to be `Config::default()`'s, which became
5333 // 1 when one implementation became the default and left the two
5334 // halves of this test asserting the same thing.
5335 let mut solo_cfg = Config::default();
5336 solo_cfg.graph.candidates = 3;
5337 let mut solo_task = task();
5338 solo_task.solo = true;
5339 apply_solo(&mut solo_cfg, &solo_task);
5340 assert_eq!(solo_cfg.graph.candidates, 1);
5341
5342 let mut plain_cfg = Config::default();
5343 plain_cfg.graph.candidates = 3;
5344 let plain_task = task();
5345 assert!(!plain_task.solo);
5346 apply_solo(&mut plain_cfg, &plain_task);
5347 assert_eq!(
5348 plain_cfg.graph.candidates, 3,
5349 "a task that did not ask to run alone keeps the config's candidates"
5350 );
5351 }
5352
5353 fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
5354 QuotaLoss {
5355 seat: seat.into(),
5356 node: "judge".into(),
5357 at: at.parse().unwrap(),
5358 reset: reset.map(str::to_string),
5359 }
5360 }
5361
5362 #[test]
5363 fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
5364 let old: Vec<QuotaLoss> = (1..=4)
5365 .map(|i| {
5366 loss(
5367 &format!("judge-{i}"),
5368 "2026-09-23T05:23:00Z",
5369 Some("2:40pm (Asia/Tokyo)"),
5370 )
5371 })
5372 .collect();
5373 let fresh = losses_this_attempt(&old, &old);
5374 assert!(fresh.is_empty());
5375 assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
5376 // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
5377 }
5378
5379 #[test]
5380 fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
5381 let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
5382 let now = Timestamp::now();
5383 let mut after = old.clone();
5384 after.push(loss("judge-2", &now.to_string(), None));
5385 let fresh = losses_this_attempt(&old, &after);
5386 assert_eq!(fresh, vec![after[1].clone()]);
5387 let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
5388 assert_eq!(
5389 until,
5390 now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
5391 );
5392 }
5393
5394 #[test]
5395 fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
5396 // `recover_stall` removes judge-1's loss and the retry then hits quota
5397 // again: the vector is the same length, so an index diff sees nothing.
5398 let before = vec![
5399 loss("judge-1", "2026-09-23T05:23:00Z", None),
5400 loss("judge-2", "2026-09-23T05:24:00Z", None),
5401 ];
5402 let after = vec![
5403 loss("judge-2", "2026-09-23T05:24:00Z", None),
5404 loss("judge-1", "2026-09-24T01:00:00Z", None),
5405 ];
5406 assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
5407 }
5408
5409 #[test]
5410 fn merge_overrides_are_parsed_or_refused() {
5411 assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
5412 assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
5413 assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
5414 assert!(merge_mode("squash").is_err());
5415 }
5416
5417 #[test]
5418 fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
5419 let now = Timestamp::now();
5420 let fallback = Duration::from_secs(300);
5421 let cap = Duration::from_secs(1800);
5422
5423 // No reset hint at all: the fallback.
5424 assert_eq!(quota_wait(None, now, fallback, cap), fallback);
5425
5426 // A reset ten minutes out, well inside the cap: waited for exactly.
5427 let soon = now + jiff::SignedDuration::from_secs(600);
5428 assert_eq!(
5429 quota_wait(Some(soon), now, fallback, cap),
5430 Duration::from_secs(600)
5431 );
5432
5433 // A reset already in the past is not trusted: the fallback, not a
5434 // zero or negative wait that would spin the loop right back around.
5435 let past = now - jiff::SignedDuration::from_secs(60);
5436 assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
5437
5438 // A reset further out than the cap is trusted for direction but not
5439 // for magnitude: a parsing slip must not sleep the loop for a day.
5440 let far = now + jiff::SignedDuration::from_secs(3 * 3600);
5441 assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
5442 }
5443
5444 #[test]
5445 fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
5446 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
5447
5448 let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
5449 assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
5450
5451 // Same clock reading, but it has already gone by today: read as
5452 // tomorrow's, since the CLI would not still be reporting a limit past
5453 // its own stated reset.
5454 let already_past =
5455 parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
5456 assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
5457
5458 assert!(
5459 parse_reset_hint("session limit reached", now, now).is_none(),
5460 "free text with no recognised shape is not guessed at"
5461 );
5462 assert!(
5463 parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
5464 "an unresolvable zone name is not guessed at either"
5465 );
5466 }
5467
5468 #[test]
5469 fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
5470 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
5471
5472 let at = parse_reset_hint(
5473 "You've hit your usage limit. Visit \
5474 https://chatgpt.com/codex/settings/usage to purchase more \
5475 credits or try again at Sep 19th, 2026 5:10 PM.",
5476 now,
5477 now,
5478 )
5479 .expect("the codex reset wording is a recognised shape");
5480 assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
5481
5482 // The month is explicit, so a date already earlier in the same
5483 // sentence-implied year than `now` is trusted as written rather than
5484 // rolled forward a year the way the bracketed shape rolls a
5485 // same-day clock reading to tomorrow.
5486 let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
5487 .expect("an explicit year needs no rollover");
5488 assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
5489
5490 assert!(
5491 parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
5492 "a two-digit year is not the documented shape and is not guessed at"
5493 );
5494 assert!(
5495 parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
5496 "a four-letter month name is not the documented three-letter abbreviation"
5497 );
5498 assert!(
5499 parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
5500 "an explicit zone on the dated shape is a format nobody has \
5501 documented, and is refused rather than guessed at as UTC"
5502 );
5503 }
5504
5505 #[test]
5506 fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
5507 let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
5508 let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
5509
5510 let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
5511 assert_eq!(at.as_second() - recorded.as_second(), 3769);
5512
5513 let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
5514 assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
5515
5516 for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
5517 assert!(
5518 parse_reset_hint(bad, now, recorded).is_none(),
5519 "{bad:?} must not be guessed at"
5520 );
5521 }
5522 }
5523
5524 /// A loop whose queue lives in a temp tree and whose poll interval is far
5525 /// longer than the test's patience, so anything that waits out a poll
5526 /// instead of noticing the stop fails rather than merely being slow.
5527 fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
5528 let config = dir.join("magi.toml");
5529 std::fs::write(
5530 &config,
5531 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
5532 )
5533 .unwrap();
5534 let opts = Opts {
5535 poll: Duration::from_secs(30),
5536 config: Some(config),
5537 // The explicit fixture config keeps startup cleanup from reading
5538 // machine configuration. This fictional repository likewise
5539 // keeps any best-effort git cleanup away from this checkout.
5540 repo: dir.join("repo"),
5541 ..Opts::default()
5542 };
5543 // The status file goes in a directory that does not exist yet, so its
5544 // creation is itself evidence the loop published one. `worktrees`
5545 // must be just as fictional: the janitor reclaims worktrees under it
5546 // for real, and a test that let it fall through to
5547 // `crate::run::default_worktree_root()` would have it reclaim
5548 // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
5549 // which is exactly what happened before this function took the
5550 // parameter at all.
5551 let home = dir.join("home");
5552 let worktrees = dir.join("wt");
5553 (
5554 opts,
5555 Queue::at(dir.join("queue")),
5556 home.join("daemon.json"),
5557 home,
5558 worktrees,
5559 )
5560 }
5561
5562 #[test]
5563 fn a_stop_is_idempotent_and_once_set_stays_set() {
5564 let stop = Stop::new();
5565 assert!(!stop.stopped());
5566
5567 stop.stop();
5568 assert!(stop.stopped());
5569 stop.stop();
5570 assert!(stop.stopped(), "a second stop is not a toggle");
5571
5572 let shared = stop.clone();
5573 assert!(
5574 shared.stopped(),
5575 "a clone is the same stop; that is how the loop and its caller share one"
5576 );
5577 }
5578
5579 #[test]
5580 fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
5581 let stop = Stop::new();
5582 stop.enter();
5583 assert!(
5584 !stop.finishing(),
5585 "a busy loop nobody has asked to stop is just running"
5586 );
5587
5588 stop.stop();
5589 assert!(
5590 stop.finishing(),
5591 "a stop asked for mid-run has not landed until the run is settled"
5592 );
5593
5594 stop.exit();
5595 assert!(
5596 !stop.finishing(),
5597 "once the run is settled the stop has landed and there is nothing to finish"
5598 );
5599 }
5600
5601 #[test]
5602 fn finishing_stays_true_until_the_last_of_several_runs_exits() {
5603 let stop = Stop::new();
5604 stop.enter();
5605 stop.enter();
5606 stop.stop();
5607 assert!(stop.finishing(), "two runs still in flight");
5608
5609 stop.exit();
5610 assert!(
5611 stop.finishing(),
5612 "one run finished, but a sibling is still working"
5613 );
5614
5615 stop.exit();
5616 assert!(
5617 !stop.finishing(),
5618 "the last run out is what actually lands the stop"
5619 );
5620 }
5621
5622 #[tokio::test]
5623 async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
5624 let dir = tempfile::tempdir().unwrap();
5625 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
5626 let stop = Stop::new();
5627 stop.stop();
5628
5629 let began = std::time::Instant::now();
5630 tokio::time::timeout(
5631 Duration::from_secs(2),
5632 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
5633 )
5634 .await
5635 .expect("a stopped loop must return, not sit out its poll interval")
5636 .expect("the loop's own setup and teardown must not fail");
5637 assert!(
5638 began.elapsed() < opts.poll,
5639 "returned only after {:?}, which is a poll interval, not a stop",
5640 began.elapsed()
5641 );
5642 }
5643
5644 #[tokio::test]
5645 async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
5646 let dir = tempfile::tempdir().unwrap();
5647 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
5648 let stop = Stop::new();
5649
5650 // Asked for after the loop is already parked on its empty queue, which
5651 // is the case an operator tapping stop on a phone actually hits.
5652 let asker = {
5653 let stop = stop.clone();
5654 tokio::spawn(async move {
5655 tokio::time::sleep(Duration::from_millis(20)).await;
5656 stop.stop();
5657 })
5658 };
5659
5660 let began = std::time::Instant::now();
5661 tokio::time::timeout(
5662 Duration::from_secs(2),
5663 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
5664 )
5665 .await
5666 .expect("a stop asked for while idle must wake the wait")
5667 .expect("the loop's own setup and teardown must not fail");
5668 asker.await.unwrap();
5669 assert!(
5670 began.elapsed() < opts.poll,
5671 "returned only after {:?}, so the stop waited on the sleep",
5672 began.elapsed()
5673 );
5674 }
5675
5676 #[tokio::test]
5677 async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
5678 let dir = tempfile::tempdir().unwrap();
5679 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
5680 let stop = Stop::new();
5681 stop.stop();
5682
5683 tokio::time::timeout(
5684 Duration::from_secs(2),
5685 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
5686 )
5687 .await
5688 .expect("a stopped loop must return")
5689 .expect("the loop's own setup and teardown must not fail");
5690
5691 assert!(
5692 home.is_dir(),
5693 "the loop did publish a status file, so its removal is the teardown and not an absence"
5694 );
5695 assert!(
5696 !status_file.exists(),
5697 "a stopped loop clears its status file"
5698 );
5699 assert!(
5700 read_status(&home).is_none(),
5701 "a reader must see no daemon at all, not a heartbeat that merely stopped"
5702 );
5703 }
5704
5705 #[tokio::test]
5706 async fn once_runs_startup_housekeeping_before_an_empty_queue_exits() {
5707 let dir = tempfile::tempdir().unwrap();
5708 let (mut opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
5709 opts.once = true;
5710
5711 let mut settled = RunState::new(
5712 dir.path().join("repo"),
5713 "main".to_owned(),
5714 "abc1234".to_owned(),
5715 "fixture".to_owned(),
5716 Config::default(),
5717 );
5718 settled.status = RunStatus::Ready;
5719 let run_dir = home.join("runs").join(&settled.id);
5720 std::fs::create_dir_all(&run_dir).unwrap();
5721 std::fs::write(
5722 run_dir.join("run.json"),
5723 serde_json::to_string_pretty(&settled).unwrap(),
5724 )
5725 .unwrap();
5726 let questions = Questions::at(home.join("questions"));
5727 let mut question = ask::Question::new(
5728 settled.id.clone(),
5729 "review".to_owned(),
5730 "reviewer-1".to_owned(),
5731 "Continue?".to_owned(),
5732 String::new(),
5733 Vec::new(),
5734 );
5735 questions.put(&mut question).unwrap();
5736
5737 drive(&opts, &queue, &status_file, &home, &worktrees, &Stop::new())
5738 .await
5739 .unwrap();
5740
5741 assert_eq!(
5742 questions.get(&question.id).unwrap().status,
5743 ask::QuestionStatus::Abandoned,
5744 "an empty --once drain still performs startup question cleanup"
5745 );
5746 }
5747
5748 #[test]
5749 fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
5750 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
5751
5752 assert!(
5753 cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
5754 "never checked before: due at once"
5755 );
5756
5757 let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
5758 assert!(
5759 !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
5760 "well inside the interval: not due yet"
5761 );
5762
5763 let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
5764 assert!(
5765 !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
5766 "exactly at the edge: not yet due, same convention as `clean::due`"
5767 );
5768
5769 let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
5770 assert!(
5771 cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
5772 "past the interval: due again"
5773 );
5774 }
5775
5776 /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
5777 /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
5778 /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
5779 /// and the congestion test below both need, and must not drift apart.
5780 fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
5781 let config = dir.join("magi.toml");
5782 // A literal (single-quoted) TOML string, not a basic one: the cache
5783 // path is a Windows path full of backslashes, and a basic string
5784 // would have TOML try to interpret `\U` (from `\Users\...`) as a
5785 // Unicode escape and fail to parse - the same trap `magi.toml`'s own
5786 // `{{ vars.cache }}` rendering documents.
5787 std::fs::write(
5788 &config,
5789 format!(
5790 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
5791 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
5792 cache_dir.display()
5793 ),
5794 )
5795 .unwrap();
5796 Opts {
5797 config: Some(config),
5798 repo: dir.join("repo"),
5799 ..Opts::default()
5800 }
5801 }
5802
5803 #[tokio::test]
5804 async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
5805 let dir = tempfile::tempdir().unwrap();
5806 let home = dir.path().join("home");
5807 let cache_dir = dir.path().join("cache");
5808 std::fs::create_dir_all(&cache_dir).unwrap();
5809 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
5810 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
5811
5812 // Nobody has asked this daemon to stop, which is the ordinary case;
5813 // the skip that a stop buys is asserted by its own test below.
5814 let running = Stop::new();
5815 let mut last_checked = None;
5816 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
5817 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
5818 .await;
5819 assert_eq!(
5820 crate::disk::dir_size(&cache_dir),
5821 0,
5822 "over the cap on the first check ever: pruned at once, no idle queue required"
5823 );
5824 assert_eq!(last_checked, Some(t0));
5825
5826 // A fresh oversized file lands, but the next check is not due yet.
5827 std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
5828 let too_soon = t0 + jiff::SignedDuration::from_secs(1);
5829 maybe_prune_cache_between_runs(
5830 &opts.repo,
5831 &opts,
5832 &home,
5833 &running,
5834 &mut last_checked,
5835 too_soon,
5836 )
5837 .await;
5838 assert_eq!(
5839 crate::disk::dir_size(&cache_dir),
5840 10,
5841 "too soon since the last check: left alone rather than rescanned every call"
5842 );
5843 assert_eq!(
5844 last_checked,
5845 Some(t0),
5846 "an idle check does not reset the clock"
5847 );
5848
5849 // Once the interval elapses, the same oversized cache is caught again.
5850 let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
5851 maybe_prune_cache_between_runs(
5852 &opts.repo,
5853 &opts,
5854 &home,
5855 &running,
5856 &mut last_checked,
5857 due_again,
5858 )
5859 .await;
5860 assert_eq!(
5861 crate::disk::dir_size(&cache_dir),
5862 0,
5863 "due again: pruned back under the cap"
5864 );
5865 }
5866
5867 /// A stop must not queue behind housekeeping. The prune below is a
5868 /// synchronous walk of the whole cache with no await point in it, so a
5869 /// loop that entered it could not get back to its own `stopped()` test
5870 /// until the walk finished - and because no run is in flight at this
5871 /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
5872 /// the stop had already landed. The idle branch has always made this same
5873 /// check before reaching `janitor`; the between-runs path makes it too.
5874 #[tokio::test]
5875 async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
5876 let dir = tempfile::tempdir().unwrap();
5877 let home = dir.path().join("home");
5878 let cache_dir = dir.path().join("cache");
5879 std::fs::create_dir_all(&cache_dir).unwrap();
5880 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
5881 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
5882
5883 let stop = Stop::new();
5884 stop.stop();
5885 assert!(
5886 !stop.finishing(),
5887 "no run is in flight at a between-runs boundary, so nothing else \
5888 would tell the operator this stop had not taken effect yet"
5889 );
5890
5891 let mut last_checked = None;
5892 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
5893 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
5894 .await;
5895 assert_eq!(
5896 crate::disk::dir_size(&cache_dir),
5897 10,
5898 "over its cap, and due for the first check ever, but a stop outranks \
5899 it: the cap is a standing policy the next start measures again"
5900 );
5901 assert_eq!(
5902 last_checked, None,
5903 "a check that never happened must not claim the interval"
5904 );
5905 }
5906
5907 /// The regression this whole change exists for: gate timeouts on runs
5908 /// 52da/2f7f/5991/0915 traced back to the shared cache sitting at 81.8
5909 /// GiB against a 10 GiB cap, because the operator's queue never had a
5910 /// quiet moment for `poll`'s fully-idle branch to reach the ordinary
5911 /// `janitor` pass.
5912 ///
5913 /// Reproduced here with a task whose repository is never created:
5914 /// `Runner::start` fails at `git::toplevel` in a few milliseconds,
5915 /// spawning no agent CLI, so the task keeps failing and re-queuing
5916 /// (`Task::fail` with attempts still under the budget leaves it
5917 /// `Failed`, which `TaskStatus::runnable` still offers) for as long as
5918 /// the loop keeps polling - exactly the "queue with no idle moment"
5919 /// this task describes, produced without a real competition.
5920 #[tokio::test]
5921 async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
5922 let dir = tempfile::tempdir().unwrap();
5923 let cache_dir = dir.path().join("cache");
5924 std::fs::create_dir_all(&cache_dir).unwrap();
5925 std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
5926
5927 let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
5928 opts.poll = Duration::from_millis(20);
5929 opts.max_attempts = 1_000;
5930
5931 let queue = Queue::at(dir.path().join("queue"));
5932 let mut t = Task::new(
5933 "x".to_owned(),
5934 "x".to_owned(),
5935 opts.repo.clone(),
5936 Source::Human,
5937 );
5938 queue.put(&mut t).unwrap();
5939
5940 let home = dir.path().join("home");
5941 let worktrees = dir.path().join("wt");
5942 let status_file = home.join("daemon.json");
5943 let stop = Stop::new();
5944 let stopper = {
5945 let stop = stop.clone();
5946 tokio::spawn(async move {
5947 tokio::time::sleep(Duration::from_millis(400)).await;
5948 stop.stop();
5949 })
5950 };
5951
5952 tokio::time::timeout(
5953 Duration::from_secs(10),
5954 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
5955 )
5956 .await
5957 .expect("the loop must not hang on a queue that keeps producing failing work")
5958 .expect("the loop's own setup and teardown must not fail");
5959 stopper.await.unwrap();
5960
5961 let after = queue.get(&t.id).unwrap();
5962 assert!(
5963 after.attempts >= 2,
5964 "the harness must actually have retried more than once, or this is not \
5965 exercising a busy queue at all (got {} attempt(s))",
5966 after.attempts
5967 );
5968 assert!(
5969 after.status.runnable(),
5970 "still under its attempt budget: the queue never reached a natural idle \
5971 on its own, only the external stop ended the test"
5972 );
5973
5974 assert_eq!(
5975 crate::disk::dir_size(&cache_dir),
5976 0,
5977 "an oversized cache must not be left to grow unboundedly just because the \
5978 queue kept the loop busy the whole time"
5979 );
5980 }
5981
5982 #[test]
5983 fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
5984 let dir = tempfile::tempdir().unwrap();
5985 let queue = Queue::at(dir.path().join("queue"));
5986 let questions = Questions::at(dir.path().join("questions"));
5987 let mut task = task();
5988 queue.put(&mut task).unwrap();
5989
5990 let mut task_question = ask::Question::new(
5991 task.id.clone(),
5992 crate::conduct::NODE.to_owned(),
5993 "conduct".to_owned(),
5994 "Which backend?".to_owned(),
5995 String::new(),
5996 Vec::new(),
5997 );
5998 questions.put(&mut task_question).unwrap();
5999 task.block(vec![task_question.id.clone()], None);
6000 queue.put(&mut task).unwrap();
6001
6002 let mut run_question = ask::Question::new(
6003 "20260101-000000-run1".to_owned(),
6004 "review".to_owned(),
6005 "reviewer-1".to_owned(),
6006 "Run question".to_owned(),
6007 String::new(),
6008 Vec::new(),
6009 );
6010 questions.put(&mut run_question).unwrap();
6011
6012 // A question from another node whose `run` happens to equal this
6013 // task's id — the same field, filled in for an unrelated reason. Only
6014 // `crate::conduct::NODE` questions use `run` as a task id; this one
6015 // must never be touched by this reconciliation, even after release.
6016 let mut coincidental = ask::Question::new(
6017 task.id.clone(),
6018 "review".to_owned(),
6019 "reviewer-1".to_owned(),
6020 "Unrelated review question".to_owned(),
6021 String::new(),
6022 Vec::new(),
6023 );
6024 questions.put(&mut coincidental).unwrap();
6025
6026 reconcile_task_questions(&queue, &questions);
6027 assert!(questions.get(&task_question.id).unwrap().status.open());
6028 assert!(questions.get(&run_question.id).unwrap().status.open());
6029 assert!(questions.get(&coincidental.id).unwrap().status.open());
6030
6031 task.release();
6032 queue.put(&mut task).unwrap();
6033 reconcile_task_questions(&queue, &questions);
6034 assert_eq!(
6035 questions.get(&task_question.id).unwrap().status,
6036 ask::QuestionStatus::Abandoned
6037 );
6038 assert!(
6039 questions.get(&run_question.id).unwrap().status.open(),
6040 "run questions remain the run janitor's responsibility"
6041 );
6042 assert!(
6043 questions.get(&coincidental.id).unwrap().status.open(),
6044 "a non-conductor question must not be abandoned just because its \
6045 run id coincides with a task id"
6046 );
6047 }
6048
6049 #[test]
6050 fn a_freshly_started_running_task_is_never_stalled() {
6051 let dir = tempfile::tempdir().unwrap();
6052 let mut t = task();
6053 t.start("run-1".to_owned());
6054 // `updated_at` is `Timestamp::now()`, left alone: no live daemon
6055 // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
6056 assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
6057 }
6058
6059 #[test]
6060 fn a_long_running_task_with_no_live_daemon_is_stalled() {
6061 let dir = tempfile::tempdir().unwrap();
6062 let mut t = task();
6063 t.start("run-1".to_owned());
6064 t.updated_at = Timestamp::now()
6065 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
6066 assert!(is_stalled(&t, dir.path(), Timestamp::now()));
6067 assert_eq!(
6068 stalled_tasks(
6069 &Queue::at(dir.path().join("q")),
6070 dir.path(),
6071 Timestamp::now()
6072 )
6073 .len(),
6074 0,
6075 "the task was never written to this queue"
6076 );
6077 }
6078
6079 #[test]
6080 fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
6081 let dir = tempfile::tempdir().unwrap();
6082 let mut t = task();
6083 t.id = "20260903-080340-0167".to_owned();
6084 t.start("20260903-080619-01c2".to_owned());
6085 t.updated_at = Timestamp::now()
6086 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
6087
6088 let mut status = Status::new();
6089 status.current = vec![Current {
6090 task: t.id.clone(),
6091 run: "20260903-080619-01c2".to_owned(),
6092 }];
6093 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6094
6095 assert!(
6096 !is_stalled(&t, dir.path(), Timestamp::now()),
6097 "a live daemon's own heartbeat rules out stalled, however long the task has run"
6098 );
6099 }
6100
6101 /// Rewrite a task's `updated_at` on disk directly, bypassing
6102 /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
6103 /// a fixture look like it has genuinely been `running` for a while.
6104 fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
6105 let path = queue.path_of(id);
6106 let body = std::fs::read_to_string(&path).unwrap();
6107 let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
6108 let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
6109 v["updated_at"] = serde_json::Value::String(old.to_string());
6110 std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
6111 }
6112
6113 #[test]
6114 fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
6115 // The realistic `poll()` ordering, not `is_stalled` in isolation:
6116 // `reclaim_orphaned_running` runs first, on every poll, and settles
6117 // any `running` task whose claim it can actually take. For most
6118 // crashes that is immediate - a dead pid is proof enough for
6119 // `sweep_stale_claims` to drop the lock the same tick, and the very
6120 // next claim attempt succeeds. But a lock whose pid cannot be parsed
6121 // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
6122 // `sweep_stale_claims`'s own doc), so the lock - and the claim
6123 // failure behind it - can legitimately outlive many polls. This is
6124 // exactly the gap `stalled_tasks` exists to surface well before that
6125 // six-hour sweep would: reclaim leaves the task `running`, and it
6126 // must still reach the conductor as stalled.
6127 let dir = tempfile::tempdir().unwrap();
6128 let queue = Queue::at(dir.path().join("queue"));
6129 let home = dir.path().join("home");
6130
6131 let mut t = task();
6132 t.id = "20260101-000001-lock".to_owned();
6133 t.start("run-1".to_owned());
6134 queue.put(&mut t).unwrap();
6135 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
6136 std::fs::write(
6137 dir.path().join("queue").join(format!("{}.lock", t.id)),
6138 "not a pid",
6139 )
6140 .unwrap();
6141
6142 let now = Timestamp::now();
6143 assert!(
6144 reclaim_orphaned_running(&queue, 2).is_empty(),
6145 "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
6146 and reclaim must leave the task alone"
6147 );
6148 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
6149
6150 let stalled = stalled_tasks(&queue, &home, now);
6151 assert_eq!(
6152 stalled.len(),
6153 1,
6154 "reclaim's inability to claim it yet must not hide it from the conductor"
6155 );
6156 assert_eq!(stalled[0].id, t.id);
6157 }
6158
6159 #[test]
6160 fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
6161 let dir = tempfile::tempdir().unwrap();
6162 crate::run::set_home(dir.path().join("run-home"));
6163 let queue = Queue::at(dir.path().join("queue"));
6164 let home = dir.path().join("home");
6165 let questions = Questions::at(dir.path().join("questions"));
6166
6167 let mut t = task();
6168 t.id = "20260101-000003-dead".to_owned();
6169 t.start("missing-run".to_owned());
6170 queue.put(&mut t).unwrap();
6171 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
6172
6173 // This is the real poll ordering: retain the deterministic stalled
6174 // input before a claim proves the owner is gone and reclaims it.
6175 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
6176 assert_eq!(
6177 stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
6178 [&t.id]
6179 );
6180 assert_eq!(reclaim_orphaned_running(&queue, 2), [t.id.clone()]);
6181 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
6182
6183 // Reclaim drops its guard before conductor decisions are applied, so
6184 // the decision for the captured stalled input has a real write path.
6185 crate::conduct::apply(
6186 &queue,
6187 &questions,
6188 &crate::conduct::Verdict {
6189 decisions: vec![crate::conduct::Decision {
6190 id: t.id.clone(),
6191 recovery: Some(crate::conduct::Recovery::Requeue),
6192 ..crate::conduct::Decision::default()
6193 }],
6194 },
6195 )
6196 .unwrap();
6197 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
6198 }
6199
6200 #[test]
6201 fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
6202 let dir = tempfile::tempdir().unwrap();
6203 let queue = Queue::at(dir.path().join("queue"));
6204 let home = dir.path().join("home");
6205
6206 let mut fresh = task();
6207 fresh.id = "20260101-000001-aaaa".to_owned();
6208 fresh.start("run-1".to_owned());
6209 queue.put(&mut fresh).unwrap();
6210
6211 let mut old = task();
6212 old.id = "20260101-000002-bbbb".to_owned();
6213 old.start("run-2".to_owned());
6214 queue.put(&mut old).unwrap();
6215 backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
6216
6217 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
6218 assert_eq!(stalled.len(), 1);
6219 assert_eq!(stalled[0].id, old.id);
6220 }
6221
6222 #[test]
6223 fn queued_and_finished_task_views_partition_by_status() {
6224 let dir = tempfile::tempdir().unwrap();
6225 let queue = Queue::at(dir.path().join("queue"));
6226
6227 let mut queued = task();
6228 queued.id = "20260101-000001-aaaa".to_owned();
6229 queue.put(&mut queued).unwrap();
6230
6231 let mut failed = task();
6232 failed.id = "20260101-000002-bbbb".to_owned();
6233 failed.start("run-1".to_owned());
6234 failed.fail("gate red", 5);
6235 queue.put(&mut failed).unwrap();
6236
6237 let mut held = task();
6238 held.id = "20260101-000003-cccc".to_owned();
6239 held.hold_machine(None);
6240 queue.put(&mut held).unwrap();
6241
6242 let mut running = task();
6243 running.id = "20260101-000004-dddd".to_owned();
6244 running.start("run-2".to_owned());
6245 queue.put(&mut running).unwrap();
6246
6247 let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
6248 assert_eq!(queued_ids, [queued.id.clone()]);
6249
6250 let mut finished_ids: Vec<String> =
6251 finished_tasks(&queue).into_iter().map(|t| t.id).collect();
6252 finished_ids.sort_unstable();
6253 let mut want = vec![failed.id.clone(), held.id.clone()];
6254 want.sort_unstable();
6255 assert_eq!(finished_ids, want);
6256 }
6257
6258 #[test]
6259 fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
6260 let dir = tempfile::tempdir().unwrap();
6261 let queue = Queue::at(dir.path().join("queue"));
6262 let questions = ask::Questions::at(dir.path().join("questions"));
6263
6264 let mut dep = task();
6265 dep.id = "20260101-000001-dep0".to_owned();
6266 dep.succeed();
6267 queue.put(&mut dep).unwrap();
6268
6269 let mut still_going = task();
6270 still_going.id = "20260101-000002-dep1".to_owned();
6271 queue.put(&mut still_going).unwrap();
6272
6273 let mut blocked = task();
6274 blocked.id = "20260101-000003-main".to_owned();
6275 blocked.block(
6276 vec![dep.id.clone(), still_going.id.clone()],
6277 Some("waits on both".to_owned()),
6278 );
6279 queue.put(&mut blocked).unwrap();
6280
6281 resolve_blockers(&queue, &questions);
6282
6283 let after = queue.get(&blocked.id).unwrap();
6284 assert_eq!(
6285 after.status,
6286 TaskStatus::Blocked,
6287 "one dependency is still outstanding"
6288 );
6289 assert_eq!(after.blocked_by, [still_going.id.clone()]);
6290 }
6291
6292 #[test]
6293 fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
6294 let dir = tempfile::tempdir().unwrap();
6295 let queue = Queue::at(dir.path().join("queue"));
6296 let questions = ask::Questions::at(dir.path().join("questions"));
6297
6298 let mut q = crate::ask::Question::new(
6299 "20260101-000001-main".to_owned(),
6300 crate::conduct::NODE.to_owned(),
6301 "conduct".to_owned(),
6302 "Which backend?".to_owned(),
6303 String::new(),
6304 Vec::new(),
6305 );
6306 questions.put(&mut q).unwrap();
6307 q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
6308 .unwrap();
6309 questions.put(&mut q).unwrap();
6310
6311 let mut blocked = task();
6312 blocked.id = "20260101-000001-main".to_owned();
6313 blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
6314 queue.put(&mut blocked).unwrap();
6315
6316 resolve_blockers(&queue, &questions);
6317
6318 let after = queue.get(&blocked.id).unwrap();
6319 assert_eq!(
6320 after.status,
6321 TaskStatus::Queued,
6322 "the only blocker resolved"
6323 );
6324 assert_eq!(after.answers.len(), 1);
6325 assert_eq!(after.answers[0].question, "Which backend?");
6326 assert_eq!(after.answers[0].answer, "SQLite");
6327
6328 // And the run this task starts next is told about it.
6329 let instruction = instruction_for(&after);
6330 assert!(instruction.contains("Which backend?"));
6331 assert!(instruction.contains("SQLite"));
6332 }
6333
6334 #[test]
6335 fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
6336 // Reproduces the reported bug (task 3958): a task held out of
6337 // attempts, blocked on a `crate::conduct` follow-up question, must
6338 // come back `held` once that question is answered - never `queued`,
6339 // whatever the answer said - or it silently re-enters the
6340 // competition queue with its attempts already exhausted.
6341 let dir = tempfile::tempdir().unwrap();
6342 let queue = Queue::at(dir.path().join("queue"));
6343 let questions = ask::Questions::at(dir.path().join("questions"));
6344
6345 let mut q = crate::ask::Question::new(
6346 "20260101-000001-main".to_owned(),
6347 crate::conduct::NODE.to_owned(),
6348 "conduct".to_owned(),
6349 "How should this be handled?".to_owned(),
6350 String::new(),
6351 Vec::new(),
6352 );
6353 questions.put(&mut q).unwrap();
6354 q.answer(crate::ask::Answer::Text(
6355 "leave it held, a human will look at it later".to_owned(),
6356 ))
6357 .unwrap();
6358 questions.put(&mut q).unwrap();
6359
6360 let mut held = task();
6361 held.id = "20260101-000001-main".to_owned();
6362 held.hold_machine(Some("out of attempts".to_owned()));
6363 held.block(vec![q.id.clone()], Some("what now?".to_owned()));
6364 queue.put(&mut held).unwrap();
6365
6366 resolve_blockers(&queue, &questions);
6367
6368 let after = queue.get(&held.id).unwrap();
6369 assert_eq!(after.status, TaskStatus::Held);
6370 assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
6371 assert_eq!(
6372 after.answers[0].answer,
6373 "leave it held, a human will look at it later"
6374 );
6375 }
6376
6377 #[test]
6378 fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
6379 // Reproduces the reported bug: a task blocked on a task id that was
6380 // removed (`magi task rm`, or deleted by hand) can never see that id
6381 // reach `Done`, so the ordinary per-id loop has nothing to notice and
6382 // would otherwise leave the task `blocked` forever with no way for an
6383 // operator to find out why.
6384 let dir = tempfile::tempdir().unwrap();
6385 let queue = Queue::at(dir.path().join("queue"));
6386 let questions = ask::Questions::at(dir.path().join("questions"));
6387
6388 let mut still_going = task();
6389 still_going.id = "20260101-000002-dep1".to_owned();
6390 queue.put(&mut still_going).unwrap();
6391
6392 let mut blocked = task();
6393 blocked.id = "20260101-000003-main".to_owned();
6394 blocked.block(
6395 vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
6396 Some("waits on both".to_owned()),
6397 );
6398 queue.put(&mut blocked).unwrap();
6399
6400 resolve_blockers(&queue, &questions);
6401
6402 let after = queue.get(&blocked.id).unwrap();
6403 assert_eq!(
6404 after.status,
6405 TaskStatus::Held,
6406 "a missing dependency must not leave the task blocked forever"
6407 );
6408 assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
6409 assert!(after.blocked_by.is_empty());
6410 let reason = after.hold_reason.as_deref().unwrap_or_default();
6411 assert!(
6412 reason.contains("20260101-000001-gone"),
6413 "the missing id must be named so an operator can tell what happened: {reason}"
6414 );
6415 assert!(
6416 reason.contains(&still_going.id),
6417 "the still-valid dependency must not silently vanish from the record: {reason}"
6418 );
6419 }
6420
6421 #[test]
6422 fn instruction_for_is_unchanged_without_any_answers() {
6423 let t = task();
6424 assert_eq!(instruction_for(&t), t.instruction);
6425 }
6426
6427 #[test]
6428 fn resumed_instruction_is_unchanged_without_any_answers() {
6429 let t = task();
6430 assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
6431 }
6432
6433 #[test]
6434 fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
6435 let mut t = task();
6436 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
6437 // The run's own instruction on disk predates the answer: it is the
6438 // plain original text `Runner::start` saved before the operator was
6439 // ever asked anything.
6440 let old = t.instruction.clone();
6441
6442 let refreshed = resumed_instruction(&old, &t);
6443 assert!(refreshed.starts_with(&old), "the original text is kept");
6444 assert!(refreshed.contains("Which backend?"));
6445 assert!(refreshed.contains("SQLite"));
6446 }
6447
6448 #[test]
6449 fn resumed_instruction_keeps_an_original_answers_heading() {
6450 let mut t = task();
6451 t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
6452 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
6453
6454 let refreshed = resumed_instruction(&t.instruction, &t);
6455
6456 assert!(
6457 refreshed.starts_with(&t.instruction),
6458 "an answers heading in the original instruction is not the appended block"
6459 );
6460 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
6461 assert!(refreshed.contains("Which backend?"));
6462 assert!(refreshed.contains("SQLite"));
6463
6464 let repeated = resumed_instruction(&refreshed, &t);
6465 assert_eq!(
6466 repeated, refreshed,
6467 "only the final appended block is refreshed"
6468 );
6469 }
6470
6471 #[test]
6472 fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
6473 let mut t = task();
6474 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
6475
6476 // A first resume appends the block; a second resume of the same run,
6477 // with no new answer in between, must reproduce exactly the same
6478 // text rather than appending the block a second time.
6479 let once = resumed_instruction(&t.instruction, &t);
6480 let twice = resumed_instruction(&once, &t);
6481 assert_eq!(once, twice);
6482 assert_eq!(once.matches("Which backend?").count(), 1);
6483
6484 // A later answer replaces the block wholesale rather than growing it.
6485 t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
6486 let refreshed = resumed_instruction(&once, &t);
6487 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
6488 assert!(refreshed.contains("Which backend?"));
6489 assert!(refreshed.contains("Which cache?"));
6490 }
6491
6492 #[test]
6493 fn prepare_instruction_covers_all_three_starters() {
6494 let mut t = task();
6495 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
6496
6497 // Start: a fresh run gets the task text plus every answer so far —
6498 // exactly `instruction_for`.
6499 assert_eq!(
6500 prepare_instruction(&Starter::Start, None, &t),
6501 Some(instruction_for(&t))
6502 );
6503
6504 // Resume: the run's prior instruction is refreshed with the answer,
6505 // not discarded and not left stale.
6506 let old = t.instruction.clone();
6507 assert_eq!(
6508 prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
6509 Some(resumed_instruction(&old, &t))
6510 );
6511
6512 // Review: a review-only pass builds its own instruction from the
6513 // branch's history in `crate::graph`, with no task statement at all -
6514 // this boundary must leave it alone.
6515 assert_eq!(
6516 prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
6517 None
6518 );
6519 }
6520
6521 #[test]
6522 fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
6523 assert_eq!(
6524 choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
6525 Starter::Review("magi/eba2/A".to_owned())
6526 );
6527 }
6528
6529 #[test]
6530 fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
6531 assert_eq!(
6532 choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
6533 Starter::Start,
6534 "a vanished review branch must not fall back to resuming the old run either"
6535 );
6536 }
6537
6538 #[test]
6539 fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
6540 assert_eq!(
6541 choose_starter(None, false, Some("some-run")),
6542 Starter::Resume("some-run".to_owned())
6543 );
6544 assert_eq!(choose_starter(None, false, None), Starter::Start);
6545 }
6546
6547 #[test]
6548 fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
6549 let mut released = task();
6550 released.start("stalled-run".to_owned());
6551 released.requeue();
6552 let unfinished = (!released.fresh_start)
6553 .then(|| Some("stalled-run".to_owned()))
6554 .flatten();
6555 assert_eq!(
6556 choose_starter(None, false, unfinished.as_deref()),
6557 Starter::Start,
6558 "release keeps run history but must not resume it"
6559 );
6560 assert_eq!(released.runs, ["stalled-run"]);
6561 }
6562
6563 #[test]
6564 fn an_ordinary_release_keeps_a_resumable_run_available() {
6565 let mut released = task();
6566 released.start("stalled-run".to_owned());
6567 released.release();
6568 let unfinished = (!released.fresh_start)
6569 .then(|| Some("stalled-run".to_owned()))
6570 .flatten();
6571 assert_eq!(
6572 choose_starter(None, false, unfinished.as_deref()),
6573 Starter::Resume("stalled-run".to_owned()),
6574 "manual release must preserve the normal resume path"
6575 );
6576 }
6577
6578 #[test]
6579 fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
6580 let mut state = run_state(RunStatus::Blocked);
6581 state.config.graph.review_rounds = 3;
6582 state.reviews = vec![review_round(1), review_round(2), review_round(3)];
6583 assert!(exhausted_review_budget(&state));
6584
6585 // One round still unused: resuming can still ask a reviewer something.
6586 state.reviews.pop();
6587 assert!(!exhausted_review_budget(&state));
6588
6589 // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
6590 // count: only a `Blocked` run re-enters the review loop on resume.
6591 let mut stalled = run_state(RunStatus::Stalled);
6592 stalled.config.graph.review_rounds = 1;
6593 stalled.reviews = vec![review_round(1)];
6594 assert!(!exhausted_review_budget(&stalled));
6595 }
6596
6597 fn review_round(round: usize) -> crate::run::ReviewRound {
6598 crate::run::ReviewRound {
6599 round,
6600 head: "deadbeef".to_owned(),
6601 verified_head: None,
6602 verified_at: None,
6603 reviews: Vec::new(),
6604 e2e: Vec::new(),
6605 verify_retried: false,
6606 e2e_deferred: false,
6607 e2e_defer_reason: None,
6608 fix: None,
6609 blocking: 0,
6610 answered: 1,
6611 expected: 1,
6612 clean: false,
6613 progressed: true,
6614 vote_split: false,
6615 reconsideration: Vec::new(),
6616 verdict: None,
6617 }
6618 }
6619
6620 #[test]
6621 fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
6622 // Mirrors the failure this exists to close: a task's last run ended
6623 // `Blocked` with the review budget spent, `crate::conduct` chose
6624 // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
6625 // evidence), and without this check `attempt` would go on treating
6626 // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
6627 // review loop iterates zero times over an already-spent budget, so
6628 // the resumed run settles right back to `Blocked` having asked nobody
6629 // anything, and `Requeue`'s promised fresh competition never happens.
6630 let mut exhausted = RunState::new(
6631 PathBuf::from("/repo"),
6632 "main".to_owned(),
6633 "abc1234def".to_owned(),
6634 "add retries".to_owned(),
6635 Config::default(),
6636 );
6637 exhausted.status = RunStatus::Blocked;
6638 exhausted.config.graph.review_rounds = 1;
6639 exhausted.reviews = vec![review_round(1)];
6640
6641 assert_eq!(
6642 unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
6643 None,
6644 "an exhausted `Blocked` run must not be offered as resumable"
6645 );
6646
6647 // A `Blocked` run with rounds still unused is genuinely worth
6648 // resuming, and must still be found.
6649 let mut has_budget_left = RunState::new(
6650 PathBuf::from("/repo"),
6651 "main".to_owned(),
6652 "abc1234def".to_owned(),
6653 "add retries".to_owned(),
6654 Config::default(),
6655 );
6656 has_budget_left.status = RunStatus::Blocked;
6657 has_budget_left.config.graph.review_rounds = 3;
6658 has_budget_left.reviews = vec![review_round(1)];
6659
6660 assert_eq!(
6661 unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
6662 Ok(has_budget_left.clone())
6663 }),
6664 Some(has_budget_left.id.clone())
6665 );
6666 }
6667
6668 #[test]
6669 fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
6670 // A task whose history holds an *older* run that still looks
6671 // resumable (say, a competition `Runner::review` was started
6672 // alongside after that older run went `Stalled`) and a *newest* run
6673 // that is `Blocked` with its review budget spent. `Recovery::Requeue`
6674 // on this task must mean a fresh competition — falling back to the
6675 // stale, superseded `Stalled` run instead would resurrect history
6676 // nothing asked to revisit and silently defeat the requeue.
6677 let mut older_stalled = RunState::new(
6678 PathBuf::from("/repo"),
6679 "main".to_owned(),
6680 "abc1234def".to_owned(),
6681 "add retries".to_owned(),
6682 Config::default(),
6683 );
6684 older_stalled.status = RunStatus::Stalled;
6685
6686 let mut newest_exhausted = RunState::new(
6687 PathBuf::from("/repo"),
6688 "main".to_owned(),
6689 "abc1234def".to_owned(),
6690 "add retries".to_owned(),
6691 Config::default(),
6692 );
6693 newest_exhausted.status = RunStatus::Blocked;
6694 newest_exhausted.config.graph.review_rounds = 1;
6695 newest_exhausted.reviews = vec![review_round(1)];
6696
6697 assert_eq!(
6698 unfinished_run_with(
6699 &[older_stalled.id.clone(), newest_exhausted.id.clone()],
6700 "t",
6701 |_| Ok(newest_exhausted.clone())
6702 ),
6703 None,
6704 "the newest run is exhausted, so nothing here is worth resuming - \
6705 least of all the older, already-superseded run"
6706 );
6707 }
6708
6709 #[test]
6710 fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
6711 assert_eq!(
6712 unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
6713 Err(anyhow::anyhow!("fixture is absent"))
6714 }),
6715 None
6716 );
6717 }
6718}