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