Skip to main content

magi/
daemon.rs

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