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