Skip to main content

magi/
daemon.rs

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