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