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/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
652/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
653/// by some other means entirely, like a manual `magi run` resume that
654/// finishes the graph outside the queue's bookkeeping.
655///
656/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
657/// `settle` is separate from `attempt`: a task recovered this way must land
658/// exactly where a live daemon would have put it — the same policy table,
659/// not a second one that quietly drifts from it — and that is only checkable
660/// without spawning a real run.
661fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize) {
662    match last_run {
663        Some(state) => {
664            let verdict = Verdict {
665                status: state.status,
666                left_pr: state.pr.is_some(),
667                quota_hit: !state.quota.is_empty(),
668                parked: state.parked,
669                no_viable_candidates: state.viable().is_empty(),
670            };
671            let detail = format!(
672                "recovered a `running` task whose daemon never recorded the outcome: {}",
673                describe(&state)
674            );
675            settle(task, verdict, &detail, max_attempts);
676        }
677        None => {
678            let why = "task was `running` with no live daemon and no readable \
679                       run to recover; held for a human to check what happened";
680            task.last_error = Some(why.to_owned());
681            // The phone shows `hold_reason`, so a task held by the machine
682            // says why there too and not only in `last_error`.
683            task.hold(Some(why.to_owned()));
684        }
685    }
686}
687
688/// Find every task left at `running` that no live process is actually
689/// driving, and settle each one against whatever its last run became.
690///
691/// # Why a claim is proof, not a guess
692///
693/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
694/// `running`, and the guard is held for the task's whole time in that status:
695/// `attempt` does not return, and the loop does not move past the scope
696/// holding the claim, until the run has settled. So a `running` task whose
697/// lock is gone cannot have a live owner — this process or any other —
698/// without needing a staleness threshold or a pid check the way
699/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
700/// task that never got as far as `running` at all. Taking the claim here is
701/// the whole test: it either fails, because something really does hold it
702/// and the task is left alone, or it succeeds, which is the proof — and it is
703/// kept for the rest of the decision so nothing else can start a competing
704/// run while this one is being written.
705///
706/// Called on every poll, not only at startup, for the reason
707/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
708/// keep noticing this, not only on the one morning it happened to restart.
709fn reclaim_orphaned_running(queue: &Queue, max_attempts: usize) -> Vec<String> {
710    let mut reclaimed = Vec::new();
711    for listed in queue.list() {
712        if listed.status != TaskStatus::Running {
713            continue;
714        }
715        let Ok(_claim) = queue.claim(&listed.id) else {
716            continue;
717        };
718        // Re-read under the claim: a release or an edit landed by a human
719        // between the listing above and the claim just taken must not be
720        // clobbered by a decision based on the stale copy.
721        let Ok(mut task) = queue.get(&listed.id) else {
722            continue;
723        };
724        if task.status != TaskStatus::Running {
725            continue;
726        }
727        let last_run = task.runs.last().and_then(|id| RunState::load(id).ok());
728        reclaim(&mut task, last_run, max_attempts);
729        record(queue, &mut task);
730        reclaimed.push(task.id.clone());
731    }
732    reclaimed
733}
734
735/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
736///
737/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
738/// sets, so there is one loop body rather than two that drift apart the first
739/// time the retry policy changes on only one of them.
740pub async fn serve(opts: Opts) -> Result<()> {
741    serve_until(opts, Stop::new()).await
742}
743
744/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
745///
746/// Neither a signal nor a `stop` abandons a run in flight. Killing the graph
747/// mid-node leaves worktrees, branches and agent sessions behind, and every
748/// agent call already paid for is lost; finishing the run costs the operator a
749/// wait and saves them a cleanup. A stop therefore only sets a flag: the
750/// current `execute` runs to its terminal status, the task's outcome is
751/// recorded, and only then does the loop return. That window is what
752/// [`Stop::finishing`] is for. An operator who genuinely wants the run dead
753/// still has a second Ctrl-C, which the runtime turns into a process kill —
754/// and the task left `Running` then tells the next daemon, and the next human,
755/// where to look.
756///
757/// While the queue is empty the stop is honoured within one wakeup rather than
758/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
759/// caller that taps stop does not sit through the remainder of a sleep.
760pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
761    let signal = {
762        let stop = stop.clone();
763        tokio::spawn(async move {
764            if tokio::signal::ctrl_c().await.is_ok() {
765                stop.stop();
766                tracing::info!("shutdown requested; a run in flight will be finished first");
767            }
768        })
769    };
770
771    let outcome = drive(
772        &opts,
773        &Queue::open(),
774        &status_path(),
775        &crate::run::home(),
776        &stop,
777    )
778    .await;
779
780    signal.abort();
781    outcome
782}
783
784/// The loop proper: setup, poll, teardown, with the queue and the status file
785/// supplied rather than discovered.
786///
787/// Both are parameters because [`crate::run::home`] is process-global and its
788/// override is a `OnceLock`, so a unit test that pinned it would fight every
789/// other test in the binary — and a loop that resolved the home itself could
790/// only be exercised against the operator's real one, publishing over a live
791/// daemon's status file and claiming tasks out of a live backlog.
792async fn drive(
793    opts: &Opts,
794    queue: &Queue,
795    status_file: &Path,
796    home: &Path,
797    stop: &Stop,
798) -> Result<()> {
799    janitor(&opts.repo, opts, home).await;
800
801    // The status file is a *snapshot*, not a stream of events: a reader only
802    // ever wants the latest values, and every tick rewrites the whole file
803    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
804    // while an mpsc channel would force the loop to re-send unchanged fields on
805    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
806    // for no gain. The lock is only ever held across a field assignment, never
807    // across an await.
808    let status = Arc::new(Mutex::new(Status::new()));
809    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
810    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
811
812    // Read once at startup, not per task: how many runs this loop drives at
813    // once is a property of the machine running it, not of whichever
814    // repository a given task happens to name - see
815    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
816    // fact in the same sense the agent roster is.
817    let concurrency = max_concurrent(
818        prepare(&opts.repo, opts)
819            .map(|c| c.daemon.max_concurrent_runs)
820            .unwrap_or(1),
821    );
822
823    tracing::info!(
824        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once)",
825        queue.root().display(),
826        opts.poll.as_secs(),
827        opts.max_attempts,
828        concurrency
829    );
830
831    let outcome = poll(opts, queue, &status, home, stop, concurrency).await;
832
833    beat.abort();
834    clear_status_at(status_file);
835    outcome
836}
837
838/// Refresh the status file on a fixed tick.
839///
840/// Separate from the loop because a run takes tens of minutes: a status file
841/// written only between tasks would look stale for the whole of every run, and
842/// a reader would report the daemon dead exactly while it was busiest.
843async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
844    loop {
845        tokio::time::sleep(HEARTBEAT).await;
846        let snapshot = {
847            let mut guard = lock(&status);
848            guard.updated_at = Timestamp::now();
849            guard.clone()
850        };
851        if let Err(e) = write_status_to(&path, &snapshot) {
852            // A failed heartbeat must not take the daemon down: the loop is the
853            // product, the status file is only the window onto it.
854            tracing::warn!("could not refresh the daemon status file: {e:#}");
855        }
856    }
857}
858
859/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
860/// if so, whether that wait is over.
861#[derive(Debug, Clone, Copy, PartialEq, Eq)]
862enum LandResume {
863    /// The task's last run is not parked on a land approval; schedule it
864    /// like any other candidate.
865    NotLanding,
866    /// Parked in `land`, waiting on a question nobody has answered yet.
867    /// Left alone: attempting it now would only re-observe the same pull
868    /// request and park again, spending a `gh` call on a decision that has
869    /// not changed since the last time this was checked.
870    StillWaiting,
871    /// Parked in `land`, and the question is settled - answered or
872    /// abandoned. Resuming this is the one kind of candidate that must not
873    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
874    Ready,
875}
876
877/// Classify a runnable candidate by whether it is parked on a land-merge
878/// approval. Read-only - no claim taken, nothing written - so it is cheap
879/// enough to call on every candidate, every poll.
880fn land_resume_state(task: &Task) -> LandResume {
881    let Some(run_id) = task.runs.last() else {
882        return LandResume::NotLanding;
883    };
884    let Ok(state) = RunState::load(run_id) else {
885        return LandResume::NotLanding;
886    };
887    if state.status != RunStatus::Landing || !state.parked {
888        return LandResume::NotLanding;
889    }
890    let store = ask::Questions::open();
891    let waiting = store
892        .list()
893        .into_iter()
894        .filter(|q| &q.run == run_id && q.node == land::APPROVAL_NODE)
895        .max_by(|a, b| a.id.cmp(&b.id));
896    let Some(mut q) = waiting else {
897        return LandResume::Ready;
898    };
899    if !q.status.open() {
900        return LandResume::Ready;
901    }
902    // `ask::ask_and_wait`'s own deadline is what used to retire a question
903    // nobody ever answered; land's approval bypasses that wait entirely (see
904    // `land::approval_gate`), so the same deadline has to be enforced here
905    // instead, or `graph.answer_timeout` silently stops meaning anything for
906    // a land approval and a run can sit `StillWaiting` forever with nobody
907    // told to look at it.
908    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
909    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
910    if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
911        q.abandon(format!(
912            "no answer within {}s of asking",
913            timeout.as_secs().max(1)
914        ));
915        // If this can't be persisted, do not treat the wait as settled on a
916        // guess: fall through and try again next poll.
917        if store.put(&mut q).is_ok() {
918            return LandResume::Ready;
919        }
920    }
921    LandResume::StillWaiting
922}
923
924/// How often the loop rechecks for new work while something it already
925/// started is still running, rather than sleeping out the whole
926/// [`Opts::poll`] interval.
927///
928/// Short on purpose: this is what lets a land-merge approval that comes back
929/// while another task is mid-competition be noticed and resumed within a
930/// fraction of a second, not within the next multi-second poll.
931const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
932
933/// Frees one attempt's concurrency slot - `Stop`'s busy count and its entry
934/// in `Status::current` - on drop, so both are released even if the attempt
935/// panics rather than returning.
936///
937/// A `Drop` impl rather than statements written after the `.await` it
938/// guards: a panic unwinds straight past code placed "after" a call, and
939/// `Runner::execute`'s chain reaches deep enough into agent-output parsing
940/// that ruling a panic out there is not a bet this loop can make. Without
941/// this, one panicking run would leave [`Stop::busy_now`] stuck `true`
942/// forever - the idle branch in [`poll`], and with it the janitor, would
943/// never run again - and a ghost entry in `Status::current` naming a task
944/// nothing is still working on.
945struct InFlightGuard<'a> {
946    status: &'a Arc<Mutex<Status>>,
947    stop: &'a Stop,
948    task_id: &'a str,
949}
950
951impl Drop for InFlightGuard<'_> {
952    fn drop(&mut self) {
953        lock(self.status).current.retain(|c| c.task != self.task_id);
954        self.stop.exit();
955    }
956}
957
958/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
959/// teardown and cannot skip the teardown on an early return.
960///
961/// `max_concurrent` bounds how many *ordinary* candidates run at once - see
962/// [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a land
963/// approval that has since been answered is dispatched outside that bound
964/// the moment [`land_resume_state`] reports it [`LandResume::Ready`]: the
965/// whole point of parking there is that it must not queue behind whatever
966/// else the loop happens to be running, even at the default of one.
967async fn poll(
968    opts: &Opts,
969    queue: &Queue,
970    status: &Arc<Mutex<Status>>,
971    home: &Path,
972    stop: &Stop,
973    max_concurrent: usize,
974) -> Result<()> {
975    // Only consulted by `once`, where a task that just failed is still
976    // `runnable` and would otherwise be picked up again inside the same drain.
977    // In the long-running mode a later poll retrying a failed task is the point,
978    // and the attempt counter is what bounds it.
979    let mut attempted: Vec<String> = Vec::new();
980    let sem = Arc::new(tokio::sync::Semaphore::new(max_concurrent));
981    // A quota hit is a fact about the machine, not the task that happened to
982    // surface it, and every other *ordinary* candidate is no less likely to
983    // hit the same wall - see the warning below. A land-merge resume is
984    // exempt: it is a human decision finishing, not a fresh competition, and
985    // must not sit out a quota cooldown it did not cause.
986    let quota_cooldown_until: Arc<Mutex<Option<Timestamp>>> = Arc::new(Mutex::new(None));
987    let mut inflight: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
988
989    while !stop.stopped() {
990        lock(status).polls += 1;
991
992        // Reap whatever finished since the last tick without blocking on
993        // anything still running. `InFlightGuard` already released the slot
994        // even if the spawned attempt panicked; this only surfaces that it
995        // happened, since a panic swallowed here otherwise leaves no trace.
996        while let Some(result) = inflight.try_join_next() {
997            if let Err(e) = result {
998                tracing::error!("a spawned attempt did not finish cleanly: {e}");
999            }
1000        }
1001
1002        let swept = sweep_stale_claims(queue, STALE_CLAIM);
1003        if !swept.is_empty() {
1004            tracing::warn!(
1005                "swept {} stale claim(s) left behind by an earlier daemon: {}",
1006                swept.len(),
1007                swept.join(", ")
1008            );
1009        }
1010        let reclaimed = reclaim_orphaned_running(queue, opts.max_attempts);
1011        if !reclaimed.is_empty() {
1012            tracing::warn!(
1013                "reclaimed {} task(s) left `running` by a daemon that never \
1014                 recorded the outcome: {}",
1015                reclaimed.len(),
1016                reclaimed.join(", ")
1017            );
1018        }
1019
1020        let candidates: Vec<Task> = runnable(queue)
1021            .into_iter()
1022            .filter(|t| !opts.once || !attempted.contains(&t.id))
1023            .collect();
1024
1025        let cooling_down =
1026            lock(&quota_cooldown_until).is_some_and(|until| Timestamp::now() < until);
1027
1028        let mut started_any = false;
1029        for candidate in candidates {
1030            if stop.stopped() {
1031                break;
1032            }
1033
1034            let resume = land_resume_state(&candidate);
1035            if resume == LandResume::StillWaiting {
1036                continue;
1037            }
1038            let priority = resume == LandResume::Ready;
1039
1040            if !priority && cooling_down {
1041                continue;
1042            }
1043            let permit = if priority {
1044                None
1045            } else {
1046                match Arc::clone(&sem).try_acquire_owned() {
1047                    Ok(p) => Some(p),
1048                    // No ordinary slot free right now. A later candidate in
1049                    // this same list might still be a priority resume, so
1050                    // keep looking rather than stopping here.
1051                    Err(_) => continue,
1052                }
1053            };
1054
1055            // A claim we cannot take means another daemon, or a human running
1056            // `magi run`, got there first. That is not the task's fault and
1057            // must not spend one of its attempts: move to the next candidate
1058            // rather than recording a failure.
1059            let Ok(claim) = queue.claim(&candidate.id) else {
1060                tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
1061                continue;
1062            };
1063            // Re-read under the claim: the task on disk may have been held or
1064            // edited between the listing and the lock.
1065            let mut task = match queue.get(&candidate.id) {
1066                Ok(t) if t.status.runnable() => t,
1067                Ok(_) => continue,
1068                Err(e) => {
1069                    tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
1070                    continue;
1071                }
1072            };
1073            let task_id = task.id.clone();
1074            attempted.push(task_id.clone());
1075            lock(status).idle = false;
1076            // A stop asked for from here on is "finishing", not "stopped": the
1077            // run gets to reach a terminal status before the loop returns.
1078            stop.enter();
1079            started_any = true;
1080
1081            let opts = opts.clone();
1082            let queue = queue.clone();
1083            let status = Arc::clone(status);
1084            let stop = stop.clone();
1085            let quota_cooldown_until = Arc::clone(&quota_cooldown_until);
1086            inflight.spawn(async move {
1087                // Held for the whole attempt: dropping either at the end of
1088                // this task is what releases the claim and, for an ordinary
1089                // candidate, frees its concurrency slot back to the loop.
1090                let _claim = claim;
1091                let _permit = permit;
1092                // See `InFlightGuard`: this must survive a panic inside `attempt`.
1093                let _inflight = InFlightGuard {
1094                    status: &status,
1095                    stop: &stop,
1096                    task_id: &task_id,
1097                };
1098                let quota = attempt(&opts, &queue, &status, &stop, &mut task).await;
1099                lock(&status).completed += 1;
1100                // A quota loss is a fact about the machine, not this task, and
1101                // the next ordinary candidate the loop offers is no less
1102                // likely to hit the same wall: without a cooldown here a
1103                // whole backlog can be run - and failed - in the seconds it
1104                // takes each attempt to notice the CLI is out of quota.
1105                if !quota.is_empty() {
1106                    let hint = quota.iter().find_map(|q| q.reset.as_deref());
1107                    let reset_at = hint.and_then(|h| parse_reset_hint(h, Timestamp::now()));
1108                    let wait = quota_wait(
1109                        reset_at,
1110                        Timestamp::now(),
1111                        QUOTA_WAIT_FALLBACK,
1112                        QUOTA_WAIT_CAP,
1113                    );
1114                    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
1115                    let until = Timestamp::now()
1116                        .checked_add(jiff::SignedDuration::from_secs(secs))
1117                        .unwrap_or(Timestamp::MAX);
1118                    *lock(&quota_cooldown_until) = Some(until);
1119                    match hint {
1120                        Some(h) => tracing::warn!(
1121                            "quota hit; waiting {}s before taking another ordinary task \
1122                             (CLI reported reset: {h})",
1123                            wait.as_secs()
1124                        ),
1125                        None => tracing::warn!(
1126                            "quota hit; waiting {}s before taking another ordinary task \
1127                             (no reset hint reported)",
1128                            wait.as_secs()
1129                        ),
1130                    }
1131                }
1132            });
1133        }
1134
1135        if started_any {
1136            continue;
1137        }
1138
1139        if stop.busy_now() {
1140            // Something started on an earlier tick is still running. Recheck
1141            // soon rather than sleeping out the whole poll interval - a freed
1142            // slot, or a land approval answered mid-run, must not sit idle
1143            // for it.
1144            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
1145            continue;
1146        }
1147
1148        // Truly idle: nothing new to start and nothing still running. The
1149        // disk is quiet, so this is the point for the janitor - folding
1150        // worktrees and pruning a cache while a sibling run is still
1151        // building would race the very compile the prune exists to keep,
1152        // which concurrent runs make possible in a way the old one-at-a-time
1153        // loop never had to guard against.
1154        janitor(&opts.repo, opts, home).await;
1155        lock(status).idle = true;
1156        if opts.once {
1157            break;
1158        }
1159        stop.idle(opts.poll).await;
1160    }
1161
1162    // Never return while a run is still in flight, whichever way the loop
1163    // above exited: a stop only sets a flag - see `serve_until` - and
1164    // returning here while `inflight` still holds spawned work would abandon
1165    // it exactly as a mid-node kill would.
1166    while let Some(result) = inflight.join_next().await {
1167        if let Err(e) = result {
1168            tracing::error!("a spawned attempt did not finish cleanly: {e}");
1169        }
1170    }
1171    Ok(())
1172}
1173
1174/// Run one claimed task to a terminal status and record the outcome.
1175///
1176/// Every transition is flushed to the queue as it happens, so the state on disk
1177/// is what actually occurred rather than what this process still intends to
1178/// write.
1179async fn attempt(
1180    opts: &Opts,
1181    queue: &Queue,
1182    status: &Arc<Mutex<Status>>,
1183    stop: &Stop,
1184    task: &mut Task,
1185) -> Vec<QuotaLoss> {
1186    let repo = repo_for(task, &opts.repo);
1187    tracing::info!(
1188        "task {} — {} (repo {})",
1189        task.short(),
1190        task.title,
1191        repo.display()
1192    );
1193
1194    let mut config = match prepare(&repo, opts) {
1195        Ok(c) => c,
1196        Err(e) => {
1197            // A setup failure spends an attempt even though no run was minted.
1198            // Without that, a task naming a repository that does not exist
1199            // would be retried at every poll for as long as the daemon lives.
1200            task.attempts += 1;
1201            task.fail(format!("config: {e:#}"), opts.max_attempts);
1202            record(queue, task);
1203            return Vec::new();
1204        }
1205    };
1206    apply_solo(&mut config, task);
1207
1208    // The free-space gate, checked *before* anything is minted: a task that
1209    // waits out a full disk costs nothing yet, and must not spend an attempt
1210    // or start a run the machine cannot finish. Held tasks stay in the list
1211    // for the human to see, and `magi task release` re-queues them when space
1212    // comes back - the same recovery as any other hold. A volume whose free
1213    // space cannot be measured closes the gate too: starting a run blind on a
1214    // disk that may be full is how the machine ends up with 6.7 GB free.
1215    if let Some(reason) = disk_gate(&repo, &config) {
1216        task.last_error = Some(reason.clone());
1217        task.hold(Some(reason.clone()));
1218        record(queue, task);
1219        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
1220        return Vec::new();
1221    }
1222
1223    // A resumable run of this task is carried on, never re-competed. The
1224    // candidates are built and paid for, and a fresh competition races a
1225    // second implementation against them.
1226    //
1227    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
1228    // started 3cbf on the same task a moment later, duplicating two and a
1229    // half hours of agent work. Then b25f stalled on a judge that timed out
1230    // and one that answered with no JSON - `quota: 0`, so nothing the machine
1231    // was to blame for - and 4043 started **one second** later, buying three
1232    // fresh implementations to reach the same panel. `RunStatus::resumable`
1233    // rather than `!done()` is what catches the second case: a stall is
1234    // terminal, and its cheap recovery re-asks only the absent seats.
1235    let unfinished = task
1236        .runs
1237        .iter()
1238        .rev()
1239        .find(|id| {
1240            RunState::load(id)
1241                .map(|s| s.status.resumable())
1242                .unwrap_or(false)
1243        })
1244        .cloned();
1245    let started = match &unfinished {
1246        Some(id) => {
1247            tracing::info!("resuming run {id} rather than competing again");
1248            Runner::resume(id)
1249        }
1250        None => Runner::start(&repo, task.instruction.clone(), config).await,
1251    };
1252    let mut runner = match started {
1253        Ok(r) => r,
1254        Err(e) => {
1255            task.attempts += 1;
1256            task.fail(format!("could not start the run: {e:#}"), opts.max_attempts);
1257            record(queue, task);
1258            return Vec::new();
1259        }
1260    };
1261    // A stop that means "park" reaches the graph through this handle.
1262    runner.on_pause(stop.pause());
1263
1264    // `start` has minted the run, so the task can now point at it. Persisting
1265    // `Running` before `execute` is what makes a crash mid-run legible.
1266    let run = runner.state.id.clone();
1267    task.start(run.clone());
1268    record(queue, task);
1269    lock(status).current.push(Current {
1270        task: task.id.clone(),
1271        run,
1272    });
1273
1274    let detail = match runner.execute().await {
1275        Ok(()) => describe(&runner.state),
1276        Err(e) => format!("{e:#}"),
1277    };
1278    let verdict = Verdict {
1279        status: runner.state.status,
1280        // A run that opened a pull request handed its work over, whatever the
1281        // gate then decided about merging it.
1282        left_pr: runner.state.pr.is_some(),
1283        // Only a rate limit earns the task its attempt back.
1284        quota_hit: !runner.state.quota.is_empty(),
1285        // A run that parked was asked to stop; that is not a failure and must
1286        // not spend an attempt, or replacing the binary a few times would
1287        // exhaust a task's budget without an agent ever misbehaving.
1288        parked: runner.state.parked,
1289        // A quota loss that left nothing viable is the same machine fact as a
1290        // `Stalled` quota loss; see `settle`'s doc table.
1291        no_viable_candidates: runner.state.viable().is_empty(),
1292    };
1293    settle(task, verdict, &detail, opts.max_attempts);
1294    record(queue, task);
1295    tracing::info!(
1296        "task {} is {} after run {} ({})",
1297        task.short(),
1298        task.status.as_str(),
1299        runner.state.short(),
1300        label(runner.state.status)
1301    );
1302    runner.state.quota
1303}
1304
1305/// Cut this attempt's candidate count to one when the task asked to run
1306/// alone.
1307///
1308/// Pure and separate from [`attempt`] so the one thing this feature changes -
1309/// which `candidates` a `solo` task's run is built with - can be asserted
1310/// without minting a run: `attempt` drives `graph::Runner`, which spawns real
1311/// agent CLIs, and no test may do that. `config` is mutated in place, taken by
1312/// value from the caller's own copy, so a repository's `magi.toml` on disk is
1313/// never touched - only the `Config` this one attempt hands to `Runner::start`.
1314fn apply_solo(config: &mut Config, task: &Task) {
1315    if task.solo {
1316        config.graph.candidates = 1;
1317    }
1318}
1319
1320/// Load the config for a task's repository, with the merge override applied.
1321fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
1322    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
1323    if let Some(mode) = &opts.merge {
1324        config.merge.mode = merge_mode(mode)?;
1325    }
1326    Ok(config)
1327}
1328
1329/// The disk janitor, with its housekeeping logged rather than fatal.
1330///
1331/// Called only at the loop's idle points, for the reason the caller documents:
1332/// a prune racing a live compile would delete files mid-build. The config is
1333/// re-read on every call because the repository that just ran may not be the
1334/// daemon's own default, and the cache directory is a repository fact.
1335///
1336/// `home` is a parameter rather than [`crate::run::home`] read here, for the
1337/// same reason [`drive`] takes its queue and status file rather than
1338/// resolving them: a test driving the loop must not reach through to the
1339/// operator's real home just because the janitor runs on every idle tick.
1340async fn janitor(repo: &Path, opts: &Opts, home: &Path) {
1341    let cfg = match prepare(repo, opts) {
1342        Ok(cfg) => cfg,
1343        Err(e) => {
1344            tracing::warn!("housekeep: no config: {e:#}");
1345            return;
1346        }
1347    };
1348    let out = clean::housekeep(
1349        &cfg,
1350        home,
1351        &crate::run::default_worktree_root(),
1352        Timestamp::now(),
1353    )
1354    .await;
1355    if out.folded > 0 {
1356        let unreadable = if out.unreadable > 0 {
1357            format!(" ({} unreadable)", out.unreadable)
1358        } else {
1359            String::new()
1360        };
1361        tracing::info!("housekeep: folded {} run(s){unreadable}", out.folded);
1362    }
1363    if out.cache_files > 0 {
1364        tracing::info!(
1365            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
1366            out.cache_files,
1367            out.cache_freed
1368        );
1369    }
1370}
1371
1372/// The free-space gate: what stands between this task and a new run, if
1373/// anything. `Some(reason)` holds the task; `None` lets it start.
1374///
1375/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
1376/// the operator opted out. A measurement failure is a gate, not a pass: both
1377/// sides of "cannot tell" are served by not starting.
1378fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
1379    let min = config.disk.min_free_bytes;
1380    if min == 0 {
1381        return None;
1382    }
1383    match crate::disk::free_bytes(repo) {
1384        Ok(free) => crate::disk::gate(free, min),
1385        Err(e) => Some(format!(
1386            "could not measure free space on {} ({e}); the disk gate refuses \
1387             to let a run start blind",
1388            repo.display()
1389        )),
1390    }
1391}
1392
1393/// How long to wait before offering another task when a run lost a seat to a
1394/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
1395/// could read, or carried nothing at all. Long enough that a quota outage
1396/// cannot burn through a whole backlog in the few seconds each doomed attempt
1397/// takes to fail; short enough that a quota which clears early is not left
1398/// idle for the fallback's sake.
1399const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
1400
1401/// Longest a parsed reset hint may push the wait out to. The hint comes from
1402/// the CLI's own words, not a contract, so a parsing slip that lands a day
1403/// away must not leave the loop asleep for a day.
1404const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
1405
1406/// How long [`poll`] should wait before offering the next task, after a run
1407/// lost at least one seat to a rate limit.
1408///
1409/// Pure and separate from the loop so the policy can be exercised without a
1410/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
1411/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
1412/// nothing to parse, or the parsed time has already passed; `cap` bounds how
1413/// far a parsed hint is trusted to push the wait out.
1414fn quota_wait(
1415    reset_at: Option<Timestamp>,
1416    now: Timestamp,
1417    fallback: Duration,
1418    cap: Duration,
1419) -> Duration {
1420    match reset_at {
1421        Some(at) if at > now => {
1422            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
1423            Duration::from_secs(secs).min(cap)
1424        }
1425        _ => fallback,
1426    }
1427}
1428
1429/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
1430///
1431/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
1432/// explains why parsing it exactly "would be a bug factory" — so this only
1433/// recognises the one shape actually observed in the wild, `"H:MMam/pm
1434/// (Zone)"`, and returns `None` for anything else rather than guess at a
1435/// format nobody has seen. A clock reading already past today is read as
1436/// tomorrow's: a CLI naming a same-day reset that has already gone by means
1437/// the window rolled over while nothing was watching.
1438fn parse_reset_hint(text: &str, now: Timestamp) -> Option<Timestamp> {
1439    let open = text.find('(')?;
1440    let close = text.rfind(')')?;
1441    if close <= open {
1442        return None;
1443    }
1444    let zone = text[open + 1..close].trim();
1445    let clock = text[..open].trim().to_lowercase();
1446    let (digits, pm) = clock
1447        .strip_suffix("am")
1448        .map(|d| (d, false))
1449        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
1450    let (h, m) = digits.trim().split_once(':')?;
1451    let mut hour: i8 = h.trim().parse().ok()?;
1452    let minute: i8 = m.trim().parse().ok()?;
1453    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
1454        return None;
1455    }
1456    if pm && hour != 12 {
1457        hour += 12;
1458    } else if !pm && hour == 12 {
1459        hour = 0;
1460    }
1461    let tz = jiff::tz::TimeZone::get(zone).ok()?;
1462    let candidate = now
1463        .to_zoned(tz)
1464        .with()
1465        .hour(hour)
1466        .minute(minute)
1467        .second(0)
1468        .millisecond(0)
1469        .microsecond(0)
1470        .nanosecond(0)
1471        .build()
1472        .ok()?;
1473    let mut at = candidate.timestamp();
1474    if at <= now {
1475        at += jiff::SignedDuration::from_hours(24);
1476    }
1477    Some(at)
1478}
1479
1480/// Which repository a task runs in. A task that names none — the normal case
1481/// for one filed from a phone — runs in the daemon's own default.
1482fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
1483    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
1484        return fallback.to_path_buf();
1485    }
1486    task.repo.clone()
1487}
1488
1489/// Persist a transition. A queue write failure is logged rather than fatal: the
1490/// run already happened, and taking the daemon down would only add a lost
1491/// backlog to a full disk.
1492fn record(queue: &Queue, task: &mut Task) {
1493    if let Err(e) = queue.put(task) {
1494        tracing::error!("could not record task {}: {e:#}", task.short());
1495    }
1496}
1497
1498/// Every runnable task, in the order the loop should try them.
1499///
1500/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
1501/// tail exists so that a claim somebody else holds costs the loop the next
1502/// candidate rather than a whole poll interval of idleness.
1503fn runnable(queue: &Queue) -> Vec<Task> {
1504    let mut tasks: Vec<Task> = queue
1505        .list()
1506        .into_iter()
1507        .filter(|t| t.status.runnable())
1508        .collect();
1509    tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
1510    tasks
1511}
1512
1513/// Why a run ended where it did, in one line, for [`Task::last_error`].
1514///
1515/// A stalled run names the seats the quota took out: "out of quota" is not
1516/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
1517/// agent to replace or which plan to top up.
1518fn describe(state: &RunState) -> String {
1519    let mut detail = if state.status == RunStatus::Stalled {
1520        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
1521        seats.sort_unstable();
1522        seats.dedup();
1523        if seats.is_empty() {
1524            "the judging panel lost its quorum".to_owned()
1525        } else {
1526            format!(
1527                "the judging panel lost its quorum; quota took out {}",
1528                seats.join(", ")
1529            )
1530        }
1531    } else {
1532        format!("run ended {}", label(state.status))
1533    };
1534    if let Some(last) = state.events.last() {
1535        detail.push_str(&format!(" ({}: {})", last.node, last.message));
1536    }
1537    detail.push_str(&format!(" [run {}]", state.id));
1538    detail
1539}
1540
1541/// Stable lower-case name for a run status, for logs and task errors.
1542/// One definition of a status's name, on the type that owns it: this table
1543/// used to live here as a second copy, and a status renamed in one place would
1544/// have gone on reading correctly in the other.
1545fn label(status: RunStatus) -> &'static str {
1546    status.as_str()
1547}
1548
1549/// Parse a merge mode override.
1550fn merge_mode(mode: &str) -> Result<MergeMode> {
1551    match mode {
1552        "none" => Ok(MergeMode::None),
1553        "local" => Ok(MergeMode::Local),
1554        "pr" => Ok(MergeMode::Pr),
1555        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
1556    }
1557}
1558
1559/// Take the status lock, recovering from a poisoned one.
1560///
1561/// A panic elsewhere must not silently stop the heartbeat: the status is plain
1562/// data, and the worst a poisoned lock can hold is a stale timestamp.
1563fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
1564    mutex
1565        .lock()
1566        .unwrap_or_else(std::sync::PoisonError::into_inner)
1567}
1568
1569#[cfg(test)]
1570mod tests {
1571    use super::*;
1572    use crate::queue::{Source, TaskStatus};
1573    use pretty_assertions::assert_eq;
1574
1575    fn task() -> Task {
1576        Task::new(
1577            "add retries".to_owned(),
1578            "add retries".to_owned(),
1579            PathBuf::from("/repo"),
1580            Source::Human,
1581        )
1582    }
1583
1584    #[test]
1585    fn every_run_status_settles_the_task_it_came_from() {
1586        // run status, resulting task status, attempts still standing after one
1587        let table = [
1588            (RunStatus::Merged, TaskStatus::Done, 1),
1589            (RunStatus::Ready, TaskStatus::Done, 1),
1590            (RunStatus::Stalled, TaskStatus::Failed, 0),
1591            (RunStatus::Blocked, TaskStatus::Failed, 1),
1592            (RunStatus::Failed, TaskStatus::Failed, 1),
1593            (RunStatus::Prep, TaskStatus::Failed, 1),
1594            (RunStatus::Implementing, TaskStatus::Failed, 1),
1595            (RunStatus::Judging, TaskStatus::Failed, 1),
1596            (RunStatus::Deliberating, TaskStatus::Failed, 1),
1597            (RunStatus::Voting, TaskStatus::Failed, 1),
1598            (RunStatus::Reviewing, TaskStatus::Failed, 1),
1599            (RunStatus::Gating, TaskStatus::Failed, 1),
1600        ];
1601        for (run, want, attempts) in table {
1602            let mut t = task();
1603            t.start("20260902-000000-aaaa".to_owned());
1604            settle(
1605                &mut t,
1606                Verdict {
1607                    status: run,
1608                    left_pr: false,
1609                    parked: false,
1610                    quota_hit: matches!(run, RunStatus::Stalled),
1611                    no_viable_candidates: false,
1612                },
1613                "why",
1614                2,
1615            );
1616            assert_eq!(t.status, want, "task status after {}", label(run));
1617            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
1618        }
1619    }
1620
1621    #[test]
1622    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
1623        let mut stalled = task();
1624        stalled.start("20260902-000000-aaaa".to_owned());
1625        settle(
1626            &mut stalled,
1627            Verdict {
1628                status: RunStatus::Stalled,
1629                left_pr: false,
1630                parked: false,
1631                quota_hit: true,
1632                no_viable_candidates: false,
1633            },
1634            "quota",
1635            1,
1636        );
1637        assert_eq!(stalled.attempts, 0);
1638        assert!(
1639            stalled.status.runnable(),
1640            "a machine problem must leave the task in line"
1641        );
1642
1643        let mut blocked = task();
1644        blocked.start("20260902-000000-aaaa".to_owned());
1645        settle(
1646            &mut blocked,
1647            Verdict {
1648                status: RunStatus::Blocked,
1649                left_pr: false,
1650                parked: false,
1651                quota_hit: false,
1652                no_viable_candidates: false,
1653            },
1654            "findings open",
1655            1,
1656        );
1657        assert_eq!(blocked.attempts, 1);
1658        assert_eq!(
1659            blocked.status,
1660            TaskStatus::Held,
1661            "the last attempt hands the task to a human"
1662        );
1663    }
1664
1665    #[test]
1666    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
1667        // Attempts to spare: without the pull request this task would go
1668        // straight back in line and run the whole competition again.
1669        let mut delivered = task();
1670        delivered.start("20260903-080619-01c2".to_owned());
1671        settle(
1672            &mut delivered,
1673            Verdict {
1674                status: RunStatus::Blocked,
1675                left_pr: true,
1676                parked: false,
1677                quota_hit: false,
1678                no_viable_candidates: false,
1679            },
1680            "no check status",
1681            4,
1682        );
1683        assert_eq!(
1684            delivered.status,
1685            TaskStatus::Held,
1686            "a pull request waiting on CI or a person is not a retryable failure"
1687        );
1688        assert!(
1689            !delivered.status.runnable(),
1690            "the loop must not pick this task up again"
1691        );
1692        assert_eq!(
1693            delivered.last_error.as_deref(),
1694            Some("no check status"),
1695            "the operator needs to be told what the gate was waiting for"
1696        );
1697
1698        // The same status without a pull request is a plain failure, and with
1699        // attempts left it is retried.
1700        let mut empty_handed = task();
1701        empty_handed.start("20260903-080619-01c2".to_owned());
1702        settle(
1703            &mut empty_handed,
1704            Verdict {
1705                status: RunStatus::Blocked,
1706                left_pr: false,
1707                parked: false,
1708                quota_hit: false,
1709                no_viable_candidates: false,
1710            },
1711            "findings open",
1712            4,
1713        );
1714        assert_eq!(empty_handed.status, TaskStatus::Failed);
1715        assert!(empty_handed.status.runnable());
1716    }
1717
1718    #[test]
1719    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
1720        // Parking is the operator asking for the process back - to replace the
1721        // binary, most of all. The run's work is intact on disk, so this is
1722        // not a failed attempt, and charging for it would mean a few upgrades
1723        // could exhaust a budget meant for agents that misbehaved.
1724        let mut parked = task();
1725        parked.start("20260903-183634-2d98".to_owned());
1726        settle(
1727            &mut parked,
1728            Verdict {
1729                status: RunStatus::Implementing,
1730                left_pr: false,
1731                quota_hit: false,
1732                parked: true,
1733                no_viable_candidates: false,
1734            },
1735            "parked after `implementing`",
1736            2,
1737        );
1738        assert_eq!(parked.attempts, 0, "a park is refunded");
1739        assert!(
1740            parked.status.runnable(),
1741            "and the task stays in line so the next loop resumes its run"
1742        );
1743        assert_eq!(
1744            parked.last_error.as_deref(),
1745            Some("parked after `implementing`"),
1746            "the card says where it stopped"
1747        );
1748
1749        // Without the park flag the same non-terminal status is what it always
1750        // was: `execute` returning mid-flight, which is a bug and spends an
1751        // attempt so a task cannot loop on it forever.
1752        let mut broken = task();
1753        broken.start("20260903-183634-2d98".to_owned());
1754        settle(
1755            &mut broken,
1756            Verdict {
1757                status: RunStatus::Implementing,
1758                left_pr: false,
1759                quota_hit: false,
1760                parked: false,
1761                no_viable_candidates: false,
1762            },
1763            "returned mid-flight",
1764            2,
1765        );
1766        assert_eq!(broken.attempts, 1);
1767    }
1768
1769    #[test]
1770    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
1771        // Run e633: quorum lost because two judges answered with the wrong
1772        // JSON shape, `quota: []`. Refunding that takes the bound off the
1773        // retry loop, and each retry pays for a fresh hour-long implement
1774        // wave before it can fail the same way.
1775        let mut flaky = task();
1776        flaky.start("20260903-123023-e633".to_owned());
1777        settle(
1778            &mut flaky,
1779            Verdict {
1780                status: RunStatus::Stalled,
1781                left_pr: false,
1782                parked: false,
1783                quota_hit: false,
1784                no_viable_candidates: false,
1785            },
1786            "verdict rests on 1 of 3 judges",
1787            2,
1788        );
1789        assert_eq!(
1790            flaky.attempts, 1,
1791            "flakiness spends an attempt, so `max_attempts` still bounds it"
1792        );
1793        assert!(flaky.status.runnable(), "and it is still worth retrying");
1794
1795        // The same status, lost to a rate limit, is the machine's fault.
1796        let mut limited = task();
1797        limited.start("20260903-123023-e633".to_owned());
1798        settle(
1799            &mut limited,
1800            Verdict {
1801                status: RunStatus::Stalled,
1802                left_pr: false,
1803                parked: false,
1804                quota_hit: true,
1805                no_viable_candidates: false,
1806            },
1807            "judge-2, judge-3 out of quota",
1808            2,
1809        );
1810        assert_eq!(limited.attempts, 0, "a quota window is refunded");
1811        assert!(limited.status.runnable());
1812
1813        // And the bound really binds: a task that keeps stalling on flakiness
1814        // reaches a human instead of running the roster forever.
1815        let mut worn = task();
1816        for _ in 0..2 {
1817            worn.release();
1818        }
1819        worn.start("20260903-123023-e633".to_owned());
1820        worn.attempts = 2;
1821        settle(
1822            &mut worn,
1823            Verdict {
1824                status: RunStatus::Stalled,
1825                left_pr: false,
1826                parked: false,
1827                quota_hit: false,
1828                no_viable_candidates: false,
1829            },
1830            "no quorum again",
1831            2,
1832        );
1833        assert_eq!(worn.status, TaskStatus::Held);
1834        assert!(!worn.status.runnable());
1835    }
1836
1837    #[test]
1838    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
1839        // The implement wave loses every seat to the same rate limit and
1840        // `after_implement` bails with nothing viable, which surfaces as
1841        // `Failed` rather than `Stalled`. That is the same machine fact the
1842        // `Stalled`-quota row already refunds, and must be refunded the same
1843        // way, or a quota outage quietly holds every task it touches instead
1844        // of leaving them in line for the reset.
1845        let mut wiped_out = task();
1846        wiped_out.start("20260907-025000-a1b2".to_owned());
1847        settle(
1848            &mut wiped_out,
1849            Verdict {
1850                status: RunStatus::Failed,
1851                left_pr: false,
1852                parked: false,
1853                quota_hit: true,
1854                no_viable_candidates: true,
1855            },
1856            "no candidate produced a change; nothing to judge",
1857            2,
1858        );
1859        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
1860        assert!(
1861            wiped_out.status.runnable(),
1862            "a machine problem must leave the task in line"
1863        );
1864
1865        // This is the exemption that must stay narrow: a candidate that did
1866        // produce a change, and then failed for some other reason, still
1867        // spends the attempt even though a seat elsewhere hit its quota.
1868        // Otherwise every ordinary failure that happens to share a run with
1869        // an unrelated rate limit would be refunded for free.
1870        let mut partial_progress = task();
1871        partial_progress.start("20260907-025500-c3d4".to_owned());
1872        settle(
1873            &mut partial_progress,
1874            Verdict {
1875                status: RunStatus::Failed,
1876                left_pr: false,
1877                parked: false,
1878                quota_hit: true,
1879                no_viable_candidates: false,
1880            },
1881            "gate failed on the winning candidate",
1882            2,
1883        );
1884        assert_eq!(
1885            partial_progress.attempts, 1,
1886            "a candidate that actually produced a change spends the attempt \
1887             even though some other seat hit its quota"
1888        );
1889        assert!(partial_progress.status.runnable());
1890    }
1891
1892    #[test]
1893    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
1894        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
1895        // disk, and that construction must reach the same conclusion as the
1896        // one `attempt` builds from a live run, or a crash at exactly the
1897        // wrong moment gives a recovered task a different policy than one a
1898        // daemon finished settling itself.
1899        let mut t = task();
1900        t.start("20260907-025000-a1b2".to_owned());
1901        let mut state = run_state(RunStatus::Failed);
1902        state.quota.push(QuotaLoss {
1903            seat: "cand-a".to_owned(),
1904            node: "implement".to_owned(),
1905            at: Timestamp::now(),
1906            reset: None,
1907        });
1908        assert!(
1909            state.viable().is_empty(),
1910            "no candidate was added, so nothing is viable"
1911        );
1912        reclaim(&mut t, Some(state), 2);
1913        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
1914        assert!(t.status.runnable());
1915    }
1916
1917    #[test]
1918    fn a_held_task_is_never_offered_to_the_loop() {
1919        let dir = tempfile::tempdir().unwrap();
1920        let queue = Queue::at(dir.path().to_path_buf());
1921        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
1922            let mut t = task();
1923            t.id = format!("2026090{n}-000000-000{n}");
1924            t.priority = priority;
1925            queue.put(&mut t).unwrap();
1926        }
1927        let mut held = task();
1928        held.id = "20260909-000000-9999".to_owned();
1929        held.priority = 99;
1930        held.hold(None);
1931        queue.put(&mut held).unwrap();
1932
1933        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
1934        assert_eq!(order.len(), 3);
1935        assert!(!order.contains(&held.id));
1936        assert_eq!(
1937            order.first().cloned(),
1938            queue.next_runnable().map(|t| t.id),
1939            "the loop's first candidate is exactly what the queue offers"
1940        );
1941        assert_eq!(
1942            order,
1943            vec![
1944                "20260902-000000-0002".to_owned(),
1945                "20260903-000000-0003".to_owned(),
1946                "20260901-000000-0001".to_owned(),
1947            ],
1948            "priority first, then oldest, so nothing starves"
1949        );
1950    }
1951
1952    #[test]
1953    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
1954        let dir = tempfile::tempdir().unwrap();
1955        let queue = Queue::at(dir.path().to_path_buf());
1956        let mut old = task();
1957        old.id = "20260101-000000-old0".to_owned();
1958        queue.put(&mut old).unwrap();
1959        let mut fresh = task();
1960        fresh.id = "20260101-000000-new0".to_owned();
1961        queue.put(&mut fresh).unwrap();
1962
1963        // No parseable pid at all, so age is the only signal there is to
1964        // check - unlike a real `Queue::claim`, which always names a real,
1965        // and therefore alive, pid this test cannot fake as dead.
1966        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
1967        std::thread::sleep(Duration::from_millis(60));
1968        let live = queue.claim(&fresh.id).unwrap();
1969
1970        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
1971        assert_eq!(swept, vec![old.id.clone()]);
1972        assert!(
1973            queue.claim(&old.id).is_ok(),
1974            "an unparseable lock older than the threshold is swept"
1975        );
1976        assert!(
1977            queue.claim(&fresh.id).is_err(),
1978            "a live pid protects its lock regardless of age"
1979        );
1980        drop(live);
1981    }
1982
1983    #[test]
1984    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
1985        // The regression this guards: `sweep` now runs concurrently with
1986        // every attempt this daemon itself has spawned (see
1987        // `InFlightGuard`), not only between them the way a single
1988        // sequential loop once did. A run that legitimately outlives
1989        // `older_than` still has this very process's own live pid sitting in
1990        // its own lock file on every later sweep, and deciding by age alone
1991        // would delete that still-valid claim out from under the attempt
1992        // that holds it - which `reclaim_orphaned_running` would then read
1993        // as abandoned and hand to a second, competing attempt.
1994        let dir = tempfile::tempdir().unwrap();
1995        let queue = Queue::at(dir.path().to_path_buf());
1996        let mut t = task();
1997        t.id = "20260101-000000-live".to_owned();
1998        queue.put(&mut t).unwrap();
1999
2000        let claim = queue.claim(&t.id).unwrap();
2001        std::thread::sleep(Duration::from_millis(60));
2002
2003        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
2004        assert!(
2005            swept.is_empty(),
2006            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
2007        );
2008        assert!(
2009            queue.claim(&t.id).is_err(),
2010            "the lock still protects its task"
2011        );
2012        drop(claim);
2013    }
2014
2015    /// A pid past any real process table, but not `u32::MAX`: Windows'
2016    /// `tasklist` answers that one with "invalid query" rather than "no such
2017    /// process", which [`crate::proc::pid_alive`] - correctly - cannot tell
2018    /// apart from a check it simply could not run, so it would read as
2019    /// alive. See `proc::tests` for the same choice made for the same
2020    /// reason.
2021    const DEAD_PID: u32 = 999_999_999;
2022
2023    #[test]
2024    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
2025        let dir = tempfile::tempdir().unwrap();
2026        let queue = Queue::at(dir.path().to_path_buf());
2027        let mut t = task();
2028        t.id = "20260101-000000-dead".to_owned();
2029        queue.put(&mut t).unwrap();
2030
2031        // Written directly rather than through `Queue::claim`, which would
2032        // stamp this test process's own very much alive pid and defeat the
2033        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
2034        // like moments after it died, not six hours later.
2035        std::fs::write(
2036            dir.path().join(format!("{}.lock", t.id)),
2037            DEAD_PID.to_string(),
2038        )
2039        .unwrap();
2040
2041        let swept = sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60));
2042        assert_eq!(
2043            swept,
2044            vec![t.id.clone()],
2045            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
2046        );
2047        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
2048    }
2049
2050    #[test]
2051    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
2052        let dir = tempfile::tempdir().unwrap();
2053        let queue = Queue::at(dir.path().to_path_buf());
2054        let mut t = task();
2055        t.id = "20260101-000000-late".to_owned();
2056        queue.put(&mut t).unwrap();
2057
2058        // Tick one, standing in for the sweep `poll` already runs at
2059        // startup: nothing to find yet.
2060        assert!(
2061            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
2062            "nothing has claimed the task yet"
2063        );
2064
2065        // A second daemon claims the task and dies before it ever writes
2066        // `running`, well after this loop's own startup sweep already ran.
2067        std::fs::write(
2068            dir.path().join(format!("{}.lock", t.id)),
2069            DEAD_PID.to_string(),
2070        )
2071        .unwrap();
2072
2073        // Tick two, standing in for a poll long into this daemon's uptime:
2074        // the same function, called again, notices what only just appeared -
2075        // proving the sweep is not a one-shot startup check.
2076        let swept = sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60));
2077        assert_eq!(swept, vec![t.id.clone()]);
2078    }
2079
2080    #[test]
2081    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
2082        // `reclaim_orphaned_running` looks up the task's last run, which
2083        // touches `run::home()`; the first call anywhere in this binary wins,
2084        // so this is a no-op if another test already pinned one, and either
2085        // way the run id below is never written under it.
2086        crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
2087        let dir = tempfile::tempdir().unwrap();
2088        let queue = Queue::at(dir.path().to_path_buf());
2089        let mut t = task();
2090        t.id = "20260101-000000-crsh".to_owned();
2091        t.status = TaskStatus::Running;
2092        t.attempts = 1;
2093        // No `run.json` behind this id: standing in for a run this test does
2094        // not need to make readable, since the point is the lock, not the
2095        // recovery table `reclaim` already has its own tests for.
2096        t.runs.push("20260904-000000-4043".to_owned());
2097        queue.put(&mut t).unwrap();
2098
2099        // The crashed daemon's own claim, naming a pid nothing on the
2100        // machine holds anymore.
2101        std::fs::write(
2102            dir.path().join(format!("{}.lock", t.id)),
2103            DEAD_PID.to_string(),
2104        )
2105        .unwrap();
2106
2107        // Before the lock is swept the task looks claimed, and
2108        // `reclaim_orphaned_running` must leave it alone - this is exactly
2109        // the bug: a `running` task stranded behind a dead daemon's lock,
2110        // invisible to the claim-as-proof check because the lock outlived
2111        // the process that wrote it.
2112        assert!(reclaim_orphaned_running(&queue, 2).is_empty());
2113        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
2114
2115        let swept = sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60));
2116        assert_eq!(swept, vec![t.id.clone()]);
2117
2118        let reclaimed = reclaim_orphaned_running(&queue, 2);
2119        assert_eq!(reclaimed, vec![t.id.clone()]);
2120        let after = queue.get(&t.id).unwrap();
2121        assert_eq!(
2122            after.status,
2123            TaskStatus::Held,
2124            "no run.json to recover from, so a human is asked"
2125        );
2126        assert_eq!(
2127            after.runs,
2128            vec!["20260904-000000-4043".to_owned()],
2129            "the crashed run's id is kept as evidence, not discarded"
2130        );
2131    }
2132
2133    fn run_state(status: RunStatus) -> RunState {
2134        let mut state = RunState::new(
2135            PathBuf::from("/repo"),
2136            "main".to_owned(),
2137            "abc1234def".to_owned(),
2138            "add retries".to_owned(),
2139            Config::default(),
2140        );
2141        state.status = status;
2142        state
2143    }
2144
2145    fn approval_question(run: &str) -> ask::Question {
2146        ask::Question::new(
2147            run.to_owned(),
2148            land::APPROVAL_NODE.to_owned(),
2149            "land".to_owned(),
2150            "merge?".to_owned(),
2151            String::new(),
2152            vec!["merge".to_owned(), "hold".to_owned()],
2153        )
2154    }
2155
2156    #[test]
2157    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
2158        crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
2159        let mut state = run_state(RunStatus::Landing);
2160        state.id = "20260101-000000-fre1".to_owned();
2161        state.parked = true;
2162        state.save().unwrap();
2163        ask::Questions::open()
2164            .put(&mut approval_question(&state.id))
2165            .unwrap();
2166
2167        let mut t = task();
2168        t.runs.push(state.id.clone());
2169        assert_eq!(
2170            land_resume_state(&t),
2171            LandResume::StillWaiting,
2172            "nobody has answered and the timeout has not passed"
2173        );
2174    }
2175
2176    #[test]
2177    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
2178        // `ask::ask_and_wait`'s own deadline used to retire a question
2179        // nobody answered; land's approval bypasses that wait (see
2180        // `land::approval_gate`), so this is now the only place
2181        // `graph.answer_timeout` is enforced for a land approval at all.
2182        crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
2183        let mut state = run_state(RunStatus::Landing);
2184        state.id = "20260101-000000-exp1".to_owned();
2185        state.parked = true;
2186        state.config.graph.answer_timeout = 60;
2187        state.save().unwrap();
2188
2189        let store = ask::Questions::open();
2190        let mut q = approval_question(&state.id);
2191        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
2192        store.put(&mut q).unwrap();
2193
2194        let mut t = task();
2195        t.runs.push(state.id.clone());
2196        assert_eq!(
2197            land_resume_state(&t),
2198            LandResume::Ready,
2199            "an expired question must not be waited on forever"
2200        );
2201
2202        let after = store.get(&q.id).unwrap();
2203        assert!(
2204            !after.status.open(),
2205            "the question is abandoned, not silently ignored"
2206        );
2207        assert!(
2208            after.resolution().is_none(),
2209            "an abandoned question is not read as a decision"
2210        );
2211    }
2212
2213    #[test]
2214    fn reclaim_settles_a_running_task_against_its_last_run() {
2215        let mut t = task();
2216        t.start("20260904-000000-4043".to_owned());
2217        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2);
2218        assert_eq!(
2219            t.status,
2220            TaskStatus::Done,
2221            "a run that actually finished must not stay `running` forever"
2222        );
2223    }
2224
2225    #[test]
2226    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
2227        // A blocked run with attempts left goes back to `Failed`, exactly as
2228        // it would from `attempt` itself - `reclaim` must not invent a second
2229        // policy for a task a daemon merely stopped without reporting.
2230        let mut t = task();
2231        t.start("20260904-000000-4043".to_owned());
2232        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2);
2233        assert_eq!(t.status, TaskStatus::Failed);
2234        assert!(t.status.runnable());
2235    }
2236
2237    #[test]
2238    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
2239        let mut t = task();
2240        t.start("20260904-000000-4043".to_owned());
2241        reclaim(&mut t, None, 2);
2242        assert_eq!(t.status, TaskStatus::Held);
2243        assert!(
2244            t.last_error
2245                .as_deref()
2246                .is_some_and(|e| e.contains("running")),
2247            "the operator needs to know why this task was held"
2248        );
2249    }
2250
2251    #[test]
2252    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
2253        let dir = tempfile::tempdir().unwrap();
2254        let queue = Queue::at(dir.path().to_path_buf());
2255
2256        // No run recorded, so this never has to touch `RunState::load`.
2257        let mut orphaned = task();
2258        orphaned.id = "20260904-000000-orph".to_owned();
2259        orphaned.status = TaskStatus::Running;
2260        orphaned.attempts = 1;
2261        queue.put(&mut orphaned).unwrap();
2262
2263        let mut alive = task();
2264        alive.id = "20260904-000000-live".to_owned();
2265        alive.status = TaskStatus::Running;
2266        alive.attempts = 1;
2267        queue.put(&mut alive).unwrap();
2268        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
2269
2270        let mut queued = task();
2271        queued.id = "20260904-000000-wait".to_owned();
2272        queue.put(&mut queued).unwrap();
2273
2274        let reclaimed = reclaim_orphaned_running(&queue, 2);
2275        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
2276
2277        assert_eq!(
2278            queue.get(&orphaned.id).unwrap().status,
2279            TaskStatus::Held,
2280            "nothing was driving it and there was no run to recover"
2281        );
2282        assert_eq!(
2283            queue.get(&alive.id).unwrap().status,
2284            TaskStatus::Running,
2285            "a live claim must protect the task it belongs to"
2286        );
2287        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
2288    }
2289
2290    #[test]
2291    fn an_already_claimed_task_is_skipped_rather_than_failed() {
2292        let dir = tempfile::tempdir().unwrap();
2293        let queue = Queue::at(dir.path().to_path_buf());
2294        let mut only = task();
2295        queue.put(&mut only).unwrap();
2296
2297        let _elsewhere = queue.claim(&only.id).unwrap();
2298        let candidates = runnable(&queue);
2299        assert_eq!(candidates.len(), 1, "the task is still runnable");
2300        assert!(
2301            queue.claim(&candidates[0].id).is_err(),
2302            "the loop cannot take a claim somebody else holds"
2303        );
2304
2305        let after = queue.get(&only.id).unwrap();
2306        assert_eq!(after.status, TaskStatus::Queued);
2307        assert_eq!(
2308            after.attempts, 0,
2309            "losing the race is not an attempt at the task"
2310        );
2311        assert_eq!(after.last_error, None);
2312    }
2313
2314    #[test]
2315    fn the_status_file_round_trips_and_its_heartbeat_advances() {
2316        let dir = tempfile::tempdir().unwrap();
2317        let path = dir.path().join("daemon.json");
2318
2319        let mut status = Status::new();
2320        status.idle = false;
2321        status.completed = 7;
2322        status.current = vec![Current {
2323            task: "20260902-000000-t111".to_owned(),
2324            run: "20260902-000001-r111".to_owned(),
2325        }];
2326        write_status_to(&path, &status).unwrap();
2327        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
2328        assert_eq!(first.schema, SCHEMA);
2329        assert_eq!(first.pid, std::process::id());
2330        assert!(!first.idle);
2331        assert_eq!(first.completed, 7);
2332        assert_eq!(first.current, status.current);
2333        assert!(
2334            !path.with_extension("json.tmp").exists(),
2335            "the temp file is renamed, not left behind"
2336        );
2337
2338        std::thread::sleep(Duration::from_millis(5));
2339        status.updated_at = Timestamp::now();
2340        status.polls = 3;
2341        write_status_to(&path, &status).unwrap();
2342        let second: Status =
2343            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
2344        assert!(
2345            second.updated_at > first.updated_at,
2346            "a reader can only detect staleness if the heartbeat moves"
2347        );
2348        assert_eq!(
2349            second.started_at, first.started_at,
2350            "the start time is not a heartbeat"
2351        );
2352        assert_eq!(second.polls, 3);
2353    }
2354
2355    #[test]
2356    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
2357        let dir = tempfile::tempdir().unwrap();
2358
2359        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
2360
2361        let mut status = Status::new();
2362        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
2363        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
2364        let stale = read_status(dir.path()).unwrap();
2365        assert!(
2366            !stale.running(Timestamp::now()),
2367            "a minute without a heartbeat is a dead daemon, not a busy one"
2368        );
2369        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
2370
2371        status.updated_at = Timestamp::now();
2372        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
2373        let fresh = read_status(dir.path()).unwrap();
2374        assert!(fresh.running(Timestamp::now()));
2375    }
2376
2377    #[test]
2378    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
2379        let dir = tempfile::tempdir().unwrap();
2380        let now = Timestamp::now();
2381        let mine = "20260903-080619-01c2";
2382
2383        assert!(
2384            !is_working_on(dir.path(), mine, now),
2385            "no status file means nobody is working on anything"
2386        );
2387
2388        let mut status = Status::new();
2389        status.current = vec![Current {
2390            task: "20260903-080340-0167".to_owned(),
2391            run: mine.to_owned(),
2392        }];
2393        status.updated_at = now;
2394        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
2395        assert!(is_working_on(dir.path(), mine, now));
2396        assert!(
2397            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
2398            "a daemon busy with one run is not working on another"
2399        );
2400
2401        // A killed daemon stops writing heartbeats but leaves the file behind
2402        // naming the run it died in. That run must not be undeletable forever.
2403        status.updated_at = now - jiff::SignedDuration::from_secs(600);
2404        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
2405        assert!(
2406            !is_working_on(dir.path(), mine, now),
2407            "a stale heartbeat is a dead daemon, so its run is a leftover"
2408        );
2409    }
2410
2411    #[test]
2412    fn a_newer_status_file_still_yields_a_reading() {
2413        let dir = tempfile::tempdir().unwrap();
2414        // A field this build has never heard of must not turn the reading into
2415        // nothing at all; that is the whole reason the reader is permissive.
2416        std::fs::write(
2417            dir.path().join("daemon.json"),
2418            serde_json::json!({
2419                "schema": 2,
2420                "updated_at": Timestamp::now().to_string(),
2421                "idle": true,
2422                "surprise": { "nested": [1, 2, 3] },
2423            })
2424            .to_string(),
2425        )
2426        .unwrap();
2427
2428        let reading = read_status(dir.path()).expect("a forward-compatible read");
2429        assert!(reading.running(Timestamp::now()));
2430        assert!(reading.idle);
2431        assert!(reading.current.is_empty());
2432    }
2433
2434    #[test]
2435    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
2436        // A daemon started before `current` became a list keeps writing this
2437        // shape on every heartbeat until it is restarted. A rolling upgrade
2438        // - a newer `magi web` or `magi doctor` reading an older `magi
2439        // serve`'s heartbeat - must still see the run it is on, not "no
2440        // daemon" from a type mismatch failing the whole struct.
2441        let dir = tempfile::tempdir().unwrap();
2442        std::fs::write(
2443            dir.path().join("daemon.json"),
2444            serde_json::json!({
2445                "schema": 1,
2446                "pid": 4242,
2447                "updated_at": Timestamp::now().to_string(),
2448                "idle": false,
2449                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
2450                "completed": 3,
2451                "polls": 9,
2452            })
2453            .to_string(),
2454        )
2455        .unwrap();
2456
2457        let reading = read_status(dir.path()).expect("an older shape must still parse");
2458        assert!(reading.running(Timestamp::now()));
2459        assert_eq!(
2460            reading.current,
2461            vec![Current {
2462                task: "20260902-140501-aaaa".to_owned(),
2463                run: "20260902-140502-bbbb".to_owned(),
2464            }]
2465        );
2466    }
2467
2468    #[test]
2469    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
2470        let dir = tempfile::tempdir().unwrap();
2471        std::fs::write(
2472            dir.path().join("daemon.json"),
2473            serde_json::json!({
2474                "schema": 1,
2475                "updated_at": Timestamp::now().to_string(),
2476                "idle": true,
2477                "current": null,
2478            })
2479            .to_string(),
2480        )
2481        .unwrap();
2482        let with_null = read_status(dir.path()).expect("null must still parse");
2483        assert!(with_null.current.is_empty());
2484
2485        std::fs::write(
2486            dir.path().join("daemon.json"),
2487            serde_json::json!({
2488                "schema": 1,
2489                "updated_at": Timestamp::now().to_string(),
2490                "idle": true,
2491            })
2492            .to_string(),
2493        )
2494        .unwrap();
2495        let absent = read_status(dir.path()).expect("a missing field must still parse");
2496        assert!(absent.current.is_empty());
2497    }
2498
2499    #[test]
2500    fn a_task_without_a_repository_runs_in_the_daemons_default() {
2501        let fallback = Path::new("/default");
2502        let mut blank = task();
2503        blank.repo = PathBuf::new();
2504        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
2505        let mut dot = task();
2506        dot.repo = PathBuf::from(".");
2507        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
2508        assert_eq!(
2509            repo_for(&task(), fallback),
2510            PathBuf::from("/repo"),
2511            "a task that names a repository keeps it"
2512        );
2513    }
2514
2515    #[test]
2516    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
2517        // Three seats said out loud. What `solo` promises is one candidate
2518        // *whatever the config asks for*, so the contrast has to be a number
2519        // this test owns - it used to be `Config::default()`'s, which became
2520        // 1 when one implementation became the default and left the two
2521        // halves of this test asserting the same thing.
2522        let mut solo_cfg = Config::default();
2523        solo_cfg.graph.candidates = 3;
2524        let mut solo_task = task();
2525        solo_task.solo = true;
2526        apply_solo(&mut solo_cfg, &solo_task);
2527        assert_eq!(solo_cfg.graph.candidates, 1);
2528
2529        let mut plain_cfg = Config::default();
2530        plain_cfg.graph.candidates = 3;
2531        let plain_task = task();
2532        assert!(!plain_task.solo);
2533        apply_solo(&mut plain_cfg, &plain_task);
2534        assert_eq!(
2535            plain_cfg.graph.candidates, 3,
2536            "a task that did not ask to run alone keeps the config's candidates"
2537        );
2538    }
2539
2540    #[test]
2541    fn merge_overrides_are_parsed_or_refused() {
2542        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
2543        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
2544        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
2545        assert!(merge_mode("squash").is_err());
2546    }
2547
2548    #[test]
2549    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
2550        let now = Timestamp::now();
2551        let fallback = Duration::from_secs(300);
2552        let cap = Duration::from_secs(1800);
2553
2554        // No reset hint at all: the fallback.
2555        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
2556
2557        // A reset ten minutes out, well inside the cap: waited for exactly.
2558        let soon = now + jiff::SignedDuration::from_secs(600);
2559        assert_eq!(
2560            quota_wait(Some(soon), now, fallback, cap),
2561            Duration::from_secs(600)
2562        );
2563
2564        // A reset already in the past is not trusted: the fallback, not a
2565        // zero or negative wait that would spin the loop right back around.
2566        let past = now - jiff::SignedDuration::from_secs(60);
2567        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
2568
2569        // A reset further out than the cap is trusted for direction but not
2570        // for magnitude: a parsing slip must not sleep the loop for a day.
2571        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
2572        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
2573    }
2574
2575    #[test]
2576    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
2577        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
2578
2579        let at = parse_reset_hint("4:50am (UTC)", now).expect("a recognised shape parses");
2580        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
2581
2582        // Same clock reading, but it has already gone by today: read as
2583        // tomorrow's, since the CLI would not still be reporting a limit past
2584        // its own stated reset.
2585        let already_past =
2586            parse_reset_hint("1:00am (UTC)", now).expect("a recognised shape parses");
2587        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
2588
2589        assert!(
2590            parse_reset_hint("session limit reached", now).is_none(),
2591            "free text with no recognised shape is not guessed at"
2592        );
2593        assert!(
2594            parse_reset_hint("4:50am (Nowhere/Fake)", now).is_none(),
2595            "an unresolvable zone name is not guessed at either"
2596        );
2597    }
2598
2599    /// A loop whose queue lives in a temp tree and whose poll interval is far
2600    /// longer than the test's patience, so anything that waits out a poll
2601    /// instead of noticing the stop fails rather than merely being slow.
2602    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf) {
2603        let opts = Opts {
2604            poll: Duration::from_secs(30),
2605            ..Opts::default()
2606        };
2607        // The status file goes in a directory that does not exist yet, so its
2608        // creation is itself evidence the loop published one.
2609        let home = dir.join("home");
2610        (
2611            opts,
2612            Queue::at(dir.join("queue")),
2613            home.join("daemon.json"),
2614            home,
2615        )
2616    }
2617
2618    #[test]
2619    fn a_stop_is_idempotent_and_once_set_stays_set() {
2620        let stop = Stop::new();
2621        assert!(!stop.stopped());
2622
2623        stop.stop();
2624        assert!(stop.stopped());
2625        stop.stop();
2626        assert!(stop.stopped(), "a second stop is not a toggle");
2627
2628        let shared = stop.clone();
2629        assert!(
2630            shared.stopped(),
2631            "a clone is the same stop; that is how the loop and its caller share one"
2632        );
2633    }
2634
2635    #[test]
2636    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
2637        let stop = Stop::new();
2638        stop.enter();
2639        assert!(
2640            !stop.finishing(),
2641            "a busy loop nobody has asked to stop is just running"
2642        );
2643
2644        stop.stop();
2645        assert!(
2646            stop.finishing(),
2647            "a stop asked for mid-run has not landed until the run is settled"
2648        );
2649
2650        stop.exit();
2651        assert!(
2652            !stop.finishing(),
2653            "once the run is settled the stop has landed and there is nothing to finish"
2654        );
2655    }
2656
2657    #[test]
2658    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
2659        let stop = Stop::new();
2660        stop.enter();
2661        stop.enter();
2662        stop.stop();
2663        assert!(stop.finishing(), "two runs still in flight");
2664
2665        stop.exit();
2666        assert!(
2667            stop.finishing(),
2668            "one run finished, but a sibling is still working"
2669        );
2670
2671        stop.exit();
2672        assert!(
2673            !stop.finishing(),
2674            "the last run out is what actually lands the stop"
2675        );
2676    }
2677
2678    #[tokio::test]
2679    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
2680        let dir = tempfile::tempdir().unwrap();
2681        let (opts, queue, status_file, home) = idle_loop(dir.path());
2682        let stop = Stop::new();
2683        stop.stop();
2684
2685        let began = std::time::Instant::now();
2686        tokio::time::timeout(
2687            Duration::from_secs(2),
2688            drive(&opts, &queue, &status_file, &home, &stop),
2689        )
2690        .await
2691        .expect("a stopped loop must return, not sit out its poll interval")
2692        .expect("the loop's own setup and teardown must not fail");
2693        assert!(
2694            began.elapsed() < opts.poll,
2695            "returned only after {:?}, which is a poll interval, not a stop",
2696            began.elapsed()
2697        );
2698    }
2699
2700    #[tokio::test]
2701    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
2702        let dir = tempfile::tempdir().unwrap();
2703        let (opts, queue, status_file, home) = idle_loop(dir.path());
2704        let stop = Stop::new();
2705
2706        // Asked for after the loop is already parked on its empty queue, which
2707        // is the case an operator tapping stop on a phone actually hits.
2708        let asker = {
2709            let stop = stop.clone();
2710            tokio::spawn(async move {
2711                tokio::time::sleep(Duration::from_millis(20)).await;
2712                stop.stop();
2713            })
2714        };
2715
2716        let began = std::time::Instant::now();
2717        tokio::time::timeout(
2718            Duration::from_secs(2),
2719            drive(&opts, &queue, &status_file, &home, &stop),
2720        )
2721        .await
2722        .expect("a stop asked for while idle must wake the wait")
2723        .expect("the loop's own setup and teardown must not fail");
2724        asker.await.unwrap();
2725        assert!(
2726            began.elapsed() < opts.poll,
2727            "returned only after {:?}, so the stop waited on the sleep",
2728            began.elapsed()
2729        );
2730    }
2731
2732    #[tokio::test]
2733    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
2734        let dir = tempfile::tempdir().unwrap();
2735        let (opts, queue, status_file, home) = idle_loop(dir.path());
2736        let stop = Stop::new();
2737        stop.stop();
2738
2739        tokio::time::timeout(
2740            Duration::from_secs(2),
2741            drive(&opts, &queue, &status_file, &home, &stop),
2742        )
2743        .await
2744        .expect("a stopped loop must return")
2745        .expect("the loop's own setup and teardown must not fail");
2746
2747        assert!(
2748            home.is_dir(),
2749            "the loop did publish a status file, so its removal is the teardown and not an absence"
2750        );
2751        assert!(
2752            !status_file.exists(),
2753            "a stopped loop clears its status file"
2754        );
2755        assert!(
2756            read_status(&home).is_none(),
2757            "a reader must see no daemon at all, not a heartbeat that merely stopped"
2758        );
2759    }
2760}