Skip to main content

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