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