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;
61use crate::clean;
62use crate::config::{Config, MergeMode};
63use crate::graph::Runner;
64use crate::land;
65use crate::queue::{Queue, Task, TaskStatus};
66use crate::run::{QuotaLoss, RunState, RunStatus};
67
68/// On-disk format for [`Status`]. Bumped when a field's meaning changes.
69pub const SCHEMA: u32 = 1;
70
71/// How often the status file is refreshed. A reader treats a status file older
72/// than [`STALE_SECS`] as "no daemon", so the heartbeat has to be brisk enough
73/// that a busy daemon is never mistaken for a dead one.
74pub const HEARTBEAT: Duration = Duration::from_secs(5);
75
76/// How old a heartbeat may be before a reader calls the daemon dead. Six
77/// missed beats: long enough to survive a slow filesystem, short enough that
78/// a crashed daemon is not still reported as running a task.
79///
80/// The single threshold every reader shares — the web UI's `/api/health` and
81/// `magi doctor` both call [`Reading::running`] rather than each comparing
82/// against their own copy of this number, so a crashed daemon cannot look
83/// alive on one screen and dead on another.
84pub const STALE_SECS: i64 = 30;
85
86/// Default queue poll interval.
87pub const POLL: Duration = Duration::from_secs(5);
88
89/// How old a claim has to be before startup sweeps it. Longer than any run
90/// this graph plausibly takes, so a sweep cannot pull a task out from under a
91/// daemon that is merely slow.
92pub const STALE_CLAIM: Duration = Duration::from_secs(6 * 60 * 60);
93
94/// What the loop is working on, for the status file.
95#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
96#[serde(default)]
97pub struct Current {
98    /// Task id being run.
99    pub task: String,
100    /// Run id the task produced.
101    pub run: String,
102}
103
104/// The daemon's liveness, published to `<home>/daemon.json`.
105///
106/// This is the only interface between the loop and the web UI, which is why it
107/// carries `updated_at` as well as `started_at`: a reader cannot tell a
108/// running daemon from a `SIGKILL`ed one by the file's existence alone, but it
109/// can compare the heartbeat against the clock.
110#[derive(Debug, Clone, Serialize, Deserialize)]
111pub struct Status {
112    /// On-disk format version.
113    pub schema: u32,
114    /// Process id, so a human can find or kill the daemon.
115    pub pid: u32,
116    /// When this process started.
117    pub started_at: Timestamp,
118    /// Last heartbeat.
119    pub updated_at: Timestamp,
120    /// True when the queue has nothing runnable.
121    pub idle: bool,
122    /// Every task and run currently in flight. More than one entry means the
123    /// loop is driving more than one run at once — see
124    /// [`crate::config::Daemon::max_concurrent_runs`]. Empty, not absent, when
125    /// nothing is running, so a reader never has to treat "no field" and "an
126    /// empty list" as two different kinds of idle.
127    pub current: Vec<Current>,
128    /// Tasks that reached a terminal status in this process.
129    pub completed: usize,
130    /// Queue polls since start, so a wedged loop shows up as a frozen count.
131    pub polls: u64,
132}
133
134impl Status {
135    /// A fresh, idle status for this process.
136    #[must_use]
137    pub fn new() -> Self {
138        let now = Timestamp::now();
139        Self {
140            schema: SCHEMA,
141            pid: std::process::id(),
142            started_at: now,
143            updated_at: now,
144            idle: true,
145            current: Vec::new(),
146            completed: 0,
147            polls: 0,
148        }
149    }
150}
151
152impl Default for Status {
153    fn default() -> Self {
154        Self::new()
155    }
156}
157
158/// How the loop should behave.
159#[derive(Debug, Clone)]
160pub struct Opts {
161    /// Repository used by tasks that name none.
162    pub repo: PathBuf,
163    /// Explicit `magi.toml`, instead of the discovered layer stack.
164    pub config: Option<PathBuf>,
165    /// Queue poll interval.
166    pub poll: Duration,
167    /// Attempts a task gets before it is held for a human.
168    pub max_attempts: usize,
169    /// Drain what is runnable now, then return, instead of waiting for more.
170    pub once: bool,
171    /// Merge mode override (`none`, `local`, `pr`); `None` keeps the config's.
172    pub merge: Option<String>,
173    /// Where the janitor's [`crate::clean::fold_orphaned_worktrees`] and
174    /// [`crate::git::worktree_prune`] look for and reclaim worktrees.
175    /// `None` resolves to [`crate::run::default_worktree_root`] - the
176    /// operator's real `~/wt/<repo>` - the same way a run with no
177    /// [`crate::config::Graph::worktree_root`] resolves its own. A caller
178    /// that does not own that directory (a test, an embedding that manages
179    /// worktrees itself) must set this, or every idle tick reclaims worktrees
180    /// out from under whoever actually does.
181    pub worktrees_root: Option<PathBuf>,
182}
183
184impl Default for Opts {
185    fn default() -> Self {
186        Self {
187            repo: PathBuf::from("."),
188            config: None,
189            poll: POLL,
190            max_attempts: 2,
191            once: false,
192            merge: None,
193            worktrees_root: None,
194        }
195    }
196}
197
198/// How many runs a plain `usize` from config may drive concurrently, floored
199/// at one. A `0` in a config file would otherwise stall the loop entirely -
200/// no runnable task could ever start - which is never what an operator who
201/// wrote `0` meant.
202fn max_concurrent(n: usize) -> usize {
203    n.max(1)
204}
205
206/// Where the status file lives.
207#[must_use]
208pub fn status_path() -> PathBuf {
209    crate::run::home().join("daemon.json")
210}
211
212/// Publish the status file for this process.
213pub fn write_status(status: &Status) -> Result<()> {
214    write_status_to(&status_path(), status)
215}
216
217/// Publish a status to an explicit path.
218///
219/// Written to a sibling `.tmp` and renamed, because the web UI reads this file
220/// on every health poll and must never see a half-written one.
221pub fn write_status_to(path: &Path, status: &Status) -> Result<()> {
222    if let Some(parent) = path.parent() {
223        std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
224    }
225    let body = serde_json::to_string_pretty(status).context("serialize daemon status")?;
226    let tmp = path.with_extension("json.tmp");
227    std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
228    std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
229    Ok(())
230}
231
232/// Delete the status file. Called on the way out so a clean exit reads as
233/// "no daemon" rather than as a daemon whose heartbeat merely stopped.
234pub fn clear_status() {
235    clear_status_at(&status_path());
236}
237
238/// Delete a status file at an explicit path, so the loop's teardown and
239/// [`clear_status`] cannot drift apart: the loop is handed the path it
240/// published to, and a test can watch a temp file disappear.
241fn clear_status_at(path: &Path) {
242    let _ = std::fs::remove_file(path);
243}
244
245/// A cooperative stop, shared with whoever asked the loop to run.
246///
247/// Cloning is how the request travels: [`serve_until`] keeps one handle, the
248/// Ctrl-C listener and the web UI keep others, and every clone points at the
249/// same flag. There is no channel because there is nothing to send — the only
250/// message is "stop", it is idempotent, and a flag cannot be missed by a
251/// receiver that was not listening yet.
252///
253/// The handle also answers the question the operator's screen asks next: a
254/// stop does not take effect until the run in flight has finished, so
255/// [`Stop::finishing`] reports "asked to stop, still working" rather than
256/// leaving a caller to infer it from a heartbeat and hope.
257#[derive(Debug, Clone, Default)]
258pub struct Stop {
259    /// Set once, never cleared: a stop is not something an operator takes back
260    /// half way through, and a clearable flag would let a start racing a stop
261    /// resurrect a loop that is already unwinding.
262    stopped: Arc<AtomicBool>,
263    /// How many runs are in flight, so `finishing` can distinguish a stop
264    /// that has landed from one that is waiting on `execute`. A count, not a
265    /// flag, because more than one run can be in flight at once - see
266    /// [`crate::config::Daemon::max_concurrent_runs`] - and the last one to
267    /// finish is the one that should turn "finishing" off.
268    busy: Arc<std::sync::atomic::AtomicUsize>,
269    /// Wakes the idle wait. Without this a stop would not be seen until the
270    /// poll interval elapsed, and an operator tapping stop on a phone would
271    /// watch a button do nothing for five seconds.
272    wake: Arc<Notify>,
273    /// Handed to the run in flight, so a stop can also mean "park at the next
274    /// node boundary" instead of "finish the whole competition first".
275    pause: crate::graph::Pause,
276}
277
278impl Stop {
279    /// A stop nobody has asked for yet.
280    #[must_use]
281    pub fn new() -> Self {
282        Self::default()
283    }
284
285    /// Ask the loop to stop. Idempotent, and safe to call before the loop
286    /// starts: the flag is checked before the first poll.
287    pub fn stop(&self) {
288        self.stopped.store(true, Ordering::SeqCst);
289        // `notify_one` rather than `notify_waiters` because the loop may not be
290        // parked yet: this stores a permit, so a wait that registers a moment
291        // later returns at once instead of sleeping out the whole interval.
292        self.wake.notify_one();
293    }
294
295    /// Has a stop been asked for?
296    #[must_use]
297    pub fn stopped(&self) -> bool {
298        self.stopped.load(Ordering::SeqCst)
299    }
300
301    /// Has a stop been asked for that has not taken effect yet, because a run
302    /// is still in flight?
303    ///
304    /// This is the state a screen has to be able to show. A stop never abandons
305    /// a run — see [`serve_until`] — so between the tap and the loop's return
306    /// there is a window of tens of minutes in which "running" and "stopped"
307    /// are both misleading answers.
308    #[must_use]
309    pub fn finishing(&self) -> bool {
310        self.stopped() && self.busy_now()
311    }
312
313    /// Ask the loop to stop *and* the run in flight to park at its next node
314    /// boundary.
315    ///
316    /// The plain [`Stop::stop`] never abandons a run, which is right when the
317    /// operator only wants the queue to drain: a competition is tens of
318    /// minutes and its worktrees are paid for. But an operator who wants to
319    /// replace the binary cannot wait out a run that has an hour left, and
320    /// killing the process loses whatever the seats in flight had not written.
321    /// Parking costs at most the node in progress and leaves the run
322    /// resumable.
323    pub fn park(&self) {
324        self.pause.park();
325        self.stop();
326    }
327
328    /// Has a park been asked for?
329    #[must_use]
330    pub fn parking(&self) -> bool {
331        self.pause.parked()
332    }
333
334    /// The pause handle to give a runner.
335    #[must_use]
336    pub fn pause(&self) -> crate::graph::Pause {
337        self.pause.clone()
338    }
339
340    /// Is any run in flight right now?
341    ///
342    /// `finishing` answers "a stop is waiting on a run", which is false until
343    /// someone asks to stop. An upgrade needs the plain question, because it
344    /// is about to be the one asking.
345    #[must_use]
346    pub fn busy_now(&self) -> bool {
347        self.busy.load(Ordering::SeqCst) > 0
348    }
349
350    /// Mark one more run as in flight, for [`Stop::finishing`].
351    fn enter(&self) {
352        self.busy.fetch_add(1, Ordering::SeqCst);
353    }
354
355    /// Mark one run as finished. The last one out is what makes
356    /// [`Stop::busy_now`] false again.
357    fn exit(&self) {
358        self.busy.fetch_sub(1, Ordering::SeqCst);
359    }
360
361    /// Wait out one poll interval, returning early once a stop is asked for.
362    async fn idle(&self, poll: Duration) {
363        tokio::select! {
364            () = tokio::time::sleep(poll) => {}
365            () = self.wake.notified() => {}
366        }
367    }
368}
369
370/// The daemon's published state, read permissively.
371///
372/// This mirrors [`Status`], but is a separate declaration on purpose: every
373/// field defaults, so a status file from an older or newer magi still yields
374/// a usable reading — one this build has never heard of — instead of a parse
375/// error that hides the daemon entirely.
376#[derive(Debug, Clone, Default, Deserialize)]
377#[serde(default)]
378pub struct Reading {
379    /// Format version the daemon claims.
380    pub schema: u32,
381    /// Daemon process id, for an operator who wants to stop it.
382    pub pid: Option<u32>,
383    /// When that process started.
384    pub started_at: Option<Timestamp>,
385    /// Last heartbeat. Absent means the file is unusable, hence not running.
386    pub updated_at: Option<Timestamp>,
387    /// True when the queue had nothing runnable at the last poll.
388    pub idle: bool,
389    /// What the daemon is working on. Empty means idle; more than one entry
390    /// means more than one run is in flight at once.
391    ///
392    /// `deserialize_with` rather than the plain derive: a daemon started
393    /// before this field became a list is still out there writing the old
394    /// shape — a single `{"task":...,"run":...}` object, or its absence —
395    /// on every heartbeat until it is restarted, and a live process reading
396    /// that file during the rollout must still see it as running rather than
397    /// as absent. A bare type change here would fail the whole struct's
398    /// deserialization on a type mismatch, defeating the permissiveness this
399    /// type exists for.
400    #[serde(deserialize_with = "de_current")]
401    pub current: Vec<Current>,
402    /// Tasks this daemon process has finished.
403    pub completed: u64,
404    /// Queue polls this daemon process has made.
405    pub polls: u64,
406}
407
408/// Accept the old single-`Current`-or-absent shape as well as the current
409/// list, so a reader never has to know which build wrote the file.
410fn de_current<'de, D>(deserializer: D) -> std::result::Result<Vec<Current>, D::Error>
411where
412    D: serde::Deserializer<'de>,
413{
414    #[derive(Deserialize)]
415    #[serde(untagged)]
416    enum Shape {
417        Many(Vec<Current>),
418        One(Current),
419    }
420    Ok(
421        Option::<Shape>::deserialize(deserializer)?.map_or_else(Vec::new, |shape| match shape {
422            Shape::Many(v) => v,
423            Shape::One(c) => vec![c],
424        }),
425    )
426}
427
428impl Reading {
429    /// Seconds since the last heartbeat, or `None` when there has never been
430    /// one.
431    #[must_use]
432    pub fn age_secs(&self, now: Timestamp) -> Option<i64> {
433        self.updated_at
434            .map(|at| (now.as_second() - at.as_second()).max(0))
435    }
436
437    /// Whether the loop counts as running: a heartbeat no older than
438    /// [`STALE_SECS`]. The alternative is a reader that claims a task is in
439    /// progress hours after the daemon that owned it was killed.
440    #[must_use]
441    pub fn running(&self, now: Timestamp) -> bool {
442        self.age_secs(now).is_some_and(|secs| secs <= STALE_SECS)
443    }
444}
445
446/// Read `<home>/daemon.json` permissively, or `None` when there is nothing
447/// usable there.
448///
449/// Missing, half-written and unparseable all collapse to `None`, because the
450/// only question a reader asks is whether a daemon is alive, and a file it
451/// cannot read is not evidence that one is.
452#[must_use]
453pub fn read_status(home: &Path) -> Option<Reading> {
454    let body = std::fs::read_to_string(home.join("daemon.json")).ok()?;
455    serde_json::from_str(&body).ok()
456}
457
458/// Every run a live daemon is working on right now.
459///
460/// One definition of liveness, because deleting a task and deleting a run are
461/// both gated on it from both the CLI and the web UI - four callers that must
462/// never disagree about whether the same thing is in flight. A stale heartbeat
463/// reads as "no daemon": that is [`Reading::running`]'s judgement, and a task
464/// left at `running` or a run left at `implementing` by a killed daemon is a
465/// leftover record rather than work in progress. More than one entry once
466/// [`crate::config::Daemon::max_concurrent_runs`] is more than one - a caller
467/// after "the one thing in flight" wants [`is_working_on`] or
468/// [`is_working_on_task`], not this directly.
469#[must_use]
470pub fn current_work(home: &Path, now: Timestamp) -> Vec<Current> {
471    read_status(home)
472        .filter(|reading| reading.running(now))
473        .map(|reading| reading.current)
474        .unwrap_or_default()
475}
476
477/// Whether a live daemon is working on this run at this moment.
478#[must_use]
479pub fn is_working_on(home: &Path, run: &str, now: Timestamp) -> bool {
480    current_work(home, now).iter().any(|c| c.run == run)
481}
482
483/// Whether a live daemon is working on a run whose short id is this one.
484///
485/// For a worktree that has no run record to compare against at all -
486/// [`crate::clean::fold_orphaned_worktrees`]'s whole reason to exist - a full
487/// id is not available to hand to [`is_working_on`]. The short id is: a run's
488/// worktree bay is named after it (see [`crate::run::RunState::worktree_root`]),
489/// and it is exactly the gap between the daemon claiming a task and
490/// `RunState::new` saving the first `run.json` that this exists to protect -
491/// a run genuinely in flight but invisible to a scan of `runs/`.
492#[must_use]
493pub fn is_working_on_short(home: &Path, short: &str, now: Timestamp) -> bool {
494    current_work(home, now)
495        .iter()
496        .any(|c| crate::run::short_of(&c.run) == short)
497}
498
499/// Whether a live daemon is working on this task at this moment.
500#[must_use]
501pub fn is_working_on_task(home: &Path, task: &str, now: Timestamp) -> bool {
502    current_work(home, now).iter().any(|c| c.task == task)
503}
504
505/// Remove claim files whose owner is provably dead, or that have simply
506/// outlived `older_than`, and return the task ids swept.
507///
508/// A daemon killed with `SIGKILL` never runs [`crate::queue::Claim`]'s
509/// destructor, and the orphaned `.lock` file would make its task permanently
510/// unclaimable — the backlog would stop for good at exactly the task that was
511/// in flight when the machine went down.
512///
513/// The pid recorded in the lock is the authority whenever it can be read at
514/// all; age is only a fallback for when it cannot be.
515///
516/// - **A parseable pid wins outright.** [`crate::proc::pid_alive`] decides,
517///   full stop — dead sweeps the lock immediately, regardless of age; alive
518///   protects it, regardless of age. This is what lets a lock be reclaimed in
519///   seconds instead of waiting out [`STALE_CLAIM`]: a lock made 33 minutes
520///   before this daemon even started, next to a `queued` task, no longer has
521///   to sit for six hours before anything notices its owner is gone.
522/// - **A pid that cannot be parsed at all** — an empty or corrupt lock file —
523///   falls back to `older_than`, since there is nothing else to check.
524///
525/// Age must never override a *positive* liveness confirmation. `sweep`
526/// [`poll`]s concurrently with every attempt this daemon itself has spawned —
527/// see [`InFlightGuard`] — not only between them the way a single sequential
528/// loop once did, so a run that legitimately runs longer than `older_than`
529/// (a multi-round review, a long land wait carried across several resumed
530/// attempts) still has this very process's own live pid sitting in its own
531/// lock file on every later sweep. Deciding by age alone in that case would
532/// delete this daemon's own still-valid claim on its own in-flight task,
533/// which [`reclaim_orphaned_running`] would then read as abandoned and hand
534/// to a second attempt — two `Runner`s writing the same `run.json` and the
535/// same worktree at once. `pid_alive` answering "alive" for anything it
536/// cannot determine (a live process, a pid this build cannot check, one
537/// under another account) is exactly what keeps that path from ever
538/// firing on a guess.
539///
540/// [`STALE_CLAIM`] itself stays large: a helper program missing or its
541/// output unreadable must not be license to guess, and the risk of an
542/// unparseable lock outliving a genuinely dead owner is bounded by an order
543/// of magnitude above any plausible run rather than by a positive check.
544///
545/// Runs on every poll, not only at startup — a daemon up for days must keep
546/// noticing a lock some other, now-dead, daemon left behind just as readily
547/// as one it trips over on the way up.
548pub fn sweep_stale_claims(queue: &Queue, older_than: Duration) -> Vec<String> {
549    let this_process = std::process::id();
550    let mut swept: Vec<String> = std::fs::read_dir(queue.root())
551        .into_iter()
552        .flatten()
553        .flatten()
554        .map(|e| e.path())
555        .filter(|p| p.extension().is_some_and(|x| x == "lock"))
556        .filter(|p| {
557            match std::fs::read_to_string(p)
558                .ok()
559                .and_then(|body| body.trim().parse::<u32>().ok())
560            {
561                // This process wrote it and is asking the question right
562                // now, so it is definitionally still alive - settled without
563                // spawning a helper process at all.
564                Some(pid) if pid == this_process => false,
565                Some(pid) => !crate::proc::pid_alive(pid),
566                None => p
567                    .metadata()
568                    .and_then(|m| m.modified())
569                    .and_then(|t| t.elapsed().map_err(std::io::Error::other))
570                    .is_ok_and(|age| age >= older_than),
571            }
572        })
573        .filter(|p| std::fs::remove_file(p).is_ok())
574        .filter_map(|p| {
575            p.file_stem()
576                .and_then(|s| s.to_str())
577                .map(std::borrow::ToOwned::to_owned)
578        })
579        .collect();
580    swept.sort_unstable();
581    swept
582}
583
584/// What a finished run tells the queue about the task it came from.
585///
586/// A struct rather than a fourth and fifth boolean argument: the two flags
587/// answer different questions about the same run, and a call site passing
588/// `(…, true, false)` is one transposition away from refunding attempts
589/// forever.
590#[derive(Debug, Clone, Copy)]
591pub struct Verdict {
592    /// Where the graph stopped.
593    pub status: RunStatus,
594    /// The run opened a pull request.
595    pub left_pr: bool,
596    /// At least one seat was lost to a rate limit.
597    pub quota_hit: bool,
598    /// The run parked at a node boundary because it was asked to.
599    pub parked: bool,
600    /// The run never produced a single candidate a judge could look at.
601    ///
602    /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
603    /// still have another candidate worth judging, in which case the loss was
604    /// not the reason nothing came of the run. This is `true` only when the
605    /// implement wave ended with nothing viable at all.
606    pub no_viable_candidates: bool,
607}
608
609/// Record a finished run against the task it came from.
610///
611/// Kept pure and separate from the loop because this mapping *is* the retry
612/// policy, and a policy that can only be exercised by spawning a graph is a
613/// policy nobody checks. The table:
614///
615/// | run status                           | task becomes        | attempt spent |
616/// |---------------------------------------|---------------------|---------------|
617/// | parked at a boundary                  | `Failed` (requeued) | **no**        |
618/// | `Merged`, `Ready`                      | `Done`               | yes          |
619/// | `Stalled`, quota hit                   | `Failed` (requeued) | **no**        |
620/// | `Failed`, quota hit, no viable cand.   | `Failed` (requeued) | **no**        |
621/// | `Stalled`, no quota                    | `Failed`, or `Held`  | yes          |
622/// | `Blocked` with a PR                    | `Held`               | yes          |
623/// | `Blocked`, `Failed` otherwise          | `Failed`, or `Held`  | yes          |
624/// | anything non-terminal                  | `Failed`, or `Held`  | yes          |
625///
626/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
627/// twice, together. A quorum lost to rate limits is a property of the machine
628/// and not of the task, so the attempt is refunded and a reset quota picks
629/// the work up where it stopped — and that is just as true when every
630/// implement seat lost the same race and `after_implement` bails with nothing
631/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
632/// machine fact. The `no_viable_candidates` guard is what keeps that row
633/// narrow: a `Failed` run that produced a real candidate which then lost for
634/// some other reason still spends the attempt, exactly like the quorum lost
635/// to judges that answered with the wrong shape is ordinary flakiness, and
636/// refunding *that* takes the bound off the retry loop entirely: run e633
637/// stalled with `quota: []` after two judges wrote unusable JSON, was
638/// refunded, and the next attempt paid for a fresh hour-long implement wave
639/// before it could fail the same way. `max_attempts` exists precisely so
640/// that cannot repeat forever.
641///
642/// A non-terminal status means `execute` returned while the graph was still
643/// mid-flight, which is a bug rather than a verdict; it is treated as a
644/// failure so that a task cannot loop on it either.
645///
646/// `left_pr` splits the `Blocked` row, and it is the difference between a run
647/// that failed and a run that finished into a gate. See [`Task::handed_off`].
648pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
649    // A parked run is the operator's own doing, and its work is intact on
650    // disk. The task goes back in line with its attempt refunded so the next
651    // loop resumes the same run - which `one_task` prefers over competing
652    // again - and so that swapping the binary a few times cannot exhaust a
653    // budget meant for agents that actually misbehaved.
654    if verdict.parked {
655        task.stall(detail);
656        return;
657    }
658    match verdict.status {
659        RunStatus::Merged | RunStatus::Ready => task.succeed(),
660        RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
661        RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
662            task.stall(detail)
663        }
664        RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
665        RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
666        RunStatus::Blocked => task.fail(detail, max_attempts),
667        other => task.fail(
668            format!(
669                "the graph stopped at `{}` without reaching a terminal status: {detail}",
670                label(other)
671            ),
672            max_attempts,
673        ),
674    }
675}
676
677/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
678/// task ends up held.
679///
680/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
681/// dead daemon never got back to) share this, so the two cannot drift into
682/// disagreeing about which held tasks get a diagnostic.
683fn settle_and_diagnose(
684    task: &mut Task,
685    verdict: Verdict,
686    detail: &str,
687    max_attempts: usize,
688    state: &RunState,
689) {
690    settle(task, verdict, detail, max_attempts);
691    if task.status == TaskStatus::Held {
692        task.diagnostic = diagnostic(state);
693    }
694}
695
696/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
697/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
698/// by some other means entirely, like a manual `magi run` resume that
699/// finishes the graph outside the queue's bookkeeping.
700///
701/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
702/// `settle` is separate from `attempt`: a task recovered this way must land
703/// exactly where a live daemon would have put it — the same policy table,
704/// not a second one that quietly drifts from it — and that is only checkable
705/// without spawning a real run.
706fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize) {
707    match last_run {
708        Some(state) => {
709            let verdict = Verdict {
710                status: state.status,
711                left_pr: state.pr.is_some(),
712                quota_hit: !state.quota.is_empty(),
713                parked: state.parked,
714                no_viable_candidates: state.viable().is_empty(),
715            };
716            let detail = format!(
717                "recovered a `running` task whose daemon never recorded the outcome: {}",
718                describe(&state)
719            );
720            settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
721        }
722        None => {
723            let why = "task was `running` with no live daemon and no readable \
724                       run to recover; held for a human to check what happened";
725            task.last_error = Some(why.to_owned());
726            // The phone shows `hold_reason`, so a task held by the machine
727            // says why there too and not only in `last_error`.
728            task.hold(Some(why.to_owned()));
729        }
730    }
731}
732
733/// Find every task left at `running` that no live process is actually
734/// driving, and settle each one against whatever its last run became.
735///
736/// # Why a claim is proof, not a guess
737///
738/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
739/// `running`, and the guard is held for the task's whole time in that status:
740/// `attempt` does not return, and the loop does not move past the scope
741/// holding the claim, until the run has settled. So a `running` task whose
742/// lock is gone cannot have a live owner — this process or any other —
743/// without needing a staleness threshold or a pid check the way
744/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
745/// task that never got as far as `running` at all. Taking the claim here is
746/// the whole test: it either fails, because something really does hold it
747/// and the task is left alone, or it succeeds, which is the proof — and it is
748/// kept for the rest of the decision so nothing else can start a competing
749/// run while this one is being written.
750///
751/// Called on every poll, not only at startup, for the reason
752/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
753/// keep noticing this, not only on the one morning it happened to restart.
754fn reclaim_orphaned_running(queue: &Queue, max_attempts: usize) -> Vec<String> {
755    let mut reclaimed = Vec::new();
756    for listed in queue.list() {
757        if listed.status != TaskStatus::Running {
758            continue;
759        }
760        let Ok(_claim) = queue.claim(&listed.id) else {
761            continue;
762        };
763        // Re-read under the claim: a release or an edit landed by a human
764        // between the listing above and the claim just taken must not be
765        // clobbered by a decision based on the stale copy.
766        let Ok(mut task) = queue.get(&listed.id) else {
767            continue;
768        };
769        if task.status != TaskStatus::Running {
770            continue;
771        }
772        let last_run = task.runs.last().and_then(|id| RunState::load(id).ok());
773        // `execute` normally abandons a run's own open questions the moment
774        // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
775        // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
776        // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
777        // with the question still `open`, because the process died before
778        // reaching that call. `reclaim` itself stays pure on purpose (see its
779        // own doc), so the same cleanup runs here instead, against the run
780        // this reclaim is already reading. `settle_run` costs nothing when
781        // `execute` already got there first.
782        if let Some(state) = &last_run
783            && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
784        {
785            tracing::warn!("abandon questions for {}: {e:#}", state.id);
786        }
787        reclaim(&mut task, last_run, max_attempts);
788        record(queue, &mut task);
789        reclaimed.push(task.id.clone());
790    }
791    reclaimed
792}
793
794/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
795///
796/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
797/// sets, so there is one loop body rather than two that drift apart the first
798/// time the retry policy changes on only one of them.
799pub async fn serve(opts: Opts) -> Result<()> {
800    serve_until(opts, Stop::new()).await
801}
802
803/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
804///
805/// Neither a signal nor a `stop` abandons a run in flight. Killing the graph
806/// mid-node leaves worktrees, branches and agent sessions behind, and every
807/// agent call already paid for is lost; finishing the run costs the operator a
808/// wait and saves them a cleanup. A stop therefore only sets a flag: the
809/// current `execute` runs to its terminal status, the task's outcome is
810/// recorded, and only then does the loop return. That window is what
811/// [`Stop::finishing`] is for. An operator who genuinely wants the run dead
812/// still has a second Ctrl-C, which the runtime turns into a process kill —
813/// and the task left `Running` then tells the next daemon, and the next human,
814/// where to look.
815///
816/// While the queue is empty the stop is honoured within one wakeup rather than
817/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
818/// caller that taps stop does not sit through the remainder of a sleep.
819pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
820    let signal = {
821        let stop = stop.clone();
822        tokio::spawn(async move {
823            if tokio::signal::ctrl_c().await.is_ok() {
824                stop.stop();
825                tracing::info!("shutdown requested; a run in flight will be finished first");
826            }
827        })
828    };
829
830    let worktrees_root = opts
831        .worktrees_root
832        .clone()
833        .unwrap_or_else(crate::run::default_worktree_root);
834    let outcome = drive(
835        &opts,
836        &Queue::open(),
837        &status_path(),
838        &crate::run::home(),
839        &worktrees_root,
840        &stop,
841    )
842    .await;
843
844    signal.abort();
845    outcome
846}
847
848/// The loop proper: setup, poll, teardown, with the queue and the status file
849/// supplied rather than discovered.
850///
851/// All three of `home`, `worktrees_root` and the queue/status paths are
852/// parameters rather than resolved here, for the same reason:
853/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
854/// so a unit test that pinned it would fight every other test in the binary,
855/// and a loop that resolved its own worktree bay could only be exercised
856/// against the operator's real `~/wt/<repo>` - publishing over a live
857/// daemon's status file, claiming tasks out of a live backlog, and, since
858/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
859/// whatever the operator actually has on disk.
860async fn drive(
861    opts: &Opts,
862    queue: &Queue,
863    status_file: &Path,
864    home: &Path,
865    worktrees_root: &Path,
866    stop: &Stop,
867) -> Result<()> {
868    janitor(&opts.repo, opts, home, worktrees_root).await;
869
870    // The status file is a *snapshot*, not a stream of events: a reader only
871    // ever wants the latest values, and every tick rewrites the whole file
872    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
873    // while an mpsc channel would force the loop to re-send unchanged fields on
874    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
875    // for no gain. The lock is only ever held across a field assignment, never
876    // across an await.
877    let status = Arc::new(Mutex::new(Status::new()));
878    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
879    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
880
881    // Read once at startup, not per task: how many runs this loop drives at
882    // once is a property of the machine running it, not of whichever
883    // repository a given task happens to name - see
884    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
885    // fact in the same sense the agent roster is.
886    let concurrency = max_concurrent(
887        prepare(&opts.repo, opts)
888            .map(|c| c.daemon.max_concurrent_runs)
889            .unwrap_or(1),
890    );
891
892    tracing::info!(
893        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once)",
894        queue.root().display(),
895        opts.poll.as_secs(),
896        opts.max_attempts,
897        concurrency
898    );
899
900    let outcome = poll(
901        opts,
902        queue,
903        &status,
904        home,
905        worktrees_root,
906        stop,
907        concurrency,
908    )
909    .await;
910
911    beat.abort();
912    clear_status_at(status_file);
913    outcome
914}
915
916/// Refresh the status file on a fixed tick.
917///
918/// Separate from the loop because a run takes tens of minutes: a status file
919/// written only between tasks would look stale for the whole of every run, and
920/// a reader would report the daemon dead exactly while it was busiest.
921async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
922    loop {
923        tokio::time::sleep(HEARTBEAT).await;
924        let snapshot = {
925            let mut guard = lock(&status);
926            guard.updated_at = Timestamp::now();
927            guard.clone()
928        };
929        if let Err(e) = write_status_to(&path, &snapshot) {
930            // A failed heartbeat must not take the daemon down: the loop is the
931            // product, the status file is only the window onto it.
932            tracing::warn!("could not refresh the daemon status file: {e:#}");
933        }
934    }
935}
936
937/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
938/// if so, whether that wait is over.
939#[derive(Debug, Clone, Copy, PartialEq, Eq)]
940enum LandResume {
941    /// The task's last run is not parked on a land approval; schedule it
942    /// like any other candidate.
943    NotLanding,
944    /// Parked in `land`, waiting on a question nobody has answered yet.
945    /// Left alone: attempting it now would only re-observe the same pull
946    /// request and park again, spending a `gh` call on a decision that has
947    /// not changed since the last time this was checked.
948    StillWaiting,
949    /// Parked in `land`, and the question is settled - answered or
950    /// abandoned. Resuming this is the one kind of candidate that must not
951    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
952    Ready,
953}
954
955/// Classify a runnable candidate by whether it is parked on a land-merge
956/// approval. Read-only - no claim taken, nothing written - so it is cheap
957/// enough to call on every candidate, every poll.
958fn land_resume_state(task: &Task) -> LandResume {
959    let Some(run_id) = task.runs.last() else {
960        return LandResume::NotLanding;
961    };
962    let Ok(state) = RunState::load(run_id) else {
963        return LandResume::NotLanding;
964    };
965    if state.status != RunStatus::Landing || !state.parked {
966        return LandResume::NotLanding;
967    }
968    let store = ask::Questions::open();
969    let waiting = store
970        .list()
971        .into_iter()
972        .filter(|q| &q.run == run_id && q.node == land::APPROVAL_NODE)
973        .max_by(|a, b| a.id.cmp(&b.id));
974    let Some(mut q) = waiting else {
975        return LandResume::Ready;
976    };
977    if !q.status.open() {
978        return LandResume::Ready;
979    }
980    // `ask::ask_and_wait`'s own deadline is what used to retire a question
981    // nobody ever answered; land's approval bypasses that wait entirely (see
982    // `land::approval_gate`), so the same deadline has to be enforced here
983    // instead, or `graph.answer_timeout` silently stops meaning anything for
984    // a land approval and a run can sit `StillWaiting` forever with nobody
985    // told to look at it.
986    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
987    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
988    if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
989        q.abandon(format!(
990            "no answer within {}s of asking",
991            timeout.as_secs().max(1)
992        ));
993        // If this can't be persisted, do not treat the wait as settled on a
994        // guess: fall through and try again next poll.
995        if store.put(&mut q).is_ok() {
996            return LandResume::Ready;
997        }
998    }
999    LandResume::StillWaiting
1000}
1001
1002/// How often the loop rechecks for new work while something it already
1003/// started is still running, rather than sleeping out the whole
1004/// [`Opts::poll`] interval.
1005///
1006/// Short on purpose: this is what lets a land-merge approval that comes back
1007/// while another task is mid-competition be noticed and resumed within a
1008/// fraction of a second, not within the next multi-second poll.
1009const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
1010
1011/// Frees one attempt's concurrency slot - `Stop`'s busy count and its entry
1012/// in `Status::current` - on drop, so both are released even if the attempt
1013/// panics rather than returning.
1014///
1015/// A `Drop` impl rather than statements written after the `.await` it
1016/// guards: a panic unwinds straight past code placed "after" a call, and
1017/// `Runner::execute`'s chain reaches deep enough into agent-output parsing
1018/// that ruling a panic out there is not a bet this loop can make. Without
1019/// this, one panicking run would leave [`Stop::busy_now`] stuck `true`
1020/// forever - the idle branch in [`poll`], and with it the janitor, would
1021/// never run again - and a ghost entry in `Status::current` naming a task
1022/// nothing is still working on.
1023struct InFlightGuard<'a> {
1024    status: &'a Arc<Mutex<Status>>,
1025    stop: &'a Stop,
1026    task_id: &'a str,
1027}
1028
1029impl Drop for InFlightGuard<'_> {
1030    fn drop(&mut self) {
1031        lock(self.status).current.retain(|c| c.task != self.task_id);
1032        self.stop.exit();
1033    }
1034}
1035
1036/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
1037/// teardown and cannot skip the teardown on an early return.
1038///
1039/// `max_concurrent` bounds how many *ordinary* candidates run at once - see
1040/// [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a land
1041/// approval that has since been answered is dispatched outside that bound
1042/// the moment [`land_resume_state`] reports it [`LandResume::Ready`]: the
1043/// whole point of parking there is that it must not queue behind whatever
1044/// else the loop happens to be running, even at the default of one.
1045async fn poll(
1046    opts: &Opts,
1047    queue: &Queue,
1048    status: &Arc<Mutex<Status>>,
1049    home: &Path,
1050    worktrees_root: &Path,
1051    stop: &Stop,
1052    max_concurrent: usize,
1053) -> Result<()> {
1054    // Only consulted by `once`, where a task that just failed is still
1055    // `runnable` and would otherwise be picked up again inside the same drain.
1056    // In the long-running mode a later poll retrying a failed task is the point,
1057    // and the attempt counter is what bounds it.
1058    let mut attempted: Vec<String> = Vec::new();
1059    let sem = Arc::new(tokio::sync::Semaphore::new(max_concurrent));
1060    // A quota hit is a fact about the machine, not the task that happened to
1061    // surface it, and every other *ordinary* candidate is no less likely to
1062    // hit the same wall - see the warning below. A land-merge resume is
1063    // exempt: it is a human decision finishing, not a fresh competition, and
1064    // must not sit out a quota cooldown it did not cause.
1065    let quota_cooldown_until: Arc<Mutex<Option<Timestamp>>> = Arc::new(Mutex::new(None));
1066    let mut inflight: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
1067
1068    while !stop.stopped() {
1069        lock(status).polls += 1;
1070
1071        // Reap whatever finished since the last tick without blocking on
1072        // anything still running. `InFlightGuard` already released the slot
1073        // even if the spawned attempt panicked; this only surfaces that it
1074        // happened, since a panic swallowed here otherwise leaves no trace.
1075        while let Some(result) = inflight.try_join_next() {
1076            if let Err(e) = result {
1077                tracing::error!("a spawned attempt did not finish cleanly: {e}");
1078            }
1079        }
1080
1081        let swept = sweep_stale_claims(queue, STALE_CLAIM);
1082        if !swept.is_empty() {
1083            tracing::warn!(
1084                "swept {} stale claim(s) left behind by an earlier daemon: {}",
1085                swept.len(),
1086                swept.join(", ")
1087            );
1088        }
1089        let reclaimed = reclaim_orphaned_running(queue, opts.max_attempts);
1090        if !reclaimed.is_empty() {
1091            tracing::warn!(
1092                "reclaimed {} task(s) left `running` by a daemon that never \
1093                 recorded the outcome: {}",
1094                reclaimed.len(),
1095                reclaimed.join(", ")
1096            );
1097        }
1098
1099        let candidates: Vec<Task> = runnable(queue)
1100            .into_iter()
1101            .filter(|t| !opts.once || !attempted.contains(&t.id))
1102            .collect();
1103
1104        let cooling_down =
1105            lock(&quota_cooldown_until).is_some_and(|until| Timestamp::now() < until);
1106
1107        let mut started_any = false;
1108        for candidate in candidates {
1109            if stop.stopped() {
1110                break;
1111            }
1112
1113            let resume = land_resume_state(&candidate);
1114            if resume == LandResume::StillWaiting {
1115                continue;
1116            }
1117            let priority = resume == LandResume::Ready;
1118
1119            if !priority && cooling_down {
1120                continue;
1121            }
1122            let permit = if priority {
1123                None
1124            } else {
1125                match Arc::clone(&sem).try_acquire_owned() {
1126                    Ok(p) => Some(p),
1127                    // No ordinary slot free right now. A later candidate in
1128                    // this same list might still be a priority resume, so
1129                    // keep looking rather than stopping here.
1130                    Err(_) => continue,
1131                }
1132            };
1133
1134            // A claim we cannot take means another daemon, or a human running
1135            // `magi run`, got there first. That is not the task's fault and
1136            // must not spend one of its attempts: move to the next candidate
1137            // rather than recording a failure.
1138            let Ok(claim) = queue.claim(&candidate.id) else {
1139                tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
1140                continue;
1141            };
1142            // Re-read under the claim: the task on disk may have been held or
1143            // edited between the listing and the lock.
1144            let mut task = match queue.get(&candidate.id) {
1145                Ok(t) if t.status.runnable() => t,
1146                Ok(_) => continue,
1147                Err(e) => {
1148                    tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
1149                    continue;
1150                }
1151            };
1152            let task_id = task.id.clone();
1153            attempted.push(task_id.clone());
1154            lock(status).idle = false;
1155            // A stop asked for from here on is "finishing", not "stopped": the
1156            // run gets to reach a terminal status before the loop returns.
1157            stop.enter();
1158            started_any = true;
1159
1160            let opts = opts.clone();
1161            let queue = queue.clone();
1162            let status = Arc::clone(status);
1163            let stop = stop.clone();
1164            let quota_cooldown_until = Arc::clone(&quota_cooldown_until);
1165            inflight.spawn(async move {
1166                // Held for the whole attempt: dropping either at the end of
1167                // this task is what releases the claim and, for an ordinary
1168                // candidate, frees its concurrency slot back to the loop.
1169                let _claim = claim;
1170                let _permit = permit;
1171                // See `InFlightGuard`: this must survive a panic inside `attempt`.
1172                let _inflight = InFlightGuard {
1173                    status: &status,
1174                    stop: &stop,
1175                    task_id: &task_id,
1176                };
1177                let quota = attempt(&opts, &queue, &status, &stop, &mut task).await;
1178                lock(&status).completed += 1;
1179                // A quota loss is a fact about the machine, not this task, and
1180                // the next ordinary candidate the loop offers is no less
1181                // likely to hit the same wall: without a cooldown here a
1182                // whole backlog can be run - and failed - in the seconds it
1183                // takes each attempt to notice the CLI is out of quota.
1184                if !quota.is_empty() {
1185                    let hint = quota.iter().find_map(|q| q.reset.as_deref());
1186                    let reset_at = hint.and_then(|h| parse_reset_hint(h, Timestamp::now()));
1187                    let wait = quota_wait(
1188                        reset_at,
1189                        Timestamp::now(),
1190                        QUOTA_WAIT_FALLBACK,
1191                        QUOTA_WAIT_CAP,
1192                    );
1193                    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
1194                    let until = Timestamp::now()
1195                        .checked_add(jiff::SignedDuration::from_secs(secs))
1196                        .unwrap_or(Timestamp::MAX);
1197                    *lock(&quota_cooldown_until) = Some(until);
1198                    match hint {
1199                        Some(h) => tracing::warn!(
1200                            "quota hit; waiting {}s before taking another ordinary task \
1201                             (CLI reported reset: {h})",
1202                            wait.as_secs()
1203                        ),
1204                        None => tracing::warn!(
1205                            "quota hit; waiting {}s before taking another ordinary task \
1206                             (no reset hint reported)",
1207                            wait.as_secs()
1208                        ),
1209                    }
1210                }
1211            });
1212        }
1213
1214        if started_any {
1215            continue;
1216        }
1217
1218        if stop.busy_now() {
1219            // Something started on an earlier tick is still running. Recheck
1220            // soon rather than sleeping out the whole poll interval - a freed
1221            // slot, or a land approval answered mid-run, must not sit idle
1222            // for it.
1223            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
1224            continue;
1225        }
1226
1227        // Truly idle: nothing new to start and nothing still running. The
1228        // disk is quiet, so this is the point for the janitor - folding
1229        // worktrees and pruning a cache while a sibling run is still
1230        // building would race the very compile the prune exists to keep,
1231        // which concurrent runs make possible in a way the old one-at-a-time
1232        // loop never had to guard against.
1233        janitor(&opts.repo, opts, home, worktrees_root).await;
1234        lock(status).idle = true;
1235        if opts.once {
1236            break;
1237        }
1238        stop.idle(opts.poll).await;
1239    }
1240
1241    // Never return while a run is still in flight, whichever way the loop
1242    // above exited: a stop only sets a flag - see `serve_until` - and
1243    // returning here while `inflight` still holds spawned work would abandon
1244    // it exactly as a mid-node kill would.
1245    while let Some(result) = inflight.join_next().await {
1246        if let Err(e) = result {
1247            tracing::error!("a spawned attempt did not finish cleanly: {e}");
1248        }
1249    }
1250    Ok(())
1251}
1252
1253/// Run one claimed task to a terminal status and record the outcome.
1254///
1255/// Every transition is flushed to the queue as it happens, so the state on disk
1256/// is what actually occurred rather than what this process still intends to
1257/// write.
1258async fn attempt(
1259    opts: &Opts,
1260    queue: &Queue,
1261    status: &Arc<Mutex<Status>>,
1262    stop: &Stop,
1263    task: &mut Task,
1264) -> Vec<QuotaLoss> {
1265    let repo = repo_for(task, &opts.repo);
1266    tracing::info!(
1267        "task {} — {} (repo {})",
1268        task.short(),
1269        task.title,
1270        repo.display()
1271    );
1272
1273    let mut config = match prepare(&repo, opts) {
1274        Ok(c) => c,
1275        Err(e) => {
1276            // A setup failure spends an attempt even though no run was minted.
1277            // Without that, a task naming a repository that does not exist
1278            // would be retried at every poll for as long as the daemon lives.
1279            task.attempts += 1;
1280            task.fail(format!("config: {e:#}"), opts.max_attempts);
1281            record(queue, task);
1282            return Vec::new();
1283        }
1284    };
1285    apply_solo(&mut config, task);
1286
1287    // The free-space gate, checked *before* anything is minted: a task that
1288    // waits out a full disk costs nothing yet, and must not spend an attempt
1289    // or start a run the machine cannot finish. Held tasks stay in the list
1290    // for the human to see, and `magi task release` re-queues them when space
1291    // comes back - the same recovery as any other hold. A volume whose free
1292    // space cannot be measured closes the gate too: starting a run blind on a
1293    // disk that may be full is how the machine ends up with 6.7 GB free.
1294    if let Some(reason) = disk_gate(&repo, &config) {
1295        task.last_error = Some(reason.clone());
1296        task.hold(Some(reason.clone()));
1297        record(queue, task);
1298        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
1299        return Vec::new();
1300    }
1301
1302    // A resumable run of this task is carried on, never re-competed. The
1303    // candidates are built and paid for, and a fresh competition races a
1304    // second implementation against them.
1305    //
1306    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
1307    // started 3cbf on the same task a moment later, duplicating two and a
1308    // half hours of agent work. Then b25f stalled on a judge that timed out
1309    // and one that answered with no JSON - `quota: 0`, so nothing the machine
1310    // was to blame for - and 4043 started **one second** later, buying three
1311    // fresh implementations to reach the same panel. `RunStatus::resumable`
1312    // rather than `!done()` is what catches the second case: a stall is
1313    // terminal, and its cheap recovery re-asks only the absent seats.
1314    let unfinished = task
1315        .runs
1316        .iter()
1317        .rev()
1318        .find(|id| {
1319            RunState::load(id)
1320                .map(|s| s.status.resumable())
1321                .unwrap_or(false)
1322        })
1323        .cloned();
1324    let started = match &unfinished {
1325        Some(id) => {
1326            tracing::info!("resuming run {id} rather than competing again");
1327            Runner::resume(id)
1328        }
1329        None => Runner::start(&repo, task.instruction.clone(), config).await,
1330    };
1331    let mut runner = match started {
1332        Ok(r) => r,
1333        Err(e) => {
1334            task.attempts += 1;
1335            task.fail(format!("could not start the run: {e:#}"), opts.max_attempts);
1336            record(queue, task);
1337            return Vec::new();
1338        }
1339    };
1340    // A stop that means "park" reaches the graph through this handle.
1341    runner.on_pause(stop.pause());
1342
1343    // `start` has minted the run, so the task can now point at it. Persisting
1344    // `Running` before `execute` is what makes a crash mid-run legible.
1345    let run = runner.state.id.clone();
1346    task.start(run.clone());
1347    record(queue, task);
1348    lock(status).current.push(Current {
1349        task: task.id.clone(),
1350        run,
1351    });
1352
1353    let detail = match runner.execute().await {
1354        Ok(()) => describe(&runner.state),
1355        Err(e) => format!("{e:#}"),
1356    };
1357    let verdict = Verdict {
1358        status: runner.state.status,
1359        // A run that opened a pull request handed its work over, whatever the
1360        // gate then decided about merging it.
1361        left_pr: runner.state.pr.is_some(),
1362        // Only a rate limit earns the task its attempt back.
1363        quota_hit: !runner.state.quota.is_empty(),
1364        // A run that parked was asked to stop; that is not a failure and must
1365        // not spend an attempt, or replacing the binary a few times would
1366        // exhaust a task's budget without an agent ever misbehaving.
1367        parked: runner.state.parked,
1368        // A quota loss that left nothing viable is the same machine fact as a
1369        // `Stalled` quota loss; see `settle`'s doc table.
1370        no_viable_candidates: runner.state.viable().is_empty(),
1371    };
1372    settle_and_diagnose(task, verdict, &detail, opts.max_attempts, &runner.state);
1373    record(queue, task);
1374    tracing::info!(
1375        "task {} is {} after run {} ({})",
1376        task.short(),
1377        task.status.as_str(),
1378        runner.state.short(),
1379        label(runner.state.status)
1380    );
1381    runner.state.quota
1382}
1383
1384/// Cut this attempt's candidate count to one when the task asked to run
1385/// alone.
1386///
1387/// Pure and separate from [`attempt`] so the one thing this feature changes -
1388/// which `candidates` a `solo` task's run is built with - can be asserted
1389/// without minting a run: `attempt` drives `graph::Runner`, which spawns real
1390/// agent CLIs, and no test may do that. `config` is mutated in place, taken by
1391/// value from the caller's own copy, so a repository's `magi.toml` on disk is
1392/// never touched - only the `Config` this one attempt hands to `Runner::start`.
1393fn apply_solo(config: &mut Config, task: &Task) {
1394    if task.solo {
1395        config.graph.candidates = 1;
1396    }
1397}
1398
1399/// Load the config for a task's repository, with the merge override applied.
1400fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
1401    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
1402    if let Some(mode) = &opts.merge {
1403        config.merge.mode = merge_mode(mode)?;
1404    }
1405    Ok(config)
1406}
1407
1408/// The disk janitor, with its housekeeping logged rather than fatal.
1409///
1410/// Called only at the loop's idle points, for the reason the caller documents:
1411/// a prune racing a live compile would delete files mid-build. The config is
1412/// re-read on every call because the repository that just ran may not be the
1413/// daemon's own default, and the cache directory is a repository fact.
1414///
1415/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
1416/// and [`crate::run::default_worktree_root`] read here, for the same reason
1417/// [`drive`] takes its queue and status file rather than resolving them: a
1418/// test driving the loop must not reach through to the operator's real home
1419/// or worktree bay just because the janitor runs on every idle tick.
1420/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
1421/// to get wrong silently - a test's `home` was already isolated, but nothing
1422/// exercised the parameter next to it, so a real worktree bay stayed wired in
1423/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
1424/// it for real, every test in this file that drives the loop at all started
1425/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
1426async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
1427    let cfg = match prepare(repo, opts) {
1428        Ok(cfg) => cfg,
1429        Err(e) => {
1430            tracing::warn!("housekeep: no config: {e:#}");
1431            return;
1432        }
1433    };
1434    // A run's own worktree lives under `config.graph.worktree_root` when the
1435    // repository sets one - the same precedence `RunState::worktree_root`
1436    // uses - and `worktrees_root` only stands in for the *default* an
1437    // unconfigured repository resolves to (see this function's own
1438    // parameter, or the test fixture wiring one to a fake path). Housekeeping
1439    // that always swept the default regardless of this override would never
1440    // see, and so never reclaim, a single worktree for a repository that
1441    // relocated them elsewhere.
1442    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
1443    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
1444    // Reported whenever there is anything to say, not only when `folded > 0`:
1445    // the incident this exists to prevent was 90 of 93 runs skipped and 0
1446    // folded, on every single pass, for months - a report gated on `folded`
1447    // would have stayed silent through every one of them.
1448    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
1449        let mut extra = Vec::new();
1450        if out.unreadable > 0 {
1451            extra.push(format!("{} unreadable", out.unreadable));
1452        }
1453        if out.orphaned_worktrees > 0 {
1454            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
1455        }
1456        let detail = if extra.is_empty() {
1457            String::new()
1458        } else {
1459            format!(" ({})", extra.join(", "))
1460        };
1461        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
1462    }
1463    if out.cache_files > 0 {
1464        tracing::info!(
1465            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
1466            out.cache_files,
1467            out.cache_freed
1468        );
1469    }
1470    if out.questions_abandoned > 0 {
1471        tracing::info!(
1472            "housekeep: abandoned {} question(s) left open by a finished run",
1473            out.questions_abandoned
1474        );
1475    }
1476}
1477
1478/// The free-space gate: what stands between this task and a new run, if
1479/// anything. `Some(reason)` holds the task; `None` lets it start.
1480///
1481/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
1482/// the operator opted out. A measurement failure is a gate, not a pass: both
1483/// sides of "cannot tell" are served by not starting.
1484fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
1485    let min = config.disk.min_free_bytes;
1486    if min == 0 {
1487        return None;
1488    }
1489    match crate::disk::free_bytes(repo) {
1490        Ok(free) => crate::disk::gate(free, min),
1491        Err(e) => Some(format!(
1492            "could not measure free space on {} ({e}); the disk gate refuses \
1493             to let a run start blind",
1494            repo.display()
1495        )),
1496    }
1497}
1498
1499/// How long to wait before offering another task when a run lost a seat to a
1500/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
1501/// could read, or carried nothing at all. Long enough that a quota outage
1502/// cannot burn through a whole backlog in the few seconds each doomed attempt
1503/// takes to fail; short enough that a quota which clears early is not left
1504/// idle for the fallback's sake.
1505const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
1506
1507/// Longest a parsed reset hint may push the wait out to. The hint comes from
1508/// the CLI's own words, not a contract, so a parsing slip that lands a day
1509/// away must not leave the loop asleep for a day.
1510const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
1511
1512/// How long [`poll`] should wait before offering the next task, after a run
1513/// lost at least one seat to a rate limit.
1514///
1515/// Pure and separate from the loop so the policy can be exercised without a
1516/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
1517/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
1518/// nothing to parse, or the parsed time has already passed; `cap` bounds how
1519/// far a parsed hint is trusted to push the wait out.
1520fn quota_wait(
1521    reset_at: Option<Timestamp>,
1522    now: Timestamp,
1523    fallback: Duration,
1524    cap: Duration,
1525) -> Duration {
1526    match reset_at {
1527        Some(at) if at > now => {
1528            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
1529            Duration::from_secs(secs).min(cap)
1530        }
1531        _ => fallback,
1532    }
1533}
1534
1535/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
1536///
1537/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
1538/// explains why parsing it exactly "would be a bug factory" — so this only
1539/// recognises the one shape actually observed in the wild, `"H:MMam/pm
1540/// (Zone)"`, and returns `None` for anything else rather than guess at a
1541/// format nobody has seen. A clock reading already past today is read as
1542/// tomorrow's: a CLI naming a same-day reset that has already gone by means
1543/// the window rolled over while nothing was watching.
1544fn parse_reset_hint(text: &str, now: Timestamp) -> Option<Timestamp> {
1545    let open = text.find('(')?;
1546    let close = text.rfind(')')?;
1547    if close <= open {
1548        return None;
1549    }
1550    let zone = text[open + 1..close].trim();
1551    let clock = text[..open].trim().to_lowercase();
1552    let (digits, pm) = clock
1553        .strip_suffix("am")
1554        .map(|d| (d, false))
1555        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
1556    let (h, m) = digits.trim().split_once(':')?;
1557    let mut hour: i8 = h.trim().parse().ok()?;
1558    let minute: i8 = m.trim().parse().ok()?;
1559    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
1560        return None;
1561    }
1562    if pm && hour != 12 {
1563        hour += 12;
1564    } else if !pm && hour == 12 {
1565        hour = 0;
1566    }
1567    let tz = jiff::tz::TimeZone::get(zone).ok()?;
1568    let candidate = now
1569        .to_zoned(tz)
1570        .with()
1571        .hour(hour)
1572        .minute(minute)
1573        .second(0)
1574        .millisecond(0)
1575        .microsecond(0)
1576        .nanosecond(0)
1577        .build()
1578        .ok()?;
1579    let mut at = candidate.timestamp();
1580    if at <= now {
1581        at += jiff::SignedDuration::from_hours(24);
1582    }
1583    Some(at)
1584}
1585
1586/// Which repository a task runs in. A task that names none — the normal case
1587/// for one filed from a phone — runs in the daemon's own default.
1588fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
1589    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
1590        return fallback.to_path_buf();
1591    }
1592    task.repo.clone()
1593}
1594
1595/// Persist a transition. A queue write failure is logged rather than fatal: the
1596/// run already happened, and taking the daemon down would only add a lost
1597/// backlog to a full disk.
1598fn record(queue: &Queue, task: &mut Task) {
1599    if let Err(e) = queue.put(task) {
1600        tracing::error!("could not record task {}: {e:#}", task.short());
1601    }
1602}
1603
1604/// Every runnable task, in the order the loop should try them.
1605///
1606/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
1607/// tail exists so that a claim somebody else holds costs the loop the next
1608/// candidate rather than a whole poll interval of idleness.
1609fn runnable(queue: &Queue) -> Vec<Task> {
1610    let mut tasks: Vec<Task> = queue
1611        .list()
1612        .into_iter()
1613        .filter(|t| t.status.runnable())
1614        .collect();
1615    tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
1616    tasks
1617}
1618
1619/// Why a run ended where it did, in one line, for [`Task::last_error`].
1620///
1621/// A stalled run names the seats the quota took out: "out of quota" is not
1622/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
1623/// agent to replace or which plan to top up.
1624fn describe(state: &RunState) -> String {
1625    let mut detail = if state.status == RunStatus::Stalled {
1626        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
1627        seats.sort_unstable();
1628        seats.dedup();
1629        if seats.is_empty() {
1630            "the judging panel lost its quorum".to_owned()
1631        } else {
1632            format!(
1633                "the judging panel lost its quorum; quota took out {}",
1634                seats.join(", ")
1635            )
1636        }
1637    } else {
1638        format!("run ended {}", label(state.status))
1639    };
1640    if let Some(last) = state.events.last() {
1641        detail.push_str(&format!(" ({}: {})", last.node, last.message));
1642    }
1643    detail.push_str(&format!(" [run {}]", state.id));
1644    detail
1645}
1646
1647/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
1648///
1649/// The task file lives in the backlog indefinitely; a diagnostic is an
1650/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
1651/// stay small regardless of how much a gate command or a candidate printed.
1652const DIAGNOSTIC_MAX: usize = 4_000;
1653
1654/// Tail kept from a single failing command's output inside a diagnostic.
1655/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
1656/// pointer for a human deciding whether to go read the full artifact by hand,
1657/// not a replacement for reading it.
1658const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
1659
1660/// Assemble a bounded diagnostic excerpt from a held task's own run, so
1661/// `magi task show` says more than the one-line reason in [`describe`].
1662///
1663/// The one-liner answers "where did the run stop"; this answers "what would a
1664/// human have found opening `artifacts/` by hand" — the point of the whole
1665/// feature is the case that one-liner actively misleads on: a run held as "no
1666/// candidate produced a change" can mean the implementer actually finished
1667/// the task (opened a PR, merged it, tagged a release) and only left a clean
1668/// local worktree behind, which reads as "nothing happened" unless someone
1669/// goes and reads what the agent actually said. `None` when the run carries
1670/// none of the three shapes this recognises — an ordinary run held for
1671/// something not diagnosable from `RunState` alone still explains itself
1672/// through `Task::last_error`.
1673fn diagnostic(state: &RunState) -> Option<String> {
1674    let mut parts: Vec<String> = Vec::new();
1675
1676    // Gate failure: which check(s), and the tail of what each printed.
1677    for o in state.gate.iter().filter(|o| !o.ok()) {
1678        parts.push(format!(
1679            "gate `{}` failed ({:?}):\n{}",
1680            o.command,
1681            o.code,
1682            crate::run::tail(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
1683        ));
1684    }
1685
1686    // The land loop gave up because the fixer declined while checks were
1687    // still red: the message already names them (see `land::run`).
1688    if let Some(last) = state
1689        .events
1690        .iter()
1691        .rev()
1692        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
1693    {
1694        parts.push(last.message.clone());
1695    }
1696
1697    // No viable candidate: every implementer's own final word, sanitized the
1698    // same way a judge would have read it, so a run that actually finished
1699    // the job does not read as an unexplained failure.
1700    if state.viable().is_empty() {
1701        for c in &state.candidates {
1702            if !c.summary.trim().is_empty() {
1703                parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
1704            } else if let Some(why) = &c.failed {
1705                parts.push(format!("candidate {}: {why}", c.label));
1706            }
1707        }
1708    }
1709
1710    if parts.is_empty() {
1711        return None;
1712    }
1713    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
1714    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
1715    // back slightly over. Leave it enough room to always land under the
1716    // limit.
1717    Some(crate::run::tail(
1718        &parts.join("\n\n"),
1719        DIAGNOSTIC_MAX.saturating_sub(100),
1720    ))
1721}
1722
1723/// Stable lower-case name for a run status, for logs and task errors.
1724/// One definition of a status's name, on the type that owns it: this table
1725/// used to live here as a second copy, and a status renamed in one place would
1726/// have gone on reading correctly in the other.
1727fn label(status: RunStatus) -> &'static str {
1728    status.as_str()
1729}
1730
1731/// Parse a merge mode override.
1732fn merge_mode(mode: &str) -> Result<MergeMode> {
1733    match mode {
1734        "none" => Ok(MergeMode::None),
1735        "local" => Ok(MergeMode::Local),
1736        "pr" => Ok(MergeMode::Pr),
1737        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
1738    }
1739}
1740
1741/// Take the status lock, recovering from a poisoned one.
1742///
1743/// A panic elsewhere must not silently stop the heartbeat: the status is plain
1744/// data, and the worst a poisoned lock can hold is a stale timestamp.
1745fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
1746    mutex
1747        .lock()
1748        .unwrap_or_else(std::sync::PoisonError::into_inner)
1749}
1750
1751#[cfg(test)]
1752mod tests {
1753    use super::*;
1754    use crate::queue::{Source, TaskStatus};
1755    use crate::run::{Candidate, CommandOutcome};
1756    use pretty_assertions::assert_eq;
1757
1758    fn task() -> Task {
1759        Task::new(
1760            "add retries".to_owned(),
1761            "add retries".to_owned(),
1762            PathBuf::from("/repo"),
1763            Source::Human,
1764        )
1765    }
1766
1767    #[test]
1768    fn every_run_status_settles_the_task_it_came_from() {
1769        // run status, resulting task status, attempts still standing after one
1770        let table = [
1771            (RunStatus::Merged, TaskStatus::Done, 1),
1772            (RunStatus::Ready, TaskStatus::Done, 1),
1773            (RunStatus::Stalled, TaskStatus::Failed, 0),
1774            (RunStatus::Blocked, TaskStatus::Failed, 1),
1775            (RunStatus::Failed, TaskStatus::Failed, 1),
1776            (RunStatus::Prep, TaskStatus::Failed, 1),
1777            (RunStatus::Implementing, TaskStatus::Failed, 1),
1778            (RunStatus::Judging, TaskStatus::Failed, 1),
1779            (RunStatus::Deliberating, TaskStatus::Failed, 1),
1780            (RunStatus::Voting, TaskStatus::Failed, 1),
1781            (RunStatus::Reviewing, TaskStatus::Failed, 1),
1782            (RunStatus::Gating, TaskStatus::Failed, 1),
1783        ];
1784        for (run, want, attempts) in table {
1785            let mut t = task();
1786            t.start("20260902-000000-aaaa".to_owned());
1787            settle(
1788                &mut t,
1789                Verdict {
1790                    status: run,
1791                    left_pr: false,
1792                    parked: false,
1793                    quota_hit: matches!(run, RunStatus::Stalled),
1794                    no_viable_candidates: false,
1795                },
1796                "why",
1797                2,
1798            );
1799            assert_eq!(t.status, want, "task status after {}", label(run));
1800            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
1801        }
1802    }
1803
1804    #[test]
1805    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
1806        let mut stalled = task();
1807        stalled.start("20260902-000000-aaaa".to_owned());
1808        settle(
1809            &mut stalled,
1810            Verdict {
1811                status: RunStatus::Stalled,
1812                left_pr: false,
1813                parked: false,
1814                quota_hit: true,
1815                no_viable_candidates: false,
1816            },
1817            "quota",
1818            1,
1819        );
1820        assert_eq!(stalled.attempts, 0);
1821        assert!(
1822            stalled.status.runnable(),
1823            "a machine problem must leave the task in line"
1824        );
1825
1826        let mut blocked = task();
1827        blocked.start("20260902-000000-aaaa".to_owned());
1828        settle(
1829            &mut blocked,
1830            Verdict {
1831                status: RunStatus::Blocked,
1832                left_pr: false,
1833                parked: false,
1834                quota_hit: false,
1835                no_viable_candidates: false,
1836            },
1837            "findings open",
1838            1,
1839        );
1840        assert_eq!(blocked.attempts, 1);
1841        assert_eq!(
1842            blocked.status,
1843            TaskStatus::Held,
1844            "the last attempt hands the task to a human"
1845        );
1846    }
1847
1848    #[test]
1849    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
1850        // Attempts to spare: without the pull request this task would go
1851        // straight back in line and run the whole competition again.
1852        let mut delivered = task();
1853        delivered.start("20260903-080619-01c2".to_owned());
1854        settle(
1855            &mut delivered,
1856            Verdict {
1857                status: RunStatus::Blocked,
1858                left_pr: true,
1859                parked: false,
1860                quota_hit: false,
1861                no_viable_candidates: false,
1862            },
1863            "no check status",
1864            4,
1865        );
1866        assert_eq!(
1867            delivered.status,
1868            TaskStatus::Held,
1869            "a pull request waiting on CI or a person is not a retryable failure"
1870        );
1871        assert!(
1872            !delivered.status.runnable(),
1873            "the loop must not pick this task up again"
1874        );
1875        assert_eq!(
1876            delivered.last_error.as_deref(),
1877            Some("no check status"),
1878            "the operator needs to be told what the gate was waiting for"
1879        );
1880
1881        // The same status without a pull request is a plain failure, and with
1882        // attempts left it is retried.
1883        let mut empty_handed = task();
1884        empty_handed.start("20260903-080619-01c2".to_owned());
1885        settle(
1886            &mut empty_handed,
1887            Verdict {
1888                status: RunStatus::Blocked,
1889                left_pr: false,
1890                parked: false,
1891                quota_hit: false,
1892                no_viable_candidates: false,
1893            },
1894            "findings open",
1895            4,
1896        );
1897        assert_eq!(empty_handed.status, TaskStatus::Failed);
1898        assert!(empty_handed.status.runnable());
1899    }
1900
1901    #[test]
1902    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
1903        // Parking is the operator asking for the process back - to replace the
1904        // binary, most of all. The run's work is intact on disk, so this is
1905        // not a failed attempt, and charging for it would mean a few upgrades
1906        // could exhaust a budget meant for agents that misbehaved.
1907        let mut parked = task();
1908        parked.start("20260903-183634-2d98".to_owned());
1909        settle(
1910            &mut parked,
1911            Verdict {
1912                status: RunStatus::Implementing,
1913                left_pr: false,
1914                quota_hit: false,
1915                parked: true,
1916                no_viable_candidates: false,
1917            },
1918            "parked after `implementing`",
1919            2,
1920        );
1921        assert_eq!(parked.attempts, 0, "a park is refunded");
1922        assert!(
1923            parked.status.runnable(),
1924            "and the task stays in line so the next loop resumes its run"
1925        );
1926        assert_eq!(
1927            parked.last_error.as_deref(),
1928            Some("parked after `implementing`"),
1929            "the card says where it stopped"
1930        );
1931
1932        // Without the park flag the same non-terminal status is what it always
1933        // was: `execute` returning mid-flight, which is a bug and spends an
1934        // attempt so a task cannot loop on it forever.
1935        let mut broken = task();
1936        broken.start("20260903-183634-2d98".to_owned());
1937        settle(
1938            &mut broken,
1939            Verdict {
1940                status: RunStatus::Implementing,
1941                left_pr: false,
1942                quota_hit: false,
1943                parked: false,
1944                no_viable_candidates: false,
1945            },
1946            "returned mid-flight",
1947            2,
1948        );
1949        assert_eq!(broken.attempts, 1);
1950    }
1951
1952    #[test]
1953    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
1954        // Run e633: quorum lost because two judges answered with the wrong
1955        // JSON shape, `quota: []`. Refunding that takes the bound off the
1956        // retry loop, and each retry pays for a fresh hour-long implement
1957        // wave before it can fail the same way.
1958        let mut flaky = task();
1959        flaky.start("20260903-123023-e633".to_owned());
1960        settle(
1961            &mut flaky,
1962            Verdict {
1963                status: RunStatus::Stalled,
1964                left_pr: false,
1965                parked: false,
1966                quota_hit: false,
1967                no_viable_candidates: false,
1968            },
1969            "verdict rests on 1 of 3 judges",
1970            2,
1971        );
1972        assert_eq!(
1973            flaky.attempts, 1,
1974            "flakiness spends an attempt, so `max_attempts` still bounds it"
1975        );
1976        assert!(flaky.status.runnable(), "and it is still worth retrying");
1977
1978        // The same status, lost to a rate limit, is the machine's fault.
1979        let mut limited = task();
1980        limited.start("20260903-123023-e633".to_owned());
1981        settle(
1982            &mut limited,
1983            Verdict {
1984                status: RunStatus::Stalled,
1985                left_pr: false,
1986                parked: false,
1987                quota_hit: true,
1988                no_viable_candidates: false,
1989            },
1990            "judge-2, judge-3 out of quota",
1991            2,
1992        );
1993        assert_eq!(limited.attempts, 0, "a quota window is refunded");
1994        assert!(limited.status.runnable());
1995
1996        // And the bound really binds: a task that keeps stalling on flakiness
1997        // reaches a human instead of running the roster forever.
1998        let mut worn = task();
1999        for _ in 0..2 {
2000            worn.release();
2001        }
2002        worn.start("20260903-123023-e633".to_owned());
2003        worn.attempts = 2;
2004        settle(
2005            &mut worn,
2006            Verdict {
2007                status: RunStatus::Stalled,
2008                left_pr: false,
2009                parked: false,
2010                quota_hit: false,
2011                no_viable_candidates: false,
2012            },
2013            "no quorum again",
2014            2,
2015        );
2016        assert_eq!(worn.status, TaskStatus::Held);
2017        assert!(!worn.status.runnable());
2018    }
2019
2020    #[test]
2021    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
2022        // The implement wave loses every seat to the same rate limit and
2023        // `after_implement` bails with nothing viable, which surfaces as
2024        // `Failed` rather than `Stalled`. That is the same machine fact the
2025        // `Stalled`-quota row already refunds, and must be refunded the same
2026        // way, or a quota outage quietly holds every task it touches instead
2027        // of leaving them in line for the reset.
2028        let mut wiped_out = task();
2029        wiped_out.start("20260907-025000-a1b2".to_owned());
2030        settle(
2031            &mut wiped_out,
2032            Verdict {
2033                status: RunStatus::Failed,
2034                left_pr: false,
2035                parked: false,
2036                quota_hit: true,
2037                no_viable_candidates: true,
2038            },
2039            "no candidate produced a change; nothing to judge",
2040            2,
2041        );
2042        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
2043        assert!(
2044            wiped_out.status.runnable(),
2045            "a machine problem must leave the task in line"
2046        );
2047
2048        // This is the exemption that must stay narrow: a candidate that did
2049        // produce a change, and then failed for some other reason, still
2050        // spends the attempt even though a seat elsewhere hit its quota.
2051        // Otherwise every ordinary failure that happens to share a run with
2052        // an unrelated rate limit would be refunded for free.
2053        let mut partial_progress = task();
2054        partial_progress.start("20260907-025500-c3d4".to_owned());
2055        settle(
2056            &mut partial_progress,
2057            Verdict {
2058                status: RunStatus::Failed,
2059                left_pr: false,
2060                parked: false,
2061                quota_hit: true,
2062                no_viable_candidates: false,
2063            },
2064            "gate failed on the winning candidate",
2065            2,
2066        );
2067        assert_eq!(
2068            partial_progress.attempts, 1,
2069            "a candidate that actually produced a change spends the attempt \
2070             even though some other seat hit its quota"
2071        );
2072        assert!(partial_progress.status.runnable());
2073    }
2074
2075    #[test]
2076    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
2077        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
2078        // disk, and that construction must reach the same conclusion as the
2079        // one `attempt` builds from a live run, or a crash at exactly the
2080        // wrong moment gives a recovered task a different policy than one a
2081        // daemon finished settling itself.
2082        let mut t = task();
2083        t.start("20260907-025000-a1b2".to_owned());
2084        let mut state = run_state(RunStatus::Failed);
2085        state.quota.push(QuotaLoss {
2086            seat: "cand-a".to_owned(),
2087            node: "implement".to_owned(),
2088            at: Timestamp::now(),
2089            reset: None,
2090        });
2091        assert!(
2092            state.viable().is_empty(),
2093            "no candidate was added, so nothing is viable"
2094        );
2095        reclaim(&mut t, Some(state), 2);
2096        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
2097        assert!(t.status.runnable());
2098    }
2099
2100    #[test]
2101    fn a_held_task_is_never_offered_to_the_loop() {
2102        let dir = tempfile::tempdir().unwrap();
2103        let queue = Queue::at(dir.path().to_path_buf());
2104        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
2105            let mut t = task();
2106            t.id = format!("2026090{n}-000000-000{n}");
2107            t.priority = priority;
2108            queue.put(&mut t).unwrap();
2109        }
2110        let mut held = task();
2111        held.id = "20260909-000000-9999".to_owned();
2112        held.priority = 99;
2113        held.hold(None);
2114        queue.put(&mut held).unwrap();
2115
2116        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
2117        assert_eq!(order.len(), 3);
2118        assert!(!order.contains(&held.id));
2119        assert_eq!(
2120            order.first().cloned(),
2121            queue.next_runnable().map(|t| t.id),
2122            "the loop's first candidate is exactly what the queue offers"
2123        );
2124        assert_eq!(
2125            order,
2126            vec![
2127                "20260902-000000-0002".to_owned(),
2128                "20260903-000000-0003".to_owned(),
2129                "20260901-000000-0001".to_owned(),
2130            ],
2131            "priority first, then oldest, so nothing starves"
2132        );
2133    }
2134
2135    #[test]
2136    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
2137        let dir = tempfile::tempdir().unwrap();
2138        let queue = Queue::at(dir.path().to_path_buf());
2139        let mut old = task();
2140        old.id = "20260101-000000-old0".to_owned();
2141        queue.put(&mut old).unwrap();
2142        let mut fresh = task();
2143        fresh.id = "20260101-000000-new0".to_owned();
2144        queue.put(&mut fresh).unwrap();
2145
2146        // No parseable pid at all, so age is the only signal there is to
2147        // check - unlike a real `Queue::claim`, which always names a real,
2148        // and therefore alive, pid this test cannot fake as dead.
2149        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
2150        std::thread::sleep(Duration::from_millis(60));
2151        let live = queue.claim(&fresh.id).unwrap();
2152
2153        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
2154        assert_eq!(swept, vec![old.id.clone()]);
2155        assert!(
2156            queue.claim(&old.id).is_ok(),
2157            "an unparseable lock older than the threshold is swept"
2158        );
2159        assert!(
2160            queue.claim(&fresh.id).is_err(),
2161            "a live pid protects its lock regardless of age"
2162        );
2163        drop(live);
2164    }
2165
2166    #[test]
2167    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
2168        // The regression this guards: `sweep` now runs concurrently with
2169        // every attempt this daemon itself has spawned (see
2170        // `InFlightGuard`), not only between them the way a single
2171        // sequential loop once did. A run that legitimately outlives
2172        // `older_than` still has this very process's own live pid sitting in
2173        // its own lock file on every later sweep, and deciding by age alone
2174        // would delete that still-valid claim out from under the attempt
2175        // that holds it - which `reclaim_orphaned_running` would then read
2176        // as abandoned and hand to a second, competing attempt.
2177        let dir = tempfile::tempdir().unwrap();
2178        let queue = Queue::at(dir.path().to_path_buf());
2179        let mut t = task();
2180        t.id = "20260101-000000-live".to_owned();
2181        queue.put(&mut t).unwrap();
2182
2183        let claim = queue.claim(&t.id).unwrap();
2184        std::thread::sleep(Duration::from_millis(60));
2185
2186        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
2187        assert!(
2188            swept.is_empty(),
2189            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
2190        );
2191        assert!(
2192            queue.claim(&t.id).is_err(),
2193            "the lock still protects its task"
2194        );
2195        drop(claim);
2196    }
2197
2198    /// A pid past any real process table, but not `u32::MAX`: Windows'
2199    /// `tasklist` answers that one with "invalid query" rather than "no such
2200    /// process", which [`crate::proc::pid_alive`] - correctly - cannot tell
2201    /// apart from a check it simply could not run, so it would read as
2202    /// alive. See `proc::tests` for the same choice made for the same
2203    /// reason.
2204    const DEAD_PID: u32 = 999_999_999;
2205
2206    #[test]
2207    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
2208        let dir = tempfile::tempdir().unwrap();
2209        let queue = Queue::at(dir.path().to_path_buf());
2210        let mut t = task();
2211        t.id = "20260101-000000-dead".to_owned();
2212        queue.put(&mut t).unwrap();
2213
2214        // Written directly rather than through `Queue::claim`, which would
2215        // stamp this test process's own very much alive pid and defeat the
2216        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
2217        // like moments after it died, not six hours later.
2218        std::fs::write(
2219            dir.path().join(format!("{}.lock", t.id)),
2220            DEAD_PID.to_string(),
2221        )
2222        .unwrap();
2223
2224        let swept = sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60));
2225        assert_eq!(
2226            swept,
2227            vec![t.id.clone()],
2228            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
2229        );
2230        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
2231    }
2232
2233    #[test]
2234    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
2235        let dir = tempfile::tempdir().unwrap();
2236        let queue = Queue::at(dir.path().to_path_buf());
2237        let mut t = task();
2238        t.id = "20260101-000000-late".to_owned();
2239        queue.put(&mut t).unwrap();
2240
2241        // Tick one, standing in for the sweep `poll` already runs at
2242        // startup: nothing to find yet.
2243        assert!(
2244            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
2245            "nothing has claimed the task yet"
2246        );
2247
2248        // A second daemon claims the task and dies before it ever writes
2249        // `running`, well after this loop's own startup sweep already ran.
2250        std::fs::write(
2251            dir.path().join(format!("{}.lock", t.id)),
2252            DEAD_PID.to_string(),
2253        )
2254        .unwrap();
2255
2256        // Tick two, standing in for a poll long into this daemon's uptime:
2257        // the same function, called again, notices what only just appeared -
2258        // proving the sweep is not a one-shot startup check.
2259        let swept = sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60));
2260        assert_eq!(swept, vec![t.id.clone()]);
2261    }
2262
2263    #[test]
2264    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
2265        // `reclaim_orphaned_running` looks up the task's last run, which
2266        // touches `run::home()`; the first call anywhere in this binary wins,
2267        // so this is a no-op if another test already pinned one, and either
2268        // way the run id below is never written under it.
2269        crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
2270        let dir = tempfile::tempdir().unwrap();
2271        let queue = Queue::at(dir.path().to_path_buf());
2272        let mut t = task();
2273        t.id = "20260101-000000-crsh".to_owned();
2274        t.status = TaskStatus::Running;
2275        t.attempts = 1;
2276        // No `run.json` behind this id: standing in for a run this test does
2277        // not need to make readable, since the point is the lock, not the
2278        // recovery table `reclaim` already has its own tests for.
2279        t.runs.push("20260904-000000-4043".to_owned());
2280        queue.put(&mut t).unwrap();
2281
2282        // The crashed daemon's own claim, naming a pid nothing on the
2283        // machine holds anymore.
2284        std::fs::write(
2285            dir.path().join(format!("{}.lock", t.id)),
2286            DEAD_PID.to_string(),
2287        )
2288        .unwrap();
2289
2290        // Before the lock is swept the task looks claimed, and
2291        // `reclaim_orphaned_running` must leave it alone - this is exactly
2292        // the bug: a `running` task stranded behind a dead daemon's lock,
2293        // invisible to the claim-as-proof check because the lock outlived
2294        // the process that wrote it.
2295        assert!(reclaim_orphaned_running(&queue, 2).is_empty());
2296        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
2297
2298        let swept = sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60));
2299        assert_eq!(swept, vec![t.id.clone()]);
2300
2301        let reclaimed = reclaim_orphaned_running(&queue, 2);
2302        assert_eq!(reclaimed, vec![t.id.clone()]);
2303        let after = queue.get(&t.id).unwrap();
2304        assert_eq!(
2305            after.status,
2306            TaskStatus::Held,
2307            "no run.json to recover from, so a human is asked"
2308        );
2309        assert_eq!(
2310            after.runs,
2311            vec!["20260904-000000-4043".to_owned()],
2312            "the crashed run's id is kept as evidence, not discarded"
2313        );
2314    }
2315
2316    fn run_state(status: RunStatus) -> RunState {
2317        let mut state = RunState::new(
2318            PathBuf::from("/repo"),
2319            "main".to_owned(),
2320            "abc1234def".to_owned(),
2321            "add retries".to_owned(),
2322            Config::default(),
2323        );
2324        state.status = status;
2325        state
2326    }
2327
2328    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
2329        Candidate {
2330            index: 0,
2331            label,
2332            agent: "claude".to_owned(),
2333            branch: format!("magi/x/{label}"),
2334            worktree: PathBuf::from("/repo"),
2335            summary: summary.to_owned(),
2336            stat: String::new(),
2337            files: 0,
2338            commits: usize::from(!empty),
2339            empty,
2340            failed: failed.map(str::to_owned),
2341            duration_ms: 0,
2342            folded: false,
2343        }
2344    }
2345
2346    #[test]
2347    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
2348        let mut state = run_state(RunStatus::Blocked);
2349        state.gate = vec![
2350            CommandOutcome {
2351                command: "cargo make check".to_owned(),
2352                code: Some(0),
2353                output_tail: "ok".to_owned(),
2354                duration_ms: 0,
2355            },
2356            CommandOutcome {
2357                command: "cargo test".to_owned(),
2358                code: Some(101),
2359                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
2360                duration_ms: 0,
2361            },
2362        ];
2363        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
2364        assert!(d.contains("cargo test"), "{d}");
2365        assert!(
2366            !d.contains("cargo make check"),
2367            "a passing check is not a diagnostic: {d}"
2368        );
2369        assert!(d.contains("assertion failed"), "{d}");
2370    }
2371
2372    #[test]
2373    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
2374        let mut state = run_state(RunStatus::Blocked);
2375        state.event(
2376            "land",
2377            "stopped: the fixer produced no commit while 2 check(s) were failing \
2378             (build, lint); stopping instead of looping on an unchanged tree",
2379        );
2380        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
2381        assert!(d.contains("build"), "{d}");
2382        assert!(d.contains("lint"), "{d}");
2383        assert!(d.contains("fixer produced no commit"), "{d}");
2384    }
2385
2386    #[test]
2387    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
2388        // The whole point of the feature: a run held as "no candidate produced
2389        // a change" can mean the implementer actually finished the task and
2390        // only left a clean local tree behind - see AGENTS.md on this exact
2391        // failure mode. The diagnostic has to carry what the agent actually
2392        // said, not just the fact that nothing was there to judge.
2393        let mut state = run_state(RunStatus::Failed);
2394        state.candidates = vec![candidate(
2395            'A',
2396            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
2397            true,
2398            None,
2399        )];
2400        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
2401        assert!(d.contains("candidate A"), "{d}");
2402        assert!(d.contains("tagged v1.2.3"), "{d}");
2403    }
2404
2405    #[test]
2406    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
2407        let mut state = run_state(RunStatus::Failed);
2408        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
2409        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
2410        assert!(d.contains("candidate A"), "{d}");
2411        assert!(d.contains("agent timed out"), "{d}");
2412    }
2413
2414    #[test]
2415    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
2416        // A viable candidate existed, the gate never ran, and nothing land
2417        // said matches - `Task::last_error` is left to explain this one alone.
2418        let mut state = run_state(RunStatus::Failed);
2419        state.candidates = vec![candidate('A', "did the work", false, None)];
2420        assert!(diagnostic(&state).is_none());
2421    }
2422
2423    #[test]
2424    fn diagnostic_is_bounded_however_much_a_run_printed() {
2425        let mut state = run_state(RunStatus::Blocked);
2426        state.gate = vec![
2427            CommandOutcome {
2428                command: "cargo test".to_owned(),
2429                code: Some(101),
2430                output_tail: "x".repeat(50_000),
2431                duration_ms: 0,
2432            },
2433            CommandOutcome {
2434                command: "cargo clippy".to_owned(),
2435                code: Some(1),
2436                output_tail: "y".repeat(50_000),
2437                duration_ms: 0,
2438            },
2439        ];
2440        state.candidates = vec![
2441            candidate('A', &"z".repeat(50_000), true, None),
2442            candidate('B', &"w".repeat(50_000), true, None),
2443        ];
2444        let d = diagnostic(&state).expect("plenty here to diagnose");
2445        assert!(
2446            d.len() <= DIAGNOSTIC_MAX,
2447            "diagnostic grew to {} bytes, unbounded",
2448            d.len()
2449        );
2450    }
2451
2452    #[test]
2453    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
2454        let mut state = run_state(RunStatus::Blocked);
2455        state.gate = vec![CommandOutcome {
2456            command: "cargo test".to_owned(),
2457            code: Some(101),
2458            output_tail: "assertion failed".to_owned(),
2459            duration_ms: 0,
2460        }];
2461        let verdict = Verdict {
2462            status: RunStatus::Blocked,
2463            left_pr: false,
2464            quota_hit: false,
2465            parked: false,
2466            no_viable_candidates: false,
2467        };
2468
2469        // Attempt one of two still has a retry coming: no diagnostic yet, the
2470        // task is going to run again and this run's evidence would go stale.
2471        let mut t = task();
2472        t.start("run-1".to_owned());
2473        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
2474        assert_eq!(t.status, TaskStatus::Failed);
2475        assert!(t.diagnostic.is_none());
2476
2477        // Attempt two exhausts the budget: now it is held, and the
2478        // diagnostic is what `magi task show` has to say more than one line.
2479        t.start("run-2".to_owned());
2480        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
2481        assert_eq!(t.status, TaskStatus::Held);
2482        let d = t.diagnostic.expect("a held task must carry its diagnostic");
2483        assert!(d.contains("cargo test"), "{d}");
2484    }
2485
2486    fn approval_question(run: &str) -> ask::Question {
2487        ask::Question::new(
2488            run.to_owned(),
2489            land::APPROVAL_NODE.to_owned(),
2490            "land".to_owned(),
2491            "merge?".to_owned(),
2492            String::new(),
2493            vec!["merge".to_owned(), "hold".to_owned()],
2494        )
2495    }
2496
2497    #[test]
2498    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
2499        crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
2500        let mut state = run_state(RunStatus::Landing);
2501        state.id = "20260101-000000-fre1".to_owned();
2502        state.parked = true;
2503        state.save().unwrap();
2504        ask::Questions::open()
2505            .put(&mut approval_question(&state.id))
2506            .unwrap();
2507
2508        let mut t = task();
2509        t.runs.push(state.id.clone());
2510        assert_eq!(
2511            land_resume_state(&t),
2512            LandResume::StillWaiting,
2513            "nobody has answered and the timeout has not passed"
2514        );
2515    }
2516
2517    #[test]
2518    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
2519        // `ask::ask_and_wait`'s own deadline used to retire a question
2520        // nobody answered; land's approval bypasses that wait (see
2521        // `land::approval_gate`), so this is now the only place
2522        // `graph.answer_timeout` is enforced for a land approval at all.
2523        crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
2524        let mut state = run_state(RunStatus::Landing);
2525        state.id = "20260101-000000-exp1".to_owned();
2526        state.parked = true;
2527        state.config.graph.answer_timeout = 60;
2528        state.save().unwrap();
2529
2530        let store = ask::Questions::open();
2531        let mut q = approval_question(&state.id);
2532        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
2533        store.put(&mut q).unwrap();
2534
2535        let mut t = task();
2536        t.runs.push(state.id.clone());
2537        assert_eq!(
2538            land_resume_state(&t),
2539            LandResume::Ready,
2540            "an expired question must not be waited on forever"
2541        );
2542
2543        let after = store.get(&q.id).unwrap();
2544        assert!(
2545            !after.status.open(),
2546            "the question is abandoned, not silently ignored"
2547        );
2548        assert!(
2549            after.resolution().is_none(),
2550            "an abandoned question is not read as a decision"
2551        );
2552    }
2553
2554    #[test]
2555    fn reclaim_settles_a_running_task_against_its_last_run() {
2556        let mut t = task();
2557        t.start("20260904-000000-4043".to_owned());
2558        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2);
2559        assert_eq!(
2560            t.status,
2561            TaskStatus::Done,
2562            "a run that actually finished must not stay `running` forever"
2563        );
2564    }
2565
2566    #[test]
2567    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
2568        // A blocked run with attempts left goes back to `Failed`, exactly as
2569        // it would from `attempt` itself - `reclaim` must not invent a second
2570        // policy for a task a daemon merely stopped without reporting.
2571        let mut t = task();
2572        t.start("20260904-000000-4043".to_owned());
2573        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2);
2574        assert_eq!(t.status, TaskStatus::Failed);
2575        assert!(t.status.runnable());
2576    }
2577
2578    #[test]
2579    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
2580        let mut t = task();
2581        t.start("20260904-000000-4043".to_owned());
2582        reclaim(&mut t, None, 2);
2583        assert_eq!(t.status, TaskStatus::Held);
2584        assert!(
2585            t.last_error
2586                .as_deref()
2587                .is_some_and(|e| e.contains("running")),
2588            "the operator needs to know why this task was held"
2589        );
2590    }
2591
2592    #[test]
2593    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
2594        let dir = tempfile::tempdir().unwrap();
2595        let queue = Queue::at(dir.path().to_path_buf());
2596
2597        // No run recorded, so this never has to touch `RunState::load`.
2598        let mut orphaned = task();
2599        orphaned.id = "20260904-000000-orph".to_owned();
2600        orphaned.status = TaskStatus::Running;
2601        orphaned.attempts = 1;
2602        queue.put(&mut orphaned).unwrap();
2603
2604        let mut alive = task();
2605        alive.id = "20260904-000000-live".to_owned();
2606        alive.status = TaskStatus::Running;
2607        alive.attempts = 1;
2608        queue.put(&mut alive).unwrap();
2609        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
2610
2611        let mut queued = task();
2612        queued.id = "20260904-000000-wait".to_owned();
2613        queue.put(&mut queued).unwrap();
2614
2615        let reclaimed = reclaim_orphaned_running(&queue, 2);
2616        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
2617
2618        assert_eq!(
2619            queue.get(&orphaned.id).unwrap().status,
2620            TaskStatus::Held,
2621            "nothing was driving it and there was no run to recover"
2622        );
2623        assert_eq!(
2624            queue.get(&alive.id).unwrap().status,
2625            TaskStatus::Running,
2626            "a live claim must protect the task it belongs to"
2627        );
2628        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
2629    }
2630
2631    #[test]
2632    fn an_already_claimed_task_is_skipped_rather_than_failed() {
2633        let dir = tempfile::tempdir().unwrap();
2634        let queue = Queue::at(dir.path().to_path_buf());
2635        let mut only = task();
2636        queue.put(&mut only).unwrap();
2637
2638        let _elsewhere = queue.claim(&only.id).unwrap();
2639        let candidates = runnable(&queue);
2640        assert_eq!(candidates.len(), 1, "the task is still runnable");
2641        assert!(
2642            queue.claim(&candidates[0].id).is_err(),
2643            "the loop cannot take a claim somebody else holds"
2644        );
2645
2646        let after = queue.get(&only.id).unwrap();
2647        assert_eq!(after.status, TaskStatus::Queued);
2648        assert_eq!(
2649            after.attempts, 0,
2650            "losing the race is not an attempt at the task"
2651        );
2652        assert_eq!(after.last_error, None);
2653    }
2654
2655    #[test]
2656    fn the_status_file_round_trips_and_its_heartbeat_advances() {
2657        let dir = tempfile::tempdir().unwrap();
2658        let path = dir.path().join("daemon.json");
2659
2660        let mut status = Status::new();
2661        status.idle = false;
2662        status.completed = 7;
2663        status.current = vec![Current {
2664            task: "20260902-000000-t111".to_owned(),
2665            run: "20260902-000001-r111".to_owned(),
2666        }];
2667        write_status_to(&path, &status).unwrap();
2668        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
2669        assert_eq!(first.schema, SCHEMA);
2670        assert_eq!(first.pid, std::process::id());
2671        assert!(!first.idle);
2672        assert_eq!(first.completed, 7);
2673        assert_eq!(first.current, status.current);
2674        assert!(
2675            !path.with_extension("json.tmp").exists(),
2676            "the temp file is renamed, not left behind"
2677        );
2678
2679        std::thread::sleep(Duration::from_millis(5));
2680        status.updated_at = Timestamp::now();
2681        status.polls = 3;
2682        write_status_to(&path, &status).unwrap();
2683        let second: Status =
2684            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
2685        assert!(
2686            second.updated_at > first.updated_at,
2687            "a reader can only detect staleness if the heartbeat moves"
2688        );
2689        assert_eq!(
2690            second.started_at, first.started_at,
2691            "the start time is not a heartbeat"
2692        );
2693        assert_eq!(second.polls, 3);
2694    }
2695
2696    #[test]
2697    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
2698        let dir = tempfile::tempdir().unwrap();
2699
2700        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
2701
2702        let mut status = Status::new();
2703        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
2704        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
2705        let stale = read_status(dir.path()).unwrap();
2706        assert!(
2707            !stale.running(Timestamp::now()),
2708            "a minute without a heartbeat is a dead daemon, not a busy one"
2709        );
2710        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
2711
2712        status.updated_at = Timestamp::now();
2713        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
2714        let fresh = read_status(dir.path()).unwrap();
2715        assert!(fresh.running(Timestamp::now()));
2716    }
2717
2718    #[test]
2719    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
2720        let dir = tempfile::tempdir().unwrap();
2721        let now = Timestamp::now();
2722        let mine = "20260903-080619-01c2";
2723
2724        assert!(
2725            !is_working_on(dir.path(), mine, now),
2726            "no status file means nobody is working on anything"
2727        );
2728
2729        let mut status = Status::new();
2730        status.current = vec![Current {
2731            task: "20260903-080340-0167".to_owned(),
2732            run: mine.to_owned(),
2733        }];
2734        status.updated_at = now;
2735        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
2736        assert!(is_working_on(dir.path(), mine, now));
2737        assert!(
2738            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
2739            "a daemon busy with one run is not working on another"
2740        );
2741
2742        // A killed daemon stops writing heartbeats but leaves the file behind
2743        // naming the run it died in. That run must not be undeletable forever.
2744        status.updated_at = now - jiff::SignedDuration::from_secs(600);
2745        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
2746        assert!(
2747            !is_working_on(dir.path(), mine, now),
2748            "a stale heartbeat is a dead daemon, so its run is a leftover"
2749        );
2750    }
2751
2752    #[test]
2753    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
2754        let dir = tempfile::tempdir().unwrap();
2755        let now = Timestamp::now();
2756
2757        assert!(
2758            !is_working_on_short(dir.path(), "01c2", now),
2759            "no status file means nobody is working on anything"
2760        );
2761
2762        let mut status = Status::new();
2763        status.current = vec![Current {
2764            task: "20260903-080340-0167".to_owned(),
2765            run: "20260903-080619-01c2".to_owned(),
2766        }];
2767        status.updated_at = now;
2768        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
2769        assert!(
2770            is_working_on_short(dir.path(), "01c2", now),
2771            "the run's short id is the last block of its full id"
2772        );
2773        assert!(
2774            !is_working_on_short(dir.path(), "3cbf", now),
2775            "a daemon busy with one worktree bay is not working on another"
2776        );
2777    }
2778
2779    #[test]
2780    fn a_newer_status_file_still_yields_a_reading() {
2781        let dir = tempfile::tempdir().unwrap();
2782        // A field this build has never heard of must not turn the reading into
2783        // nothing at all; that is the whole reason the reader is permissive.
2784        std::fs::write(
2785            dir.path().join("daemon.json"),
2786            serde_json::json!({
2787                "schema": 2,
2788                "updated_at": Timestamp::now().to_string(),
2789                "idle": true,
2790                "surprise": { "nested": [1, 2, 3] },
2791            })
2792            .to_string(),
2793        )
2794        .unwrap();
2795
2796        let reading = read_status(dir.path()).expect("a forward-compatible read");
2797        assert!(reading.running(Timestamp::now()));
2798        assert!(reading.idle);
2799        assert!(reading.current.is_empty());
2800    }
2801
2802    #[test]
2803    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
2804        // A daemon started before `current` became a list keeps writing this
2805        // shape on every heartbeat until it is restarted. A rolling upgrade
2806        // - a newer `magi web` or `magi doctor` reading an older `magi
2807        // serve`'s heartbeat - must still see the run it is on, not "no
2808        // daemon" from a type mismatch failing the whole struct.
2809        let dir = tempfile::tempdir().unwrap();
2810        std::fs::write(
2811            dir.path().join("daemon.json"),
2812            serde_json::json!({
2813                "schema": 1,
2814                "pid": 4242,
2815                "updated_at": Timestamp::now().to_string(),
2816                "idle": false,
2817                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
2818                "completed": 3,
2819                "polls": 9,
2820            })
2821            .to_string(),
2822        )
2823        .unwrap();
2824
2825        let reading = read_status(dir.path()).expect("an older shape must still parse");
2826        assert!(reading.running(Timestamp::now()));
2827        assert_eq!(
2828            reading.current,
2829            vec![Current {
2830                task: "20260902-140501-aaaa".to_owned(),
2831                run: "20260902-140502-bbbb".to_owned(),
2832            }]
2833        );
2834    }
2835
2836    #[test]
2837    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
2838        let dir = tempfile::tempdir().unwrap();
2839        std::fs::write(
2840            dir.path().join("daemon.json"),
2841            serde_json::json!({
2842                "schema": 1,
2843                "updated_at": Timestamp::now().to_string(),
2844                "idle": true,
2845                "current": null,
2846            })
2847            .to_string(),
2848        )
2849        .unwrap();
2850        let with_null = read_status(dir.path()).expect("null must still parse");
2851        assert!(with_null.current.is_empty());
2852
2853        std::fs::write(
2854            dir.path().join("daemon.json"),
2855            serde_json::json!({
2856                "schema": 1,
2857                "updated_at": Timestamp::now().to_string(),
2858                "idle": true,
2859            })
2860            .to_string(),
2861        )
2862        .unwrap();
2863        let absent = read_status(dir.path()).expect("a missing field must still parse");
2864        assert!(absent.current.is_empty());
2865    }
2866
2867    #[test]
2868    fn a_task_without_a_repository_runs_in_the_daemons_default() {
2869        let fallback = Path::new("/default");
2870        let mut blank = task();
2871        blank.repo = PathBuf::new();
2872        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
2873        let mut dot = task();
2874        dot.repo = PathBuf::from(".");
2875        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
2876        assert_eq!(
2877            repo_for(&task(), fallback),
2878            PathBuf::from("/repo"),
2879            "a task that names a repository keeps it"
2880        );
2881    }
2882
2883    #[test]
2884    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
2885        // Three seats said out loud. What `solo` promises is one candidate
2886        // *whatever the config asks for*, so the contrast has to be a number
2887        // this test owns - it used to be `Config::default()`'s, which became
2888        // 1 when one implementation became the default and left the two
2889        // halves of this test asserting the same thing.
2890        let mut solo_cfg = Config::default();
2891        solo_cfg.graph.candidates = 3;
2892        let mut solo_task = task();
2893        solo_task.solo = true;
2894        apply_solo(&mut solo_cfg, &solo_task);
2895        assert_eq!(solo_cfg.graph.candidates, 1);
2896
2897        let mut plain_cfg = Config::default();
2898        plain_cfg.graph.candidates = 3;
2899        let plain_task = task();
2900        assert!(!plain_task.solo);
2901        apply_solo(&mut plain_cfg, &plain_task);
2902        assert_eq!(
2903            plain_cfg.graph.candidates, 3,
2904            "a task that did not ask to run alone keeps the config's candidates"
2905        );
2906    }
2907
2908    #[test]
2909    fn merge_overrides_are_parsed_or_refused() {
2910        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
2911        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
2912        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
2913        assert!(merge_mode("squash").is_err());
2914    }
2915
2916    #[test]
2917    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
2918        let now = Timestamp::now();
2919        let fallback = Duration::from_secs(300);
2920        let cap = Duration::from_secs(1800);
2921
2922        // No reset hint at all: the fallback.
2923        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
2924
2925        // A reset ten minutes out, well inside the cap: waited for exactly.
2926        let soon = now + jiff::SignedDuration::from_secs(600);
2927        assert_eq!(
2928            quota_wait(Some(soon), now, fallback, cap),
2929            Duration::from_secs(600)
2930        );
2931
2932        // A reset already in the past is not trusted: the fallback, not a
2933        // zero or negative wait that would spin the loop right back around.
2934        let past = now - jiff::SignedDuration::from_secs(60);
2935        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
2936
2937        // A reset further out than the cap is trusted for direction but not
2938        // for magnitude: a parsing slip must not sleep the loop for a day.
2939        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
2940        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
2941    }
2942
2943    #[test]
2944    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
2945        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
2946
2947        let at = parse_reset_hint("4:50am (UTC)", now).expect("a recognised shape parses");
2948        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
2949
2950        // Same clock reading, but it has already gone by today: read as
2951        // tomorrow's, since the CLI would not still be reporting a limit past
2952        // its own stated reset.
2953        let already_past =
2954            parse_reset_hint("1:00am (UTC)", now).expect("a recognised shape parses");
2955        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
2956
2957        assert!(
2958            parse_reset_hint("session limit reached", now).is_none(),
2959            "free text with no recognised shape is not guessed at"
2960        );
2961        assert!(
2962            parse_reset_hint("4:50am (Nowhere/Fake)", now).is_none(),
2963            "an unresolvable zone name is not guessed at either"
2964        );
2965    }
2966
2967    /// A loop whose queue lives in a temp tree and whose poll interval is far
2968    /// longer than the test's patience, so anything that waits out a poll
2969    /// instead of noticing the stop fails rather than merely being slow.
2970    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
2971        let opts = Opts {
2972            poll: Duration::from_secs(30),
2973            // `Opts::default`'s `repo` is `"."` - the process's own working
2974            // directory, which under `cargo test` is this very checkout, a
2975            // real git repository with its own `magi.toml`. `drive` runs the
2976            // janitor unconditionally on every call, and the janitor discovers
2977            // its config from `opts.repo` and then prunes worktree
2978            // registrations there - so leaving this at `"."` would have every
2979            // test that drives the loop mutate this checkout's own git admin
2980            // state. A directory that is not a repository at all makes that
2981            // step fail closed instead (`git worktree prune` errors, caught
2982            // and logged, nothing pruned).
2983            repo: dir.join("repo"),
2984            ..Opts::default()
2985        };
2986        // The status file goes in a directory that does not exist yet, so its
2987        // creation is itself evidence the loop published one. `worktrees`
2988        // must be just as fictional: the janitor reclaims worktrees under it
2989        // for real, and a test that let it fall through to
2990        // `crate::run::default_worktree_root()` would have it reclaim
2991        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
2992        // which is exactly what happened before this function took the
2993        // parameter at all.
2994        let home = dir.join("home");
2995        let worktrees = dir.join("wt");
2996        (
2997            opts,
2998            Queue::at(dir.join("queue")),
2999            home.join("daemon.json"),
3000            home,
3001            worktrees,
3002        )
3003    }
3004
3005    #[test]
3006    fn a_stop_is_idempotent_and_once_set_stays_set() {
3007        let stop = Stop::new();
3008        assert!(!stop.stopped());
3009
3010        stop.stop();
3011        assert!(stop.stopped());
3012        stop.stop();
3013        assert!(stop.stopped(), "a second stop is not a toggle");
3014
3015        let shared = stop.clone();
3016        assert!(
3017            shared.stopped(),
3018            "a clone is the same stop; that is how the loop and its caller share one"
3019        );
3020    }
3021
3022    #[test]
3023    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
3024        let stop = Stop::new();
3025        stop.enter();
3026        assert!(
3027            !stop.finishing(),
3028            "a busy loop nobody has asked to stop is just running"
3029        );
3030
3031        stop.stop();
3032        assert!(
3033            stop.finishing(),
3034            "a stop asked for mid-run has not landed until the run is settled"
3035        );
3036
3037        stop.exit();
3038        assert!(
3039            !stop.finishing(),
3040            "once the run is settled the stop has landed and there is nothing to finish"
3041        );
3042    }
3043
3044    #[test]
3045    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
3046        let stop = Stop::new();
3047        stop.enter();
3048        stop.enter();
3049        stop.stop();
3050        assert!(stop.finishing(), "two runs still in flight");
3051
3052        stop.exit();
3053        assert!(
3054            stop.finishing(),
3055            "one run finished, but a sibling is still working"
3056        );
3057
3058        stop.exit();
3059        assert!(
3060            !stop.finishing(),
3061            "the last run out is what actually lands the stop"
3062        );
3063    }
3064
3065    #[tokio::test]
3066    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
3067        let dir = tempfile::tempdir().unwrap();
3068        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
3069        let stop = Stop::new();
3070        stop.stop();
3071
3072        let began = std::time::Instant::now();
3073        tokio::time::timeout(
3074            Duration::from_secs(2),
3075            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
3076        )
3077        .await
3078        .expect("a stopped loop must return, not sit out its poll interval")
3079        .expect("the loop's own setup and teardown must not fail");
3080        assert!(
3081            began.elapsed() < opts.poll,
3082            "returned only after {:?}, which is a poll interval, not a stop",
3083            began.elapsed()
3084        );
3085    }
3086
3087    #[tokio::test]
3088    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
3089        let dir = tempfile::tempdir().unwrap();
3090        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
3091        let stop = Stop::new();
3092
3093        // Asked for after the loop is already parked on its empty queue, which
3094        // is the case an operator tapping stop on a phone actually hits.
3095        let asker = {
3096            let stop = stop.clone();
3097            tokio::spawn(async move {
3098                tokio::time::sleep(Duration::from_millis(20)).await;
3099                stop.stop();
3100            })
3101        };
3102
3103        let began = std::time::Instant::now();
3104        tokio::time::timeout(
3105            Duration::from_secs(2),
3106            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
3107        )
3108        .await
3109        .expect("a stop asked for while idle must wake the wait")
3110        .expect("the loop's own setup and teardown must not fail");
3111        asker.await.unwrap();
3112        assert!(
3113            began.elapsed() < opts.poll,
3114            "returned only after {:?}, so the stop waited on the sleep",
3115            began.elapsed()
3116        );
3117    }
3118
3119    #[tokio::test]
3120    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
3121        let dir = tempfile::tempdir().unwrap();
3122        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
3123        let stop = Stop::new();
3124        stop.stop();
3125
3126        tokio::time::timeout(
3127            Duration::from_secs(2),
3128            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
3129        )
3130        .await
3131        .expect("a stopped loop must return")
3132        .expect("the loop's own setup and teardown must not fail");
3133
3134        assert!(
3135            home.is_dir(),
3136            "the loop did publish a status file, so its removal is the teardown and not an absence"
3137        );
3138        assert!(
3139            !status_file.exists(),
3140            "a stopped loop clears its status file"
3141        );
3142        assert!(
3143            read_status(&home).is_none(),
3144            "a reader must see no daemon at all, not a heartbeat that merely stopped"
3145        );
3146    }
3147}