Skip to main content

magi/
daemon.rs

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