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/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
961///
962/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
963/// sets, so there is one loop body rather than two that drift apart the first
964/// time the retry policy changes on only one of them.
965pub async fn serve(opts: Opts) -> Result<()> {
966    serve_until(opts, Stop::new()).await
967}
968
969/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
970///
971/// Neither a signal nor a `stop` abandons a run in flight. Killing the graph
972/// mid-node leaves worktrees, branches and agent sessions behind, and every
973/// agent call already paid for is lost; finishing the run costs the operator a
974/// wait and saves them a cleanup. A stop therefore only sets a flag: the
975/// current `execute` runs to its terminal status, the task's outcome is
976/// recorded, and only then does the loop return. That window is what
977/// [`Stop::finishing`] is for. An operator who genuinely wants the run dead
978/// still has a second Ctrl-C, which the runtime turns into a process kill —
979/// and the task left `Running` then tells the next daemon, and the next human,
980/// where to look.
981///
982/// While the queue is empty the stop is honoured within one wakeup rather than
983/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
984/// caller that taps stop does not sit through the remainder of a sleep.
985pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
986    let signal = {
987        let stop = stop.clone();
988        tokio::spawn(async move {
989            if tokio::signal::ctrl_c().await.is_ok() {
990                stop.stop();
991                tracing::info!("shutdown requested; a run in flight will be finished first");
992            }
993        })
994    };
995
996    let worktrees_root = opts
997        .worktrees_root
998        .clone()
999        .unwrap_or_else(crate::run::default_worktree_root);
1000    let outcome = drive(
1001        &opts,
1002        &Queue::open(),
1003        &status_path(),
1004        &crate::run::home(),
1005        &worktrees_root,
1006        &stop,
1007    )
1008    .await;
1009
1010    signal.abort();
1011    outcome
1012}
1013
1014/// The loop proper: setup, poll, teardown, with the queue and the status file
1015/// supplied rather than discovered.
1016///
1017/// All three of `home`, `worktrees_root` and the queue/status paths are
1018/// parameters rather than resolved here, for the same reason:
1019/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
1020/// so a unit test that pinned it would fight every other test in the binary,
1021/// and a loop that resolved its own worktree bay could only be exercised
1022/// against the operator's real `~/wt/<repo>` - publishing over a live
1023/// daemon's status file, claiming tasks out of a live backlog, and, since
1024/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
1025/// whatever the operator actually has on disk.
1026async fn drive(
1027    opts: &Opts,
1028    queue: &Queue,
1029    status_file: &Path,
1030    home: &Path,
1031    worktrees_root: &Path,
1032    stop: &Stop,
1033) -> Result<()> {
1034    // The status file is a *snapshot*, not a stream of events: a reader only
1035    // ever wants the latest values, and every tick rewrites the whole file
1036    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
1037    // while an mpsc channel would force the loop to re-send unchanged fields on
1038    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
1039    // for no gain. The lock is only ever held across a field assignment, never
1040    // across an await.
1041    let status = Arc::new(Mutex::new(Status::new()));
1042    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
1043    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
1044
1045    // Read once at startup, not per task: how many runs this loop drives at
1046    // once is a property of the machine running it, not of whichever
1047    // repository a given task happens to name - see
1048    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
1049    // fact in the same sense the agent roster is.
1050    let concurrency = max_concurrent(
1051        prepare(&opts.repo, opts)
1052            .map(|c| c.daemon.max_concurrent_runs)
1053            .unwrap_or(1),
1054    );
1055
1056    tracing::info!(
1057        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once)",
1058        queue.root().display(),
1059        opts.poll.as_secs(),
1060        opts.max_attempts,
1061        concurrency
1062    );
1063
1064    // `--once` drains an already-idle queue without reaching the idle wait,
1065    // but must still perform the startup cleanup.
1066    janitor(&opts.repo, opts, home, worktrees_root).await;
1067
1068    let outcome = poll(
1069        opts,
1070        queue,
1071        &status,
1072        home,
1073        worktrees_root,
1074        stop,
1075        concurrency,
1076    )
1077    .await;
1078
1079    beat.abort();
1080    clear_status_at(status_file);
1081    outcome
1082}
1083
1084/// Refresh the status file on a fixed tick.
1085///
1086/// Separate from the loop because a run takes tens of minutes: a status file
1087/// written only between tasks would look stale for the whole of every run, and
1088/// a reader would report the daemon dead exactly while it was busiest.
1089async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
1090    loop {
1091        tokio::time::sleep(HEARTBEAT).await;
1092        let snapshot = {
1093            let mut guard = lock(&status);
1094            guard.updated_at = Timestamp::now();
1095            guard.clone()
1096        };
1097        if let Err(e) = write_status_to(&path, &snapshot) {
1098            // A failed heartbeat must not take the daemon down: the loop is the
1099            // product, the status file is only the window onto it.
1100            tracing::warn!("could not refresh the daemon status file: {e:#}");
1101        }
1102    }
1103}
1104
1105/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
1106/// if so, whether that wait is over.
1107#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1108enum LandResume {
1109    /// The task's last run is not parked on a land approval; schedule it
1110    /// like any other candidate.
1111    NotLanding,
1112    /// Parked in `land`, waiting on a question nobody has answered yet.
1113    /// Left alone: attempting it now would only re-observe the same pull
1114    /// request and park again, spending a `gh` call on a decision that has
1115    /// not changed since the last time this was checked.
1116    StillWaiting,
1117    /// Parked in `land`, and the question is settled - answered or
1118    /// abandoned. Resuming this is the one kind of candidate that must not
1119    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
1120    Ready,
1121}
1122
1123/// Classify a runnable candidate by whether it is parked on a land-merge
1124/// approval. Read-only - no claim taken, nothing written - so it is cheap
1125/// enough to call on every candidate, every poll.
1126fn land_resume_state(task: &Task) -> LandResume {
1127    let Some(run_id) = task.runs.last() else {
1128        return LandResume::NotLanding;
1129    };
1130    let Ok(state) = RunState::load(run_id) else {
1131        return LandResume::NotLanding;
1132    };
1133    if state.status != RunStatus::Landing || !state.parked {
1134        return LandResume::NotLanding;
1135    }
1136    let store = ask::Questions::open();
1137    let waiting = store
1138        .list()
1139        .into_iter()
1140        .filter(|q| &q.run == run_id && q.node == land::APPROVAL_NODE)
1141        .max_by(|a, b| a.id.cmp(&b.id));
1142    let Some(mut q) = waiting else {
1143        return LandResume::Ready;
1144    };
1145    if !q.status.open() {
1146        return LandResume::Ready;
1147    }
1148    // `ask::ask_and_wait`'s own deadline is what used to retire a question
1149    // nobody ever answered; land's approval bypasses that wait entirely (see
1150    // `land::approval_gate`), so the same deadline has to be enforced here
1151    // instead, or `graph.answer_timeout` silently stops meaning anything for
1152    // a land approval and a run can sit `StillWaiting` forever with nobody
1153    // told to look at it.
1154    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
1155    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
1156    if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
1157        q.abandon(format!(
1158            "no answer within {}s of asking",
1159            timeout.as_secs().max(1)
1160        ));
1161        // If this can't be persisted, do not treat the wait as settled on a
1162        // guess: fall through and try again next poll.
1163        if store.put(&mut q).is_ok() {
1164            return LandResume::Ready;
1165        }
1166    }
1167    LandResume::StillWaiting
1168}
1169
1170/// How often the loop rechecks for new work while something it already
1171/// started is still running, rather than sleeping out the whole
1172/// [`Opts::poll`] interval.
1173///
1174/// Short on purpose: this is what lets a land-merge approval that comes back
1175/// while another task is mid-competition be noticed and resumed within a
1176/// fraction of a second, not within the next multi-second poll.
1177const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
1178
1179/// Frees one attempt's concurrency slot - `Stop`'s busy count and its entry
1180/// in `Status::current` - on drop, so both are released even if the attempt
1181/// panics rather than returning.
1182///
1183/// A `Drop` impl rather than statements written after the `.await` it
1184/// guards: a panic unwinds straight past code placed "after" a call, and
1185/// `Runner::execute`'s chain reaches deep enough into agent-output parsing
1186/// that ruling a panic out there is not a bet this loop can make. Without
1187/// this, one panicking run would leave [`Stop::busy_now`] stuck `true`
1188/// forever - the idle branch in [`poll`], and with it the janitor, would
1189/// never run again - and a ghost entry in `Status::current` naming a task
1190/// nothing is still working on.
1191struct InFlightGuard<'a> {
1192    status: &'a Arc<Mutex<Status>>,
1193    stop: &'a Stop,
1194    task_id: &'a str,
1195}
1196
1197impl Drop for InFlightGuard<'_> {
1198    fn drop(&mut self) {
1199        lock(self.status).current.retain(|c| c.task != self.task_id);
1200        self.stop.exit();
1201    }
1202}
1203
1204/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
1205/// teardown and cannot skip the teardown on an early return.
1206///
1207/// `max_concurrent` bounds how many *ordinary* candidates run at once - see
1208/// [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a land
1209/// approval that has since been answered is dispatched outside that bound
1210/// the moment [`land_resume_state`] reports it [`LandResume::Ready`]: the
1211/// whole point of parking there is that it must not queue behind whatever
1212/// else the loop happens to be running, even at the default of one.
1213async fn poll(
1214    opts: &Opts,
1215    queue: &Queue,
1216    status: &Arc<Mutex<Status>>,
1217    home: &Path,
1218    worktrees_root: &Path,
1219    stop: &Stop,
1220    max_concurrent: usize,
1221) -> Result<()> {
1222    // Only consulted by `once`, where a task that just failed is still
1223    // `runnable` and would otherwise be picked up again inside the same drain.
1224    // In the long-running mode a later poll retrying a failed task is the point,
1225    // and the attempt counter is what bounds it.
1226    let mut attempted: Vec<String> = Vec::new();
1227    let sem = Arc::new(tokio::sync::Semaphore::new(max_concurrent));
1228    // A quota hit is a fact about the machine, not the task that happened to
1229    // surface it, and every other *ordinary* candidate is no less likely to
1230    // hit the same wall - see the warning below. A land-merge resume is
1231    // exempt: it is a human decision finishing, not a fresh competition, and
1232    // must not sit out a quota cooldown it did not cause.
1233    let quota_cooldown_until: Arc<Mutex<Option<Timestamp>>> = Arc::new(Mutex::new(None));
1234    let mut inflight: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
1235    let mut conductor = Conductor::new();
1236
1237    while !stop.stopped() {
1238        lock(status).polls += 1;
1239
1240        // Reap whatever finished since the last tick without blocking on
1241        // anything still running. `InFlightGuard` already released the slot
1242        // even if the spawned attempt panicked; this only surfaces that it
1243        // happened, since a panic swallowed here otherwise leaves no trace.
1244        while let Some(result) = inflight.try_join_next() {
1245            if let Err(e) = result {
1246                tracing::error!("a spawned attempt did not finish cleanly: {e}");
1247            }
1248        }
1249
1250        let swept = sweep_stale_claims(queue, STALE_CLAIM);
1251        if !swept.is_empty() {
1252            tracing::warn!(
1253                "swept {} stale claim(s) left behind by an earlier daemon: {}",
1254                swept.len(),
1255                swept.join(", ")
1256            );
1257        }
1258        // Capture stalled work before reclaiming it. A dead daemon's ordinary
1259        // lock is swept and reclaimed in this same poll, but the conductor
1260        // must still see that it was stranded rather than only its mechanical
1261        // terminal state.
1262        let now = Timestamp::now();
1263        let stalled = stalled_tasks(queue, home, now);
1264        let stalled_ids: std::collections::BTreeSet<_> =
1265            stalled.iter().map(|task| task.id.clone()).collect();
1266        let reclaimed = reclaim_orphaned_running(queue, opts.max_attempts);
1267        if !reclaimed.is_empty() {
1268            tracing::warn!(
1269                "reclaimed {} task(s) left `running` by a daemon that never \
1270                 recorded the outcome: {}",
1271                reclaimed.len(),
1272                reclaimed.join(", ")
1273            );
1274        }
1275
1276        // `home`, not `ask::Questions::open()`'s own process-global default:
1277        // `poll` is handed its home explicitly precisely so a test can point
1278        // it elsewhere, the same reason `Queue::at` and the status file path
1279        // are parameters rather than resolved here - see `drive`'s own doc.
1280        let questions = Questions::at(home.join("questions"));
1281
1282        // Deterministic: no model, run before the conductor sees anything so
1283        // its input reflects the queue's current, already-resolved state.
1284        resolve_blockers(queue, &questions);
1285        reconcile_task_questions(queue, &questions);
1286
1287        // The conductor gets one look per cycle, right before the loop takes
1288        // its next task, and only when there is something new to look at -
1289        // see `Conductor::worth_a_look`'s own doc for why "stalled is
1290        // non-empty" is the wrong test. Checked before `prepare` so an
1291        // unchanged cycle never pays for a synchronous config load.
1292        let finished: Vec<Task> = finished_tasks(queue)
1293            .into_iter()
1294            .filter(|task| !stalled_ids.contains(&task.id))
1295            .collect();
1296        let queued = queued_tasks(queue);
1297        // An empty queue has nothing to arrange. In particular, do not let
1298        // the conductor's initial snapshot cause synchronous config I/O
1299        // between the caller's stop notification and the idle wait below.
1300        if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
1301            && conductor.worth_a_look(queue, &stalled, &finished)
1302        {
1303            match prepare(&opts.repo, opts) {
1304                Ok(cfg) => {
1305                    conductor
1306                        .maybe_run(
1307                            &cfg,
1308                            &opts.repo,
1309                            queue,
1310                            &questions,
1311                            home,
1312                            &queued,
1313                            &stalled,
1314                            &finished,
1315                            opts.max_attempts,
1316                        )
1317                        .await;
1318                }
1319                Err(e) => tracing::warn!("conductor: no config: {e:#}"),
1320            }
1321        }
1322
1323        let candidates: Vec<Task> = runnable(queue)
1324            .into_iter()
1325            .filter(|t| !opts.once || !attempted.contains(&t.id))
1326            .collect();
1327
1328        let cooling_down =
1329            lock(&quota_cooldown_until).is_some_and(|until| Timestamp::now() < until);
1330
1331        let mut started_any = false;
1332        for candidate in candidates {
1333            if stop.stopped() {
1334                break;
1335            }
1336
1337            let resume = land_resume_state(&candidate);
1338            if resume == LandResume::StillWaiting {
1339                continue;
1340            }
1341            let priority = resume == LandResume::Ready;
1342
1343            if !priority && cooling_down {
1344                continue;
1345            }
1346            let permit = if priority {
1347                None
1348            } else {
1349                match Arc::clone(&sem).try_acquire_owned() {
1350                    Ok(p) => Some(p),
1351                    // No ordinary slot free right now. A later candidate in
1352                    // this same list might still be a priority resume, so
1353                    // keep looking rather than stopping here.
1354                    Err(_) => continue,
1355                }
1356            };
1357
1358            // A claim we cannot take means another daemon, or a human running
1359            // `magi run`, got there first. That is not the task's fault and
1360            // must not spend one of its attempts: move to the next candidate
1361            // rather than recording a failure.
1362            let Ok(claim) = queue.claim(&candidate.id) else {
1363                tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
1364                continue;
1365            };
1366            // Re-read under the claim: the task on disk may have been held or
1367            // edited between the listing and the lock.
1368            let mut task = match queue.get(&candidate.id) {
1369                Ok(t) if t.status.runnable() => t,
1370                Ok(_) => continue,
1371                Err(e) => {
1372                    tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
1373                    continue;
1374                }
1375            };
1376            let task_id = task.id.clone();
1377            attempted.push(task_id.clone());
1378            lock(status).idle = false;
1379            // A stop asked for from here on is "finishing", not "stopped": the
1380            // run gets to reach a terminal status before the loop returns.
1381            stop.enter();
1382            started_any = true;
1383
1384            let opts = opts.clone();
1385            let queue = queue.clone();
1386            let status = Arc::clone(status);
1387            let stop = stop.clone();
1388            let quota_cooldown_until = Arc::clone(&quota_cooldown_until);
1389            inflight.spawn(async move {
1390                // Held for the whole attempt: dropping either at the end of
1391                // this task is what releases the claim and, for an ordinary
1392                // candidate, frees its concurrency slot back to the loop.
1393                let _claim = claim;
1394                let _permit = permit;
1395                // See `InFlightGuard`: this must survive a panic inside `attempt`.
1396                let _inflight = InFlightGuard {
1397                    status: &status,
1398                    stop: &stop,
1399                    task_id: &task_id,
1400                };
1401                let quota = attempt(&opts, &queue, &status, &stop, &mut task).await;
1402                lock(&status).completed += 1;
1403                // A quota loss is a fact about the machine, not this task, and
1404                // the next ordinary candidate the loop offers is no less
1405                // likely to hit the same wall: without a cooldown here a
1406                // whole backlog can be run - and failed - in the seconds it
1407                // takes each attempt to notice the CLI is out of quota.
1408                if !quota.is_empty() {
1409                    let hint = quota.iter().find_map(|q| q.reset.as_deref());
1410                    let reset_at = hint.and_then(|h| parse_reset_hint(h, Timestamp::now()));
1411                    let wait = quota_wait(
1412                        reset_at,
1413                        Timestamp::now(),
1414                        QUOTA_WAIT_FALLBACK,
1415                        QUOTA_WAIT_CAP,
1416                    );
1417                    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
1418                    let until = Timestamp::now()
1419                        .checked_add(jiff::SignedDuration::from_secs(secs))
1420                        .unwrap_or(Timestamp::MAX);
1421                    *lock(&quota_cooldown_until) = Some(until);
1422                    match hint {
1423                        Some(h) => tracing::warn!(
1424                            "quota hit; waiting {}s before taking another ordinary task \
1425                             (CLI reported reset: {h})",
1426                            wait.as_secs()
1427                        ),
1428                        None => tracing::warn!(
1429                            "quota hit; waiting {}s before taking another ordinary task \
1430                             (no reset hint reported)",
1431                            wait.as_secs()
1432                        ),
1433                    }
1434                }
1435            });
1436        }
1437
1438        if started_any {
1439            continue;
1440        }
1441
1442        if stop.busy_now() {
1443            // Something started on an earlier tick is still running. Recheck
1444            // soon rather than sleeping out the whole poll interval - a freed
1445            // slot, or a land approval answered mid-run, must not sit idle
1446            // for it.
1447            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
1448            continue;
1449        }
1450
1451        // Truly idle: nothing new to start and nothing still running.
1452        lock(status).idle = true;
1453        if opts.once {
1454            // A one-shot drain must perform the same post-work cleanup as a
1455            // daemon that reached a normal idle interval. The startup pass
1456            // cannot see runs or cache files produced by this drain.
1457            janitor(&opts.repo, opts, home, worktrees_root).await;
1458            break;
1459        }
1460        stop.idle(opts.poll).await;
1461        if stop.stopped() {
1462            continue;
1463        }
1464        // Housekeeping only after a full quiet interval. Running it before
1465        // the first idle wait can block the executor while an operator's
1466        // stop request is waiting to be scheduled, defeating Stop's retained
1467        // wake permit. No run can start while this branch is active, so the
1468        // janitor still never races an in-flight compile.
1469        janitor(&opts.repo, opts, home, worktrees_root).await;
1470    }
1471
1472    // Never return while a run is still in flight, whichever way the loop
1473    // above exited: a stop only sets a flag - see `serve_until` - and
1474    // returning here while `inflight` still holds spawned work would abandon
1475    // it exactly as a mid-node kill would.
1476    while let Some(result) = inflight.join_next().await {
1477        if let Err(e) = result {
1478            tracing::error!("a spawned attempt did not finish cleanly: {e}");
1479        }
1480    }
1481    Ok(())
1482}
1483
1484/// Run one claimed task to a terminal status and record the outcome.
1485///
1486/// Every transition is flushed to the queue as it happens, so the state on disk
1487/// is what actually occurred rather than what this process still intends to
1488/// write.
1489async fn attempt(
1490    opts: &Opts,
1491    queue: &Queue,
1492    status: &Arc<Mutex<Status>>,
1493    stop: &Stop,
1494    task: &mut Task,
1495) -> Vec<QuotaLoss> {
1496    let repo = repo_for(task, &opts.repo);
1497    tracing::info!(
1498        "task {} — {} (repo {})",
1499        task.short(),
1500        task.title,
1501        repo.display()
1502    );
1503
1504    let mut config = match prepare(&repo, opts) {
1505        Ok(c) => c,
1506        Err(e) => {
1507            // A setup failure spends an attempt even though no run was minted.
1508            // Without that, a task naming a repository that does not exist
1509            // would be retried at every poll for as long as the daemon lives.
1510            task.attempts += 1;
1511            task.fail(format!("config: {e:#}"), opts.max_attempts);
1512            record(queue, task);
1513            return Vec::new();
1514        }
1515    };
1516    apply_solo(&mut config, task);
1517
1518    // The free-space gate, checked *before* anything is minted: a task that
1519    // waits out a full disk costs nothing yet, and must not spend an attempt
1520    // or start a run the machine cannot finish. Held tasks stay in the list
1521    // for the human to see, and `magi task release` re-queues them when space
1522    // comes back - the same recovery as any other hold. A volume whose free
1523    // space cannot be measured closes the gate too: starting a run blind on a
1524    // disk that may be full is how the machine ends up with 6.7 GB free.
1525    if let Some(reason) = disk_gate(&repo, &config) {
1526        task.last_error = Some(reason.clone());
1527        task.hold_machine(Some(reason.clone()));
1528        record(queue, task);
1529        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
1530        return Vec::new();
1531    }
1532
1533    // A resumable run of this task is carried on, never re-competed. The
1534    // candidates are built and paid for, and a fresh competition races a
1535    // second implementation against them.
1536    //
1537    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
1538    // started 3cbf on the same task a moment later, duplicating two and a
1539    // half hours of agent work. Then b25f stalled on a judge that timed out
1540    // and one that answered with no JSON - `quota: 0`, so nothing the machine
1541    // was to blame for - and 4043 started **one second** later, buying three
1542    // fresh implementations to reach the same panel. `RunStatus::resumable`
1543    // rather than `!done()` is what catches the second case: a stall is
1544    // terminal, and its cheap recovery re-asks only the absent seats.
1545    //
1546    // A load failure is warned about rather than silently read as "not
1547    // resumable": the alternative is exactly what let a schema mismatch on
1548    // run `eba2` fall through to a full re-competition with nobody told why.
1549    // `crate::conduct` is what actually offers a better answer than
1550    // `Runner::start` here (see `Recovery::Review`), once this task's next
1551    // failure shows it up as `held`/`failed` with the run state unreadable.
1552    let unfinished = (!task.fresh_start)
1553        .then(|| unfinished_run(&task.runs, task.short()))
1554        .flatten();
1555    // `crate::conduct` chose `Review` for this task on an earlier cycle: its
1556    // branch survived, and this reopens exactly that branch as a
1557    // review-only pass rather than resuming or competing again. Consumed
1558    // (cleared) here whichever way this goes, so it never outlives this one
1559    // attempt - see `queue::Task::review_branch`.
1560    let review_branch = task.review_branch.take();
1561    let branch_exists = match &review_branch {
1562        Some(branch) => crate::git::branch_exists(&repo, branch)
1563            .await
1564            .unwrap_or(false),
1565        None => false,
1566    };
1567    let starter = choose_starter(
1568        review_branch.as_deref(),
1569        branch_exists,
1570        unfinished.as_deref(),
1571    );
1572    let started = match &starter {
1573        Starter::Review(branch) => {
1574            tracing::info!(
1575                "task {} reopens `{branch}` as a review-only pass",
1576                task.short()
1577            );
1578            Runner::review(&repo, branch, config).await
1579        }
1580        Starter::Resume(id) => {
1581            tracing::info!("resuming run {id} rather than competing again");
1582            Runner::resume(id).map(|mut r| {
1583                if let Some(instruction) =
1584                    prepare_instruction(&starter, Some(&r.state.instruction), task)
1585                {
1586                    r.state.instruction = instruction;
1587                }
1588                r
1589            })
1590        }
1591        Starter::Start => {
1592            if let Some(branch) = &review_branch {
1593                tracing::warn!(
1594                    "conductor chose review for task {} but branch `{branch}` no longer \
1595                     exists; requeuing as a fresh competition instead",
1596                    task.short()
1597                );
1598            }
1599            let instruction = prepare_instruction(&starter, None, task)
1600                .unwrap_or_else(|| task.instruction.clone());
1601            Runner::start(&repo, instruction, config).await
1602        }
1603    };
1604    let mut runner = match started {
1605        Ok(r) => r,
1606        Err(e) => {
1607            task.attempts += 1;
1608            task.fail(format!("could not start the run: {e:#}"), opts.max_attempts);
1609            record(queue, task);
1610            return Vec::new();
1611        }
1612    };
1613    // A stop that means "park" reaches the graph through this handle.
1614    runner.on_pause(stop.pause());
1615
1616    // `start` has minted the run, so the task can now point at it. Persisting
1617    // `Running` before `execute` is what makes a crash mid-run legible.
1618    let run = runner.state.id.clone();
1619    task.start(run.clone());
1620    record(queue, task);
1621    lock(status).current.push(Current {
1622        task: task.id.clone(),
1623        run,
1624    });
1625
1626    let detail = match runner.execute().await {
1627        Ok(()) => describe(&runner.state),
1628        Err(e) => format!("{e:#}"),
1629    };
1630    let verdict = Verdict {
1631        status: runner.state.status,
1632        // A run that opened a pull request handed its work over, whatever the
1633        // gate then decided about merging it.
1634        left_pr: runner.state.pr.is_some(),
1635        // Only a rate limit earns the task its attempt back.
1636        quota_hit: !runner.state.quota.is_empty(),
1637        // A run that parked was asked to stop; that is not a failure and must
1638        // not spend an attempt, or replacing the binary a few times would
1639        // exhaust a task's budget without an agent ever misbehaving.
1640        parked: runner.state.parked,
1641        // A quota loss that left nothing viable is the same machine fact as a
1642        // `Stalled` quota loss; see `settle`'s doc table.
1643        no_viable_candidates: runner.state.viable().is_empty(),
1644    };
1645    settle_and_diagnose(task, verdict, &detail, opts.max_attempts, &runner.state);
1646    record(queue, task);
1647    tracing::info!(
1648        "task {} is {} after run {} ({})",
1649        task.short(),
1650        task.status.as_str(),
1651        runner.state.short(),
1652        label(runner.state.status)
1653    );
1654    runner.state.quota
1655}
1656
1657/// Cut this attempt's candidate count to one when the task asked to run
1658/// alone.
1659///
1660/// Pure and separate from [`attempt`] so the one thing this feature changes -
1661/// which `candidates` a `solo` task's run is built with - can be asserted
1662/// without minting a run: `attempt` drives `graph::Runner`, which spawns real
1663/// agent CLIs, and no test may do that. `config` is mutated in place, taken by
1664/// value from the caller's own copy, so a repository's `magi.toml` on disk is
1665/// never touched - only the `Config` this one attempt hands to `Runner::start`.
1666fn apply_solo(config: &mut Config, task: &Task) {
1667    if task.solo {
1668        config.graph.candidates = 1;
1669    }
1670}
1671
1672/// Load the config for a task's repository, with the merge override applied.
1673fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
1674    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
1675    if let Some(mode) = &opts.merge {
1676        config.merge.mode = merge_mode(mode)?;
1677    }
1678    Ok(config)
1679}
1680
1681/// The disk janitor, with its housekeeping logged rather than fatal.
1682///
1683/// Called only at the loop's idle points, for the reason the caller documents:
1684/// a prune racing a live compile would delete files mid-build. The config is
1685/// re-read on every call because the repository that just ran may not be the
1686/// daemon's own default, and the cache directory is a repository fact.
1687///
1688/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
1689/// and [`crate::run::default_worktree_root`] read here, for the same reason
1690/// [`drive`] takes its queue and status file rather than resolving them: a
1691/// test driving the loop must not reach through to the operator's real home
1692/// or worktree bay just because the janitor runs on every idle tick.
1693/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
1694/// to get wrong silently - a test's `home` was already isolated, but nothing
1695/// exercised the parameter next to it, so a real worktree bay stayed wired in
1696/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
1697/// it for real, every test in this file that drives the loop at all started
1698/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
1699async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
1700    let cfg = match prepare(repo, opts) {
1701        Ok(cfg) => cfg,
1702        Err(e) => {
1703            tracing::warn!("housekeep: no config: {e:#}");
1704            return;
1705        }
1706    };
1707    // A run's own worktree lives under `config.graph.worktree_root` when the
1708    // repository sets one - the same precedence `RunState::worktree_root`
1709    // uses - and `worktrees_root` only stands in for the *default* an
1710    // unconfigured repository resolves to (see this function's own
1711    // parameter, or the test fixture wiring one to a fake path). Housekeeping
1712    // that always swept the default regardless of this override would never
1713    // see, and so never reclaim, a single worktree for a repository that
1714    // relocated them elsewhere.
1715    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
1716    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
1717    // Reported whenever there is anything to say, not only when `folded > 0`:
1718    // the incident this exists to prevent was 90 of 93 runs skipped and 0
1719    // folded, on every single pass, for months - a report gated on `folded`
1720    // would have stayed silent through every one of them.
1721    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
1722        let mut extra = Vec::new();
1723        if out.unreadable > 0 {
1724            extra.push(format!("{} unreadable", out.unreadable));
1725        }
1726        if out.orphaned_worktrees > 0 {
1727            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
1728        }
1729        let detail = if extra.is_empty() {
1730            String::new()
1731        } else {
1732            format!(" ({})", extra.join(", "))
1733        };
1734        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
1735    }
1736    if out.cache_files > 0 {
1737        tracing::info!(
1738            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
1739            out.cache_files,
1740            out.cache_freed
1741        );
1742    }
1743    if out.questions_abandoned > 0 {
1744        tracing::info!(
1745            "housekeep: abandoned {} question(s) left open by a finished run",
1746            out.questions_abandoned
1747        );
1748    }
1749}
1750
1751/// The free-space gate: what stands between this task and a new run, if
1752/// anything. `Some(reason)` holds the task; `None` lets it start.
1753///
1754/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
1755/// the operator opted out. A measurement failure is a gate, not a pass: both
1756/// sides of "cannot tell" are served by not starting.
1757fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
1758    let min = config.disk.min_free_bytes;
1759    if min == 0 {
1760        return None;
1761    }
1762    match crate::disk::free_bytes(repo) {
1763        Ok(free) => crate::disk::gate(free, min),
1764        Err(e) => Some(format!(
1765            "could not measure free space on {} ({e}); the disk gate refuses \
1766             to let a run start blind",
1767            repo.display()
1768        )),
1769    }
1770}
1771
1772/// How long to wait before offering another task when a run lost a seat to a
1773/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
1774/// could read, or carried nothing at all. Long enough that a quota outage
1775/// cannot burn through a whole backlog in the few seconds each doomed attempt
1776/// takes to fail; short enough that a quota which clears early is not left
1777/// idle for the fallback's sake.
1778const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
1779
1780/// Longest a parsed reset hint may push the wait out to. The hint comes from
1781/// the CLI's own words, not a contract, so a parsing slip that lands a day
1782/// away must not leave the loop asleep for a day.
1783const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
1784
1785/// How long [`poll`] should wait before offering the next task, after a run
1786/// lost at least one seat to a rate limit.
1787///
1788/// Pure and separate from the loop so the policy can be exercised without a
1789/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
1790/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
1791/// nothing to parse, or the parsed time has already passed; `cap` bounds how
1792/// far a parsed hint is trusted to push the wait out.
1793fn quota_wait(
1794    reset_at: Option<Timestamp>,
1795    now: Timestamp,
1796    fallback: Duration,
1797    cap: Duration,
1798) -> Duration {
1799    match reset_at {
1800        Some(at) if at > now => {
1801            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
1802            Duration::from_secs(secs).min(cap)
1803        }
1804        _ => fallback,
1805    }
1806}
1807
1808/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
1809///
1810/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
1811/// explains why parsing it exactly "would be a bug factory" — so this only
1812/// recognises the one shape actually observed in the wild, `"H:MMam/pm
1813/// (Zone)"`, and returns `None` for anything else rather than guess at a
1814/// format nobody has seen. A clock reading already past today is read as
1815/// tomorrow's: a CLI naming a same-day reset that has already gone by means
1816/// the window rolled over while nothing was watching.
1817fn parse_reset_hint(text: &str, now: Timestamp) -> Option<Timestamp> {
1818    let open = text.find('(')?;
1819    let close = text.rfind(')')?;
1820    if close <= open {
1821        return None;
1822    }
1823    let zone = text[open + 1..close].trim();
1824    let clock = text[..open].trim().to_lowercase();
1825    let (digits, pm) = clock
1826        .strip_suffix("am")
1827        .map(|d| (d, false))
1828        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
1829    let (h, m) = digits.trim().split_once(':')?;
1830    let mut hour: i8 = h.trim().parse().ok()?;
1831    let minute: i8 = m.trim().parse().ok()?;
1832    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
1833        return None;
1834    }
1835    if pm && hour != 12 {
1836        hour += 12;
1837    } else if !pm && hour == 12 {
1838        hour = 0;
1839    }
1840    let tz = jiff::tz::TimeZone::get(zone).ok()?;
1841    let candidate = now
1842        .to_zoned(tz)
1843        .with()
1844        .hour(hour)
1845        .minute(minute)
1846        .second(0)
1847        .millisecond(0)
1848        .microsecond(0)
1849        .nanosecond(0)
1850        .build()
1851        .ok()?;
1852    let mut at = candidate.timestamp();
1853    if at <= now {
1854        at += jiff::SignedDuration::from_hours(24);
1855    }
1856    Some(at)
1857}
1858
1859/// Resuming a `Blocked` run that already spent every review round its own
1860/// config allowed cannot make progress: `graph::Runner`'s review loop walks
1861/// `(reviews.len()+1)..=max_rounds`, which is empty once `reviews.len()` has
1862/// reached `max_rounds`, so `execute` would settle straight back to
1863/// `Blocked` without asking anyone anything. Read-only against a state this
1864/// build never mutates — `src/graph.rs` stays untouched — but without this
1865/// check, [`unfinished_run`] would keep reporting such a run as still
1866/// "unfinished", and `crate::conduct::Recovery::Requeue` (whose whole
1867/// promise is a fresh competition when a design needs to change) would
1868/// silently resume the exhausted run instead, spending an attempt on a
1869/// cycle that cannot change anything.
1870fn exhausted_review_budget(state: &RunState) -> bool {
1871    state.status == RunStatus::Blocked && state.reviews.len() >= state.config.graph.review_rounds
1872}
1873
1874/// This task's *most recent* run, if resuming it would actually make
1875/// progress. `short` is only for the warning's own message.
1876///
1877/// Only ever `runs.last()` — never a search back through older history.
1878/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
1879/// mint, oldest first, and every entry before the last one was already
1880/// superseded at the moment it was minted: the daemon only ever starts a new
1881/// run when the previous one was not worth resuming (unresumable, exhausted,
1882/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
1883/// opens a fresh review-only run alongside an older, already-failed
1884/// competition. Searching further back would let an old run that merely
1885/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
1886/// behind, say — get resumed instead of the fresh competition
1887/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
1888/// nothing asked to revisit.
1889///
1890/// Two runs paid for the "prefer resuming over restarting" half of this
1891/// lesson, which is why this still checks `runs.last()` rather than always
1892/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
1893/// task a moment later, duplicating two and a half hours of agent work. Then
1894/// b25f stalled on a judge that timed out and one that answered with no JSON
1895/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
1896/// **one second** later, buying three fresh implementations to reach the
1897/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
1898/// the second case: a stall is terminal, and its cheap recovery re-asks only
1899/// the absent seats. [`exhausted_review_budget`] is the other half: a run
1900/// that is technically `resumable()` but provably cannot progress must not
1901/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
1902/// no-op instead of the fresh competition it promises.
1903///
1904/// A load failure is warned about rather than silently read as "not
1905/// resumable": the alternative is exactly what let a schema mismatch on run
1906/// `eba2` fall through to a full re-competition with nobody told why.
1907/// `crate::conduct` is what actually offers a better answer than
1908/// `Runner::start` here (see `Recovery::Review`), once this task's next
1909/// failure shows it up as `held`/`failed` with the run state unreadable.
1910fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
1911    unfinished_run_with(runs, short, RunState::load)
1912}
1913
1914/// [`unfinished_run`] with an injected state reader. Tests provide their
1915/// fixtures directly rather than touching the process-global run home.
1916fn unfinished_run_with<F>(runs: &[String], short: &str, load: F) -> Option<String>
1917where
1918    F: FnOnce(&str) -> Result<RunState>,
1919{
1920    let id = runs.last()?;
1921    match load(id) {
1922        Ok(s) if s.status.resumable() && !exhausted_review_budget(&s) => Some(id.clone()),
1923        Ok(_) => None,
1924        Err(e) => {
1925            tracing::warn!("could not read run {id} for task {short}: {e:#}");
1926            None
1927        }
1928    }
1929}
1930
1931/// Which of the three ways [`attempt`] can mint or continue a run this task
1932/// should use.
1933#[derive(Debug, Clone, PartialEq, Eq)]
1934enum Starter {
1935    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
1936    /// and that still exists.
1937    Review(String),
1938    /// `crate::graph::Runner::resume` on an unfinished run of this task.
1939    Resume(String),
1940    /// `crate::graph::Runner::start`: a fresh competition.
1941    Start,
1942}
1943
1944/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
1945/// this attempt should use. Pure, and separate from [`attempt`], so the
1946/// routing itself is assertable without spawning a real graph or a git
1947/// process: `attempt`'s own `crate::git::branch_exists` call has already
1948/// happened by the time this is called.
1949///
1950/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
1951/// whose branch is gone falls all the way through to [`Starter::Start`], not
1952/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
1953/// old (likely `Blocked`) run in the first place, and a branch that vanished
1954/// out from under that choice is not evidence resuming it would fare better.
1955fn choose_starter(
1956    review_branch: Option<&str>,
1957    branch_exists: bool,
1958    unfinished: Option<&str>,
1959) -> Starter {
1960    match review_branch {
1961        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
1962        Some(_) => Starter::Start,
1963        None => match unfinished {
1964            Some(id) => Starter::Resume(id.to_owned()),
1965            None => Starter::Start,
1966        },
1967    }
1968}
1969
1970/// Which repository a task runs in. A task that names none — the normal case
1971/// for one filed from a phone — runs in the daemon's own default.
1972fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
1973    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
1974        return fallback.to_path_buf();
1975    }
1976    task.repo.clone()
1977}
1978
1979/// The header [`append_answers`] appends operator answers under. Shared with
1980/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
1981/// rather than grown a new block on every resume.
1982const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
1983
1984/// Render the first `count` answers in the block appended to an instruction.
1985fn answers_block(task: &Task, count: usize) -> String {
1986    let mut s = ANSWERS_HEADER.to_owned();
1987    for a in &task.answers[..count] {
1988        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
1989    }
1990    s
1991}
1992
1993/// Append every answer `crate::conduct` has collected for `task` onto `base`,
1994/// in the shape both [`instruction_for`] and [`resumed_instruction`] use.
1995fn append_answers(base: &str, task: &Task) -> String {
1996    if task.answers.is_empty() {
1997        return base.to_owned();
1998    }
1999    let mut s = base.to_owned();
2000    s.push_str(&answers_block(task, task.answers.len()));
2001    s
2002}
2003
2004/// Drop the prior answer block only when it is exactly the suffix this task
2005/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
2006/// the task author is ordinary instruction text, not a block to remove.
2007fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
2008    for count in (1..=task.answers.len()).rev() {
2009        let block = answers_block(task, count);
2010        if let Some(base) = instruction.strip_suffix(&block) {
2011            return base;
2012        }
2013    }
2014    instruction
2015}
2016
2017/// The instruction handed to `Runner::start`: the task's own text, plus any
2018/// operator answers `crate::conduct` collected for it (see
2019/// [`Task::answers`]), so a decision the operator actually made reaches the
2020/// implementers rather than only clearing the block that was waiting on it.
2021///
2022/// Appended rather than merged into [`Task::instruction`] itself, so the
2023/// task's own record stays exactly what its author wrote.
2024fn instruction_for(task: &Task) -> String {
2025    append_answers(&task.instruction, task)
2026}
2027
2028/// The instruction a resumed run should carry on with: whatever it already
2029/// had, refreshed with the task's *current* operator answers.
2030///
2031/// A resumable run's own `RunState::instruction` predates any answer
2032/// `crate::conduct` collects after the run parks, so resuming it unchanged —
2033/// the behaviour before this function existed — silently drops the very
2034/// decision the operator made to unblock it. Re-stripping any block this
2035/// function appended on an earlier resume before re-appending the current
2036/// list (rather than blindly appending again) is what keeps a task resumed
2037/// three times over three answered questions from carrying the same answer
2038/// three times.
2039fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
2040    append_answers(strip_answers_block(old_instruction, task), task)
2041}
2042
2043/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
2044/// answers before handing it to `Runner` — the actual boundary between
2045/// [`choose_starter`]'s routing and the graph, factored out so it is
2046/// assertable without a real repository, git branch, or agent CLI.
2047///
2048/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
2049/// instruction from the reviewed branch's own commit log because there is no
2050/// task statement to speak of for hand-written work, and splicing operator
2051/// answers into that text would contradict the very message it sends
2052/// reviewers ("there is no task statement").
2053fn prepare_instruction(
2054    starter: &Starter,
2055    old_instruction: Option<&str>,
2056    task: &Task,
2057) -> Option<String> {
2058    match starter {
2059        Starter::Start => Some(instruction_for(task)),
2060        Starter::Resume(_) => Some(resumed_instruction(
2061            old_instruction.expect("a resumed run always has a prior instruction"),
2062            task,
2063        )),
2064        Starter::Review(_) => None,
2065    }
2066}
2067
2068/// Persist a transition. A queue write failure is logged rather than fatal: the
2069/// run already happened, and taking the daemon down would only add a lost
2070/// backlog to a full disk.
2071fn record(queue: &Queue, task: &mut Task) {
2072    if let Err(e) = queue.put(task) {
2073        tracing::error!("could not record task {}: {e:#}", task.short());
2074    }
2075}
2076
2077/// Every runnable task, in the order the loop should try them.
2078///
2079/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
2080/// tail exists so that a claim somebody else holds costs the loop the next
2081/// candidate rather than a whole poll interval of idleness.
2082fn runnable(queue: &Queue) -> Vec<Task> {
2083    let mut tasks: Vec<Task> = queue
2084        .list()
2085        .into_iter()
2086        .filter(|t| t.status.runnable())
2087        .collect();
2088    tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
2089    tasks
2090}
2091
2092/// Why a run ended where it did, in one line, for [`Task::last_error`].
2093///
2094/// A stalled run names the seats the quota took out: "out of quota" is not
2095/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
2096/// agent to replace or which plan to top up.
2097fn describe(state: &RunState) -> String {
2098    let mut detail = if state.status == RunStatus::Stalled {
2099        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
2100        seats.sort_unstable();
2101        seats.dedup();
2102        if seats.is_empty() {
2103            "the judging panel lost its quorum".to_owned()
2104        } else {
2105            format!(
2106                "the judging panel lost its quorum; quota took out {}",
2107                seats.join(", ")
2108            )
2109        }
2110    } else {
2111        format!("run ended {}", label(state.status))
2112    };
2113    if let Some(last) = state.events.last() {
2114        detail.push_str(&format!(" ({}: {})", last.node, last.message));
2115    }
2116    detail.push_str(&format!(" [run {}]", state.id));
2117    detail
2118}
2119
2120/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
2121///
2122/// The task file lives in the backlog indefinitely; a diagnostic is an
2123/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
2124/// stay small regardless of how much a gate command or a candidate printed.
2125const DIAGNOSTIC_MAX: usize = 4_000;
2126
2127/// Tail kept from a single failing command's output inside a diagnostic.
2128/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
2129/// pointer for a human deciding whether to go read the full artifact by hand,
2130/// not a replacement for reading it.
2131const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
2132
2133/// Assemble a bounded diagnostic excerpt from a held task's own run, so
2134/// `magi task show` says more than the one-line reason in [`describe`].
2135///
2136/// The one-liner answers "where did the run stop"; this answers "what would a
2137/// human have found opening `artifacts/` by hand" — the point of the whole
2138/// feature is the case that one-liner actively misleads on: a run held as "no
2139/// candidate produced a change" can mean the implementer actually finished
2140/// the task (opened a PR, merged it, tagged a release) and only left a clean
2141/// local worktree behind, which reads as "nothing happened" unless someone
2142/// goes and reads what the agent actually said. `None` when the run carries
2143/// none of the three shapes this recognises — an ordinary run held for
2144/// something not diagnosable from `RunState` alone still explains itself
2145/// through `Task::last_error`.
2146fn diagnostic(state: &RunState) -> Option<String> {
2147    let mut parts: Vec<String> = Vec::new();
2148
2149    // Gate failure: which check(s), and the tail of what each printed.
2150    for o in state.gate.iter().filter(|o| !o.ok()) {
2151        parts.push(format!(
2152            "gate `{}` failed ({:?}):\n{}",
2153            o.command,
2154            o.code,
2155            crate::run::tail(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
2156        ));
2157    }
2158
2159    // The land loop gave up because the fixer declined while checks were
2160    // still red: the message already names them (see `land::run`).
2161    if let Some(last) = state
2162        .events
2163        .iter()
2164        .rev()
2165        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
2166    {
2167        parts.push(last.message.clone());
2168    }
2169
2170    // No viable candidate: every implementer's own final word, sanitized the
2171    // same way a judge would have read it, so a run that actually finished
2172    // the job does not read as an unexplained failure.
2173    if state.viable().is_empty() {
2174        for c in &state.candidates {
2175            if !c.summary.trim().is_empty() {
2176                parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
2177            } else if let Some(why) = &c.failed {
2178                parts.push(format!("candidate {}: {why}", c.label));
2179            }
2180        }
2181    }
2182
2183    if parts.is_empty() {
2184        return None;
2185    }
2186    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
2187    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
2188    // back slightly over. Leave it enough room to always land under the
2189    // limit.
2190    Some(crate::run::tail(
2191        &parts.join("\n\n"),
2192        DIAGNOSTIC_MAX.saturating_sub(100),
2193    ))
2194}
2195
2196/// Stable lower-case name for a run status, for logs and task errors.
2197/// One definition of a status's name, on the type that owns it: this table
2198/// used to live here as a second copy, and a status renamed in one place would
2199/// have gone on reading correctly in the other.
2200fn label(status: RunStatus) -> &'static str {
2201    status.as_str()
2202}
2203
2204/// Parse a merge mode override.
2205fn merge_mode(mode: &str) -> Result<MergeMode> {
2206    match mode {
2207        "none" => Ok(MergeMode::None),
2208        "local" => Ok(MergeMode::Local),
2209        "pr" => Ok(MergeMode::Pr),
2210        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
2211    }
2212}
2213
2214/// Take the status lock, recovering from a poisoned one.
2215///
2216/// A panic elsewhere must not silently stop the heartbeat: the status is plain
2217/// data, and the worst a poisoned lock can hold is a stale timestamp.
2218fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
2219    mutex
2220        .lock()
2221        .unwrap_or_else(std::sync::PoisonError::into_inner)
2222}
2223
2224#[cfg(test)]
2225mod tests {
2226    use super::*;
2227    use crate::queue::{Source, TaskStatus};
2228    use crate::run::{Candidate, CommandOutcome};
2229    use pretty_assertions::assert_eq;
2230
2231    fn task() -> Task {
2232        Task::new(
2233            "add retries".to_owned(),
2234            "add retries".to_owned(),
2235            PathBuf::from("/repo"),
2236            Source::Human,
2237        )
2238    }
2239
2240    #[test]
2241    fn every_run_status_settles_the_task_it_came_from() {
2242        // run status, resulting task status, attempts still standing after one
2243        let table = [
2244            (RunStatus::Merged, TaskStatus::Done, 1),
2245            (RunStatus::Ready, TaskStatus::Done, 1),
2246            (RunStatus::Stalled, TaskStatus::Failed, 0),
2247            (RunStatus::Blocked, TaskStatus::Failed, 1),
2248            (RunStatus::Failed, TaskStatus::Failed, 1),
2249            (RunStatus::Prep, TaskStatus::Failed, 1),
2250            (RunStatus::Implementing, TaskStatus::Failed, 1),
2251            (RunStatus::Judging, TaskStatus::Failed, 1),
2252            (RunStatus::Deliberating, TaskStatus::Failed, 1),
2253            (RunStatus::Voting, TaskStatus::Failed, 1),
2254            (RunStatus::Reviewing, TaskStatus::Failed, 1),
2255            (RunStatus::Gating, TaskStatus::Failed, 1),
2256        ];
2257        for (run, want, attempts) in table {
2258            let mut t = task();
2259            t.start("20260902-000000-aaaa".to_owned());
2260            settle(
2261                &mut t,
2262                Verdict {
2263                    status: run,
2264                    left_pr: false,
2265                    parked: false,
2266                    quota_hit: matches!(run, RunStatus::Stalled),
2267                    no_viable_candidates: false,
2268                },
2269                "why",
2270                2,
2271            );
2272            assert_eq!(t.status, want, "task status after {}", label(run));
2273            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
2274        }
2275    }
2276
2277    #[test]
2278    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
2279        let mut stalled = task();
2280        stalled.start("20260902-000000-aaaa".to_owned());
2281        settle(
2282            &mut stalled,
2283            Verdict {
2284                status: RunStatus::Stalled,
2285                left_pr: false,
2286                parked: false,
2287                quota_hit: true,
2288                no_viable_candidates: false,
2289            },
2290            "quota",
2291            1,
2292        );
2293        assert_eq!(stalled.attempts, 0);
2294        assert!(
2295            stalled.status.runnable(),
2296            "a machine problem must leave the task in line"
2297        );
2298
2299        let mut blocked = task();
2300        blocked.start("20260902-000000-aaaa".to_owned());
2301        settle(
2302            &mut blocked,
2303            Verdict {
2304                status: RunStatus::Blocked,
2305                left_pr: false,
2306                parked: false,
2307                quota_hit: false,
2308                no_viable_candidates: false,
2309            },
2310            "findings open",
2311            1,
2312        );
2313        assert_eq!(blocked.attempts, 1);
2314        assert_eq!(
2315            blocked.status,
2316            TaskStatus::Held,
2317            "the last attempt hands the task to a human"
2318        );
2319    }
2320
2321    #[test]
2322    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
2323        // Attempts to spare: without the pull request this task would go
2324        // straight back in line and run the whole competition again.
2325        let mut delivered = task();
2326        delivered.start("20260903-080619-01c2".to_owned());
2327        settle(
2328            &mut delivered,
2329            Verdict {
2330                status: RunStatus::Blocked,
2331                left_pr: true,
2332                parked: false,
2333                quota_hit: false,
2334                no_viable_candidates: false,
2335            },
2336            "no check status",
2337            4,
2338        );
2339        assert_eq!(
2340            delivered.status,
2341            TaskStatus::Held,
2342            "a pull request waiting on CI or a person is not a retryable failure"
2343        );
2344        assert!(
2345            !delivered.status.runnable(),
2346            "the loop must not pick this task up again"
2347        );
2348        assert_eq!(
2349            delivered.last_error.as_deref(),
2350            Some("no check status"),
2351            "the operator needs to be told what the gate was waiting for"
2352        );
2353
2354        // The same status without a pull request is a plain failure, and with
2355        // attempts left it is retried.
2356        let mut empty_handed = task();
2357        empty_handed.start("20260903-080619-01c2".to_owned());
2358        settle(
2359            &mut empty_handed,
2360            Verdict {
2361                status: RunStatus::Blocked,
2362                left_pr: false,
2363                parked: false,
2364                quota_hit: false,
2365                no_viable_candidates: false,
2366            },
2367            "findings open",
2368            4,
2369        );
2370        assert_eq!(empty_handed.status, TaskStatus::Failed);
2371        assert!(empty_handed.status.runnable());
2372    }
2373
2374    #[test]
2375    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
2376        // Parking is the operator asking for the process back - to replace the
2377        // binary, most of all. The run's work is intact on disk, so this is
2378        // not a failed attempt, and charging for it would mean a few upgrades
2379        // could exhaust a budget meant for agents that misbehaved.
2380        let mut parked = task();
2381        parked.start("20260903-183634-2d98".to_owned());
2382        settle(
2383            &mut parked,
2384            Verdict {
2385                status: RunStatus::Implementing,
2386                left_pr: false,
2387                quota_hit: false,
2388                parked: true,
2389                no_viable_candidates: false,
2390            },
2391            "parked after `implementing`",
2392            2,
2393        );
2394        assert_eq!(parked.attempts, 0, "a park is refunded");
2395        assert!(
2396            parked.status.runnable(),
2397            "and the task stays in line so the next loop resumes its run"
2398        );
2399        assert_eq!(
2400            parked.last_error.as_deref(),
2401            Some("parked after `implementing`"),
2402            "the card says where it stopped"
2403        );
2404
2405        // Without the park flag the same non-terminal status is what it always
2406        // was: `execute` returning mid-flight, which is a bug and spends an
2407        // attempt so a task cannot loop on it forever.
2408        let mut broken = task();
2409        broken.start("20260903-183634-2d98".to_owned());
2410        settle(
2411            &mut broken,
2412            Verdict {
2413                status: RunStatus::Implementing,
2414                left_pr: false,
2415                quota_hit: false,
2416                parked: false,
2417                no_viable_candidates: false,
2418            },
2419            "returned mid-flight",
2420            2,
2421        );
2422        assert_eq!(broken.attempts, 1);
2423    }
2424
2425    #[test]
2426    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
2427        // Run e633: quorum lost because two judges answered with the wrong
2428        // JSON shape, `quota: []`. Refunding that takes the bound off the
2429        // retry loop, and each retry pays for a fresh hour-long implement
2430        // wave before it can fail the same way.
2431        let mut flaky = task();
2432        flaky.start("20260903-123023-e633".to_owned());
2433        settle(
2434            &mut flaky,
2435            Verdict {
2436                status: RunStatus::Stalled,
2437                left_pr: false,
2438                parked: false,
2439                quota_hit: false,
2440                no_viable_candidates: false,
2441            },
2442            "verdict rests on 1 of 3 judges",
2443            2,
2444        );
2445        assert_eq!(
2446            flaky.attempts, 1,
2447            "flakiness spends an attempt, so `max_attempts` still bounds it"
2448        );
2449        assert!(flaky.status.runnable(), "and it is still worth retrying");
2450
2451        // The same status, lost to a rate limit, is the machine's fault.
2452        let mut limited = task();
2453        limited.start("20260903-123023-e633".to_owned());
2454        settle(
2455            &mut limited,
2456            Verdict {
2457                status: RunStatus::Stalled,
2458                left_pr: false,
2459                parked: false,
2460                quota_hit: true,
2461                no_viable_candidates: false,
2462            },
2463            "judge-2, judge-3 out of quota",
2464            2,
2465        );
2466        assert_eq!(limited.attempts, 0, "a quota window is refunded");
2467        assert!(limited.status.runnable());
2468
2469        // And the bound really binds: a task that keeps stalling on flakiness
2470        // reaches a human instead of running the roster forever.
2471        let mut worn = task();
2472        for _ in 0..2 {
2473            worn.release();
2474        }
2475        worn.start("20260903-123023-e633".to_owned());
2476        worn.attempts = 2;
2477        settle(
2478            &mut worn,
2479            Verdict {
2480                status: RunStatus::Stalled,
2481                left_pr: false,
2482                parked: false,
2483                quota_hit: false,
2484                no_viable_candidates: false,
2485            },
2486            "no quorum again",
2487            2,
2488        );
2489        assert_eq!(worn.status, TaskStatus::Held);
2490        assert!(!worn.status.runnable());
2491    }
2492
2493    #[test]
2494    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
2495        // The implement wave loses every seat to the same rate limit and
2496        // `after_implement` bails with nothing viable, which surfaces as
2497        // `Failed` rather than `Stalled`. That is the same machine fact the
2498        // `Stalled`-quota row already refunds, and must be refunded the same
2499        // way, or a quota outage quietly holds every task it touches instead
2500        // of leaving them in line for the reset.
2501        let mut wiped_out = task();
2502        wiped_out.start("20260907-025000-a1b2".to_owned());
2503        settle(
2504            &mut wiped_out,
2505            Verdict {
2506                status: RunStatus::Failed,
2507                left_pr: false,
2508                parked: false,
2509                quota_hit: true,
2510                no_viable_candidates: true,
2511            },
2512            "no candidate produced a change; nothing to judge",
2513            2,
2514        );
2515        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
2516        assert!(
2517            wiped_out.status.runnable(),
2518            "a machine problem must leave the task in line"
2519        );
2520
2521        // This is the exemption that must stay narrow: a candidate that did
2522        // produce a change, and then failed for some other reason, still
2523        // spends the attempt even though a seat elsewhere hit its quota.
2524        // Otherwise every ordinary failure that happens to share a run with
2525        // an unrelated rate limit would be refunded for free.
2526        let mut partial_progress = task();
2527        partial_progress.start("20260907-025500-c3d4".to_owned());
2528        settle(
2529            &mut partial_progress,
2530            Verdict {
2531                status: RunStatus::Failed,
2532                left_pr: false,
2533                parked: false,
2534                quota_hit: true,
2535                no_viable_candidates: false,
2536            },
2537            "gate failed on the winning candidate",
2538            2,
2539        );
2540        assert_eq!(
2541            partial_progress.attempts, 1,
2542            "a candidate that actually produced a change spends the attempt \
2543             even though some other seat hit its quota"
2544        );
2545        assert!(partial_progress.status.runnable());
2546    }
2547
2548    #[test]
2549    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
2550        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
2551        // disk, and that construction must reach the same conclusion as the
2552        // one `attempt` builds from a live run, or a crash at exactly the
2553        // wrong moment gives a recovered task a different policy than one a
2554        // daemon finished settling itself.
2555        let mut t = task();
2556        t.start("20260907-025000-a1b2".to_owned());
2557        let mut state = run_state(RunStatus::Failed);
2558        state.quota.push(QuotaLoss {
2559            seat: "cand-a".to_owned(),
2560            node: "implement".to_owned(),
2561            at: Timestamp::now(),
2562            reset: None,
2563        });
2564        assert!(
2565            state.viable().is_empty(),
2566            "no candidate was added, so nothing is viable"
2567        );
2568        reclaim(&mut t, Some(state), 2);
2569        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
2570        assert!(t.status.runnable());
2571    }
2572
2573    #[test]
2574    fn a_held_task_is_never_offered_to_the_loop() {
2575        let dir = tempfile::tempdir().unwrap();
2576        let queue = Queue::at(dir.path().to_path_buf());
2577        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
2578            let mut t = task();
2579            t.id = format!("2026090{n}-000000-000{n}");
2580            t.priority = priority;
2581            queue.put(&mut t).unwrap();
2582        }
2583        let mut held = task();
2584        held.id = "20260909-000000-9999".to_owned();
2585        held.priority = 99;
2586        held.hold_machine(None);
2587        queue.put(&mut held).unwrap();
2588
2589        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
2590        assert_eq!(order.len(), 3);
2591        assert!(!order.contains(&held.id));
2592        assert_eq!(
2593            order.first().cloned(),
2594            queue.next_runnable().map(|t| t.id),
2595            "the loop's first candidate is exactly what the queue offers"
2596        );
2597        assert_eq!(
2598            order,
2599            vec![
2600                "20260902-000000-0002".to_owned(),
2601                "20260903-000000-0003".to_owned(),
2602                "20260901-000000-0001".to_owned(),
2603            ],
2604            "priority first, then oldest, so nothing starves"
2605        );
2606    }
2607
2608    #[test]
2609    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
2610        let dir = tempfile::tempdir().unwrap();
2611        let queue = Queue::at(dir.path().to_path_buf());
2612        let mut old = task();
2613        old.id = "20260101-000000-old0".to_owned();
2614        queue.put(&mut old).unwrap();
2615        let mut fresh = task();
2616        fresh.id = "20260101-000000-new0".to_owned();
2617        queue.put(&mut fresh).unwrap();
2618
2619        // No parseable pid at all, so age is the only signal there is to
2620        // check - unlike a real `Queue::claim`, which always names a real,
2621        // and therefore alive, pid this test cannot fake as dead.
2622        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
2623        std::thread::sleep(Duration::from_millis(60));
2624        let live = queue.claim(&fresh.id).unwrap();
2625
2626        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
2627        assert_eq!(swept, vec![old.id.clone()]);
2628        assert!(
2629            queue.claim(&old.id).is_ok(),
2630            "an unparseable lock older than the threshold is swept"
2631        );
2632        assert!(
2633            queue.claim(&fresh.id).is_err(),
2634            "a live pid protects its lock regardless of age"
2635        );
2636        drop(live);
2637    }
2638
2639    #[test]
2640    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
2641        // The regression this guards: `sweep` now runs concurrently with
2642        // every attempt this daemon itself has spawned (see
2643        // `InFlightGuard`), not only between them the way a single
2644        // sequential loop once did. A run that legitimately outlives
2645        // `older_than` still has this very process's own live pid sitting in
2646        // its own lock file on every later sweep, and deciding by age alone
2647        // would delete that still-valid claim out from under the attempt
2648        // that holds it - which `reclaim_orphaned_running` would then read
2649        // as abandoned and hand to a second, competing attempt.
2650        let dir = tempfile::tempdir().unwrap();
2651        let queue = Queue::at(dir.path().to_path_buf());
2652        let mut t = task();
2653        t.id = "20260101-000000-live".to_owned();
2654        queue.put(&mut t).unwrap();
2655
2656        let claim = queue.claim(&t.id).unwrap();
2657        std::thread::sleep(Duration::from_millis(60));
2658
2659        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
2660        assert!(
2661            swept.is_empty(),
2662            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
2663        );
2664        assert!(
2665            queue.claim(&t.id).is_err(),
2666            "the lock still protects its task"
2667        );
2668        drop(claim);
2669    }
2670
2671    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
2672    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
2673    fn injected_dead_pid() -> u32 {
2674        std::process::id().checked_add(1).unwrap_or(1)
2675    }
2676
2677    #[test]
2678    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
2679        let dir = tempfile::tempdir().unwrap();
2680        let queue = Queue::at(dir.path().to_path_buf());
2681        let mut t = task();
2682        t.id = "20260101-000000-dead".to_owned();
2683        queue.put(&mut t).unwrap();
2684        let dead_pid = injected_dead_pid();
2685
2686        // Written directly rather than through `Queue::claim`, which would
2687        // stamp this test process's own very much alive pid and defeat the
2688        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
2689        // like moments after it died, not six hours later.
2690        std::fs::write(
2691            dir.path().join(format!("{}.lock", t.id)),
2692            dead_pid.to_string(),
2693        )
2694        .unwrap();
2695
2696        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
2697            pid != dead_pid
2698        });
2699        assert_eq!(
2700            swept,
2701            vec![t.id.clone()],
2702            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
2703        );
2704        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
2705    }
2706
2707    #[test]
2708    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
2709        let dir = tempfile::tempdir().unwrap();
2710        let queue = Queue::at(dir.path().to_path_buf());
2711        let mut t = task();
2712        t.id = "20260101-000000-late".to_owned();
2713        queue.put(&mut t).unwrap();
2714        let dead_pid = injected_dead_pid();
2715
2716        // Tick one, standing in for the sweep `poll` already runs at
2717        // startup: nothing to find yet.
2718        assert!(
2719            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
2720            "nothing has claimed the task yet"
2721        );
2722
2723        // A second daemon claims the task and dies before it ever writes
2724        // `running`, well after this loop's own startup sweep already ran.
2725        std::fs::write(
2726            dir.path().join(format!("{}.lock", t.id)),
2727            dead_pid.to_string(),
2728        )
2729        .unwrap();
2730
2731        // Tick two, standing in for a poll long into this daemon's uptime:
2732        // the same function, called again, notices what only just appeared -
2733        // proving the sweep is not a one-shot startup check.
2734        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
2735            pid != dead_pid
2736        });
2737        assert_eq!(swept, vec![t.id.clone()]);
2738    }
2739
2740    #[test]
2741    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
2742        // `reclaim_orphaned_running` looks up the task's last run, which
2743        // touches `run::home()`; the first call anywhere in this binary wins,
2744        // so this is a no-op if another test already pinned one, and either
2745        // way the run id below is never written under it.
2746        crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
2747        let dir = tempfile::tempdir().unwrap();
2748        let queue = Queue::at(dir.path().to_path_buf());
2749        let mut t = task();
2750        t.id = "20260101-000000-crsh".to_owned();
2751        t.status = TaskStatus::Running;
2752        t.attempts = 1;
2753        // No `run.json` behind this id: standing in for a run this test does
2754        // not need to make readable, since the point is the lock, not the
2755        // recovery table `reclaim` already has its own tests for.
2756        t.runs.push("20260904-000000-4043".to_owned());
2757        queue.put(&mut t).unwrap();
2758        let dead_pid = injected_dead_pid();
2759
2760        // The crashed daemon's own claim, naming a pid nothing on the
2761        // machine holds anymore.
2762        std::fs::write(
2763            dir.path().join(format!("{}.lock", t.id)),
2764            dead_pid.to_string(),
2765        )
2766        .unwrap();
2767
2768        // Before the lock is swept the task looks claimed, and
2769        // `reclaim_orphaned_running` must leave it alone - this is exactly
2770        // the bug: a `running` task stranded behind a dead daemon's lock,
2771        // invisible to the claim-as-proof check because the lock outlived
2772        // the process that wrote it.
2773        assert!(reclaim_orphaned_running(&queue, 2).is_empty());
2774        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
2775
2776        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
2777            pid != dead_pid
2778        });
2779        assert_eq!(swept, vec![t.id.clone()]);
2780
2781        let reclaimed = reclaim_orphaned_running(&queue, 2);
2782        assert_eq!(reclaimed, vec![t.id.clone()]);
2783        let after = queue.get(&t.id).unwrap();
2784        assert_eq!(
2785            after.status,
2786            TaskStatus::Held,
2787            "no run.json to recover from, so a human is asked"
2788        );
2789        assert_eq!(
2790            after.runs,
2791            vec!["20260904-000000-4043".to_owned()],
2792            "the crashed run's id is kept as evidence, not discarded"
2793        );
2794    }
2795
2796    #[test]
2797    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
2798        let dir = tempfile::tempdir().unwrap();
2799        let queue = Queue::at(dir.path().to_path_buf());
2800        let mut t = task();
2801        t.id = "20260101-000000-unknown".to_owned();
2802        queue.put(&mut t).unwrap();
2803        let dead_pid = injected_dead_pid();
2804        std::fs::write(
2805            dir.path().join(format!("{}.lock", t.id)),
2806            dead_pid.to_string(),
2807        )
2808        .unwrap();
2809
2810        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
2811        assert!(swept.is_empty(), "an unknown pid must keep its lock");
2812        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
2813    }
2814
2815    fn run_state(status: RunStatus) -> RunState {
2816        let mut state = RunState::new(
2817            PathBuf::from("/repo"),
2818            "main".to_owned(),
2819            "abc1234def".to_owned(),
2820            "add retries".to_owned(),
2821            Config::default(),
2822        );
2823        state.status = status;
2824        state
2825    }
2826
2827    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
2828        Candidate {
2829            index: 0,
2830            label,
2831            agent: "claude".to_owned(),
2832            branch: format!("magi/x/{label}"),
2833            worktree: PathBuf::from("/repo"),
2834            summary: summary.to_owned(),
2835            stat: String::new(),
2836            files: 0,
2837            commits: usize::from(!empty),
2838            empty,
2839            failed: failed.map(str::to_owned),
2840            duration_ms: 0,
2841            folded: false,
2842        }
2843    }
2844
2845    #[test]
2846    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
2847        let mut state = run_state(RunStatus::Blocked);
2848        state.gate = vec![
2849            CommandOutcome {
2850                command: "cargo make check".to_owned(),
2851                code: Some(0),
2852                output_tail: "ok".to_owned(),
2853                duration_ms: 0,
2854            },
2855            CommandOutcome {
2856                command: "cargo test".to_owned(),
2857                code: Some(101),
2858                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
2859                duration_ms: 0,
2860            },
2861        ];
2862        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
2863        assert!(d.contains("cargo test"), "{d}");
2864        assert!(
2865            !d.contains("cargo make check"),
2866            "a passing check is not a diagnostic: {d}"
2867        );
2868        assert!(d.contains("assertion failed"), "{d}");
2869    }
2870
2871    #[test]
2872    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
2873        let mut state = run_state(RunStatus::Blocked);
2874        state.event(
2875            "land",
2876            "stopped: the fixer produced no commit while 2 check(s) were failing \
2877             (build, lint); stopping instead of looping on an unchanged tree",
2878        );
2879        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
2880        assert!(d.contains("build"), "{d}");
2881        assert!(d.contains("lint"), "{d}");
2882        assert!(d.contains("fixer produced no commit"), "{d}");
2883    }
2884
2885    #[test]
2886    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
2887        // The whole point of the feature: a run held as "no candidate produced
2888        // a change" can mean the implementer actually finished the task and
2889        // only left a clean local tree behind - see AGENTS.md on this exact
2890        // failure mode. The diagnostic has to carry what the agent actually
2891        // said, not just the fact that nothing was there to judge.
2892        let mut state = run_state(RunStatus::Failed);
2893        state.candidates = vec![candidate(
2894            'A',
2895            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
2896            true,
2897            None,
2898        )];
2899        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
2900        assert!(d.contains("candidate A"), "{d}");
2901        assert!(d.contains("tagged v1.2.3"), "{d}");
2902    }
2903
2904    #[test]
2905    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
2906        let mut state = run_state(RunStatus::Failed);
2907        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
2908        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
2909        assert!(d.contains("candidate A"), "{d}");
2910        assert!(d.contains("agent timed out"), "{d}");
2911    }
2912
2913    #[test]
2914    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
2915        // A viable candidate existed, the gate never ran, and nothing land
2916        // said matches - `Task::last_error` is left to explain this one alone.
2917        let mut state = run_state(RunStatus::Failed);
2918        state.candidates = vec![candidate('A', "did the work", false, None)];
2919        assert!(diagnostic(&state).is_none());
2920    }
2921
2922    #[test]
2923    fn diagnostic_is_bounded_however_much_a_run_printed() {
2924        let mut state = run_state(RunStatus::Blocked);
2925        state.gate = vec![
2926            CommandOutcome {
2927                command: "cargo test".to_owned(),
2928                code: Some(101),
2929                output_tail: "x".repeat(50_000),
2930                duration_ms: 0,
2931            },
2932            CommandOutcome {
2933                command: "cargo clippy".to_owned(),
2934                code: Some(1),
2935                output_tail: "y".repeat(50_000),
2936                duration_ms: 0,
2937            },
2938        ];
2939        state.candidates = vec![
2940            candidate('A', &"z".repeat(50_000), true, None),
2941            candidate('B', &"w".repeat(50_000), true, None),
2942        ];
2943        let d = diagnostic(&state).expect("plenty here to diagnose");
2944        assert!(
2945            d.len() <= DIAGNOSTIC_MAX,
2946            "diagnostic grew to {} bytes, unbounded",
2947            d.len()
2948        );
2949    }
2950
2951    #[test]
2952    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
2953        let mut state = run_state(RunStatus::Blocked);
2954        state.gate = vec![CommandOutcome {
2955            command: "cargo test".to_owned(),
2956            code: Some(101),
2957            output_tail: "assertion failed".to_owned(),
2958            duration_ms: 0,
2959        }];
2960        let verdict = Verdict {
2961            status: RunStatus::Blocked,
2962            left_pr: false,
2963            quota_hit: false,
2964            parked: false,
2965            no_viable_candidates: false,
2966        };
2967
2968        // Attempt one of two still has a retry coming: no diagnostic yet, the
2969        // task is going to run again and this run's evidence would go stale.
2970        let mut t = task();
2971        t.start("run-1".to_owned());
2972        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
2973        assert_eq!(t.status, TaskStatus::Failed);
2974        assert!(t.diagnostic.is_none());
2975
2976        // Attempt two exhausts the budget: now it is held, and the
2977        // diagnostic is what `magi task show` has to say more than one line.
2978        t.start("run-2".to_owned());
2979        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
2980        assert_eq!(t.status, TaskStatus::Held);
2981        let d = t.diagnostic.expect("a held task must carry its diagnostic");
2982        assert!(d.contains("cargo test"), "{d}");
2983    }
2984
2985    fn approval_question(run: &str) -> ask::Question {
2986        ask::Question::new(
2987            run.to_owned(),
2988            land::APPROVAL_NODE.to_owned(),
2989            "land".to_owned(),
2990            "merge?".to_owned(),
2991            String::new(),
2992            vec!["merge".to_owned(), "hold".to_owned()],
2993        )
2994    }
2995
2996    #[test]
2997    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
2998        crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
2999        let mut state = run_state(RunStatus::Landing);
3000        state.id = "20260101-000000-fre1".to_owned();
3001        state.parked = true;
3002        state.save().unwrap();
3003        ask::Questions::open()
3004            .put(&mut approval_question(&state.id))
3005            .unwrap();
3006
3007        let mut t = task();
3008        t.runs.push(state.id.clone());
3009        assert_eq!(
3010            land_resume_state(&t),
3011            LandResume::StillWaiting,
3012            "nobody has answered and the timeout has not passed"
3013        );
3014    }
3015
3016    #[test]
3017    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
3018        // `ask::ask_and_wait`'s own deadline used to retire a question
3019        // nobody answered; land's approval bypasses that wait (see
3020        // `land::approval_gate`), so this is now the only place
3021        // `graph.answer_timeout` is enforced for a land approval at all.
3022        crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
3023        let mut state = run_state(RunStatus::Landing);
3024        state.id = "20260101-000000-exp1".to_owned();
3025        state.parked = true;
3026        state.config.graph.answer_timeout = 60;
3027        state.save().unwrap();
3028
3029        let store = ask::Questions::open();
3030        let mut q = approval_question(&state.id);
3031        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
3032        store.put(&mut q).unwrap();
3033
3034        let mut t = task();
3035        t.runs.push(state.id.clone());
3036        assert_eq!(
3037            land_resume_state(&t),
3038            LandResume::Ready,
3039            "an expired question must not be waited on forever"
3040        );
3041
3042        let after = store.get(&q.id).unwrap();
3043        assert!(
3044            !after.status.open(),
3045            "the question is abandoned, not silently ignored"
3046        );
3047        assert!(
3048            after.resolution().is_none(),
3049            "an abandoned question is not read as a decision"
3050        );
3051    }
3052
3053    #[test]
3054    fn reclaim_settles_a_running_task_against_its_last_run() {
3055        let mut t = task();
3056        t.start("20260904-000000-4043".to_owned());
3057        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2);
3058        assert_eq!(
3059            t.status,
3060            TaskStatus::Done,
3061            "a run that actually finished must not stay `running` forever"
3062        );
3063    }
3064
3065    #[test]
3066    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
3067        // A blocked run with attempts left goes back to `Failed`, exactly as
3068        // it would from `attempt` itself - `reclaim` must not invent a second
3069        // policy for a task a daemon merely stopped without reporting.
3070        let mut t = task();
3071        t.start("20260904-000000-4043".to_owned());
3072        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2);
3073        assert_eq!(t.status, TaskStatus::Failed);
3074        assert!(t.status.runnable());
3075    }
3076
3077    #[test]
3078    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
3079        let mut t = task();
3080        t.start("20260904-000000-4043".to_owned());
3081        reclaim(&mut t, None, 2);
3082        assert_eq!(t.status, TaskStatus::Held);
3083        assert!(
3084            t.last_error
3085                .as_deref()
3086                .is_some_and(|e| e.contains("running")),
3087            "the operator needs to know why this task was held"
3088        );
3089    }
3090
3091    #[test]
3092    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
3093        let dir = tempfile::tempdir().unwrap();
3094        let queue = Queue::at(dir.path().to_path_buf());
3095
3096        // No run recorded, so this never has to touch `RunState::load`.
3097        let mut orphaned = task();
3098        orphaned.id = "20260904-000000-orph".to_owned();
3099        orphaned.status = TaskStatus::Running;
3100        orphaned.attempts = 1;
3101        queue.put(&mut orphaned).unwrap();
3102
3103        let mut alive = task();
3104        alive.id = "20260904-000000-live".to_owned();
3105        alive.status = TaskStatus::Running;
3106        alive.attempts = 1;
3107        queue.put(&mut alive).unwrap();
3108        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
3109
3110        let mut queued = task();
3111        queued.id = "20260904-000000-wait".to_owned();
3112        queue.put(&mut queued).unwrap();
3113
3114        let reclaimed = reclaim_orphaned_running(&queue, 2);
3115        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
3116
3117        assert_eq!(
3118            queue.get(&orphaned.id).unwrap().status,
3119            TaskStatus::Held,
3120            "nothing was driving it and there was no run to recover"
3121        );
3122        assert_eq!(
3123            queue.get(&alive.id).unwrap().status,
3124            TaskStatus::Running,
3125            "a live claim must protect the task it belongs to"
3126        );
3127        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
3128    }
3129
3130    #[test]
3131    fn an_already_claimed_task_is_skipped_rather_than_failed() {
3132        let dir = tempfile::tempdir().unwrap();
3133        let queue = Queue::at(dir.path().to_path_buf());
3134        let mut only = task();
3135        queue.put(&mut only).unwrap();
3136
3137        let _elsewhere = queue.claim(&only.id).unwrap();
3138        let candidates = runnable(&queue);
3139        assert_eq!(candidates.len(), 1, "the task is still runnable");
3140        assert!(
3141            queue.claim(&candidates[0].id).is_err(),
3142            "the loop cannot take a claim somebody else holds"
3143        );
3144
3145        let after = queue.get(&only.id).unwrap();
3146        assert_eq!(after.status, TaskStatus::Queued);
3147        assert_eq!(
3148            after.attempts, 0,
3149            "losing the race is not an attempt at the task"
3150        );
3151        assert_eq!(after.last_error, None);
3152    }
3153
3154    #[test]
3155    fn the_status_file_round_trips_and_its_heartbeat_advances() {
3156        let dir = tempfile::tempdir().unwrap();
3157        let path = dir.path().join("daemon.json");
3158
3159        let mut status = Status::new();
3160        status.idle = false;
3161        status.completed = 7;
3162        status.current = vec![Current {
3163            task: "20260902-000000-t111".to_owned(),
3164            run: "20260902-000001-r111".to_owned(),
3165        }];
3166        write_status_to(&path, &status).unwrap();
3167        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
3168        assert_eq!(first.schema, SCHEMA);
3169        assert_eq!(first.pid, std::process::id());
3170        assert!(!first.idle);
3171        assert_eq!(first.completed, 7);
3172        assert_eq!(first.current, status.current);
3173        assert!(
3174            !path.with_extension("json.tmp").exists(),
3175            "the temp file is renamed, not left behind"
3176        );
3177
3178        std::thread::sleep(Duration::from_millis(5));
3179        status.updated_at = Timestamp::now();
3180        status.polls = 3;
3181        write_status_to(&path, &status).unwrap();
3182        let second: Status =
3183            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
3184        assert!(
3185            second.updated_at > first.updated_at,
3186            "a reader can only detect staleness if the heartbeat moves"
3187        );
3188        assert_eq!(
3189            second.started_at, first.started_at,
3190            "the start time is not a heartbeat"
3191        );
3192        assert_eq!(second.polls, 3);
3193    }
3194
3195    #[test]
3196    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
3197        let dir = tempfile::tempdir().unwrap();
3198
3199        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
3200
3201        let mut status = Status::new();
3202        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
3203        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
3204        let stale = read_status(dir.path()).unwrap();
3205        assert!(
3206            !stale.running(Timestamp::now()),
3207            "a minute without a heartbeat is a dead daemon, not a busy one"
3208        );
3209        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
3210
3211        status.updated_at = Timestamp::now();
3212        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
3213        let fresh = read_status(dir.path()).unwrap();
3214        assert!(fresh.running(Timestamp::now()));
3215    }
3216
3217    #[test]
3218    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
3219        let dir = tempfile::tempdir().unwrap();
3220        let now = Timestamp::now();
3221        let mine = "20260903-080619-01c2";
3222
3223        assert!(
3224            !is_working_on(dir.path(), mine, now),
3225            "no status file means nobody is working on anything"
3226        );
3227
3228        let mut status = Status::new();
3229        status.current = vec![Current {
3230            task: "20260903-080340-0167".to_owned(),
3231            run: mine.to_owned(),
3232        }];
3233        status.updated_at = now;
3234        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
3235        assert!(is_working_on(dir.path(), mine, now));
3236        assert!(
3237            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
3238            "a daemon busy with one run is not working on another"
3239        );
3240
3241        // A killed daemon stops writing heartbeats but leaves the file behind
3242        // naming the run it died in. That run must not be undeletable forever.
3243        status.updated_at = now - jiff::SignedDuration::from_secs(600);
3244        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
3245        assert!(
3246            !is_working_on(dir.path(), mine, now),
3247            "a stale heartbeat is a dead daemon, so its run is a leftover"
3248        );
3249    }
3250
3251    #[test]
3252    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
3253        let dir = tempfile::tempdir().unwrap();
3254        let now = Timestamp::now();
3255
3256        assert!(
3257            !is_working_on_short(dir.path(), "01c2", now),
3258            "no status file means nobody is working on anything"
3259        );
3260
3261        let mut status = Status::new();
3262        status.current = vec![Current {
3263            task: "20260903-080340-0167".to_owned(),
3264            run: "20260903-080619-01c2".to_owned(),
3265        }];
3266        status.updated_at = now;
3267        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
3268        assert!(
3269            is_working_on_short(dir.path(), "01c2", now),
3270            "the run's short id is the last block of its full id"
3271        );
3272        assert!(
3273            !is_working_on_short(dir.path(), "3cbf", now),
3274            "a daemon busy with one worktree bay is not working on another"
3275        );
3276    }
3277
3278    #[test]
3279    fn a_newer_status_file_still_yields_a_reading() {
3280        let dir = tempfile::tempdir().unwrap();
3281        // A field this build has never heard of must not turn the reading into
3282        // nothing at all; that is the whole reason the reader is permissive.
3283        std::fs::write(
3284            dir.path().join("daemon.json"),
3285            serde_json::json!({
3286                "schema": 2,
3287                "updated_at": Timestamp::now().to_string(),
3288                "idle": true,
3289                "surprise": { "nested": [1, 2, 3] },
3290            })
3291            .to_string(),
3292        )
3293        .unwrap();
3294
3295        let reading = read_status(dir.path()).expect("a forward-compatible read");
3296        assert!(reading.running(Timestamp::now()));
3297        assert!(reading.idle);
3298        assert!(reading.current.is_empty());
3299    }
3300
3301    #[test]
3302    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
3303        // A daemon started before `current` became a list keeps writing this
3304        // shape on every heartbeat until it is restarted. A rolling upgrade
3305        // - a newer `magi web` or `magi doctor` reading an older `magi
3306        // serve`'s heartbeat - must still see the run it is on, not "no
3307        // daemon" from a type mismatch failing the whole struct.
3308        let dir = tempfile::tempdir().unwrap();
3309        std::fs::write(
3310            dir.path().join("daemon.json"),
3311            serde_json::json!({
3312                "schema": 1,
3313                "pid": 4242,
3314                "updated_at": Timestamp::now().to_string(),
3315                "idle": false,
3316                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
3317                "completed": 3,
3318                "polls": 9,
3319            })
3320            .to_string(),
3321        )
3322        .unwrap();
3323
3324        let reading = read_status(dir.path()).expect("an older shape must still parse");
3325        assert!(reading.running(Timestamp::now()));
3326        assert_eq!(
3327            reading.current,
3328            vec![Current {
3329                task: "20260902-140501-aaaa".to_owned(),
3330                run: "20260902-140502-bbbb".to_owned(),
3331            }]
3332        );
3333    }
3334
3335    #[test]
3336    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
3337        let dir = tempfile::tempdir().unwrap();
3338        std::fs::write(
3339            dir.path().join("daemon.json"),
3340            serde_json::json!({
3341                "schema": 1,
3342                "updated_at": Timestamp::now().to_string(),
3343                "idle": true,
3344                "current": null,
3345            })
3346            .to_string(),
3347        )
3348        .unwrap();
3349        let with_null = read_status(dir.path()).expect("null must still parse");
3350        assert!(with_null.current.is_empty());
3351
3352        std::fs::write(
3353            dir.path().join("daemon.json"),
3354            serde_json::json!({
3355                "schema": 1,
3356                "updated_at": Timestamp::now().to_string(),
3357                "idle": true,
3358            })
3359            .to_string(),
3360        )
3361        .unwrap();
3362        let absent = read_status(dir.path()).expect("a missing field must still parse");
3363        assert!(absent.current.is_empty());
3364    }
3365
3366    #[test]
3367    fn a_task_without_a_repository_runs_in_the_daemons_default() {
3368        let fallback = Path::new("/default");
3369        let mut blank = task();
3370        blank.repo = PathBuf::new();
3371        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
3372        let mut dot = task();
3373        dot.repo = PathBuf::from(".");
3374        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
3375        assert_eq!(
3376            repo_for(&task(), fallback),
3377            PathBuf::from("/repo"),
3378            "a task that names a repository keeps it"
3379        );
3380    }
3381
3382    #[test]
3383    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
3384        // Three seats said out loud. What `solo` promises is one candidate
3385        // *whatever the config asks for*, so the contrast has to be a number
3386        // this test owns - it used to be `Config::default()`'s, which became
3387        // 1 when one implementation became the default and left the two
3388        // halves of this test asserting the same thing.
3389        let mut solo_cfg = Config::default();
3390        solo_cfg.graph.candidates = 3;
3391        let mut solo_task = task();
3392        solo_task.solo = true;
3393        apply_solo(&mut solo_cfg, &solo_task);
3394        assert_eq!(solo_cfg.graph.candidates, 1);
3395
3396        let mut plain_cfg = Config::default();
3397        plain_cfg.graph.candidates = 3;
3398        let plain_task = task();
3399        assert!(!plain_task.solo);
3400        apply_solo(&mut plain_cfg, &plain_task);
3401        assert_eq!(
3402            plain_cfg.graph.candidates, 3,
3403            "a task that did not ask to run alone keeps the config's candidates"
3404        );
3405    }
3406
3407    #[test]
3408    fn merge_overrides_are_parsed_or_refused() {
3409        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
3410        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
3411        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
3412        assert!(merge_mode("squash").is_err());
3413    }
3414
3415    #[test]
3416    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
3417        let now = Timestamp::now();
3418        let fallback = Duration::from_secs(300);
3419        let cap = Duration::from_secs(1800);
3420
3421        // No reset hint at all: the fallback.
3422        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
3423
3424        // A reset ten minutes out, well inside the cap: waited for exactly.
3425        let soon = now + jiff::SignedDuration::from_secs(600);
3426        assert_eq!(
3427            quota_wait(Some(soon), now, fallback, cap),
3428            Duration::from_secs(600)
3429        );
3430
3431        // A reset already in the past is not trusted: the fallback, not a
3432        // zero or negative wait that would spin the loop right back around.
3433        let past = now - jiff::SignedDuration::from_secs(60);
3434        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
3435
3436        // A reset further out than the cap is trusted for direction but not
3437        // for magnitude: a parsing slip must not sleep the loop for a day.
3438        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
3439        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
3440    }
3441
3442    #[test]
3443    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
3444        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
3445
3446        let at = parse_reset_hint("4:50am (UTC)", now).expect("a recognised shape parses");
3447        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
3448
3449        // Same clock reading, but it has already gone by today: read as
3450        // tomorrow's, since the CLI would not still be reporting a limit past
3451        // its own stated reset.
3452        let already_past =
3453            parse_reset_hint("1:00am (UTC)", now).expect("a recognised shape parses");
3454        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
3455
3456        assert!(
3457            parse_reset_hint("session limit reached", now).is_none(),
3458            "free text with no recognised shape is not guessed at"
3459        );
3460        assert!(
3461            parse_reset_hint("4:50am (Nowhere/Fake)", now).is_none(),
3462            "an unresolvable zone name is not guessed at either"
3463        );
3464    }
3465
3466    /// A loop whose queue lives in a temp tree and whose poll interval is far
3467    /// longer than the test's patience, so anything that waits out a poll
3468    /// instead of noticing the stop fails rather than merely being slow.
3469    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
3470        let config = dir.join("magi.toml");
3471        std::fs::write(
3472            &config,
3473            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
3474        )
3475        .unwrap();
3476        let opts = Opts {
3477            poll: Duration::from_secs(30),
3478            config: Some(config),
3479            // The explicit fixture config keeps startup cleanup from reading
3480            // machine configuration. This fictional repository likewise
3481            // keeps any best-effort git cleanup away from this checkout.
3482            repo: dir.join("repo"),
3483            ..Opts::default()
3484        };
3485        // The status file goes in a directory that does not exist yet, so its
3486        // creation is itself evidence the loop published one. `worktrees`
3487        // must be just as fictional: the janitor reclaims worktrees under it
3488        // for real, and a test that let it fall through to
3489        // `crate::run::default_worktree_root()` would have it reclaim
3490        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
3491        // which is exactly what happened before this function took the
3492        // parameter at all.
3493        let home = dir.join("home");
3494        let worktrees = dir.join("wt");
3495        (
3496            opts,
3497            Queue::at(dir.join("queue")),
3498            home.join("daemon.json"),
3499            home,
3500            worktrees,
3501        )
3502    }
3503
3504    #[test]
3505    fn a_stop_is_idempotent_and_once_set_stays_set() {
3506        let stop = Stop::new();
3507        assert!(!stop.stopped());
3508
3509        stop.stop();
3510        assert!(stop.stopped());
3511        stop.stop();
3512        assert!(stop.stopped(), "a second stop is not a toggle");
3513
3514        let shared = stop.clone();
3515        assert!(
3516            shared.stopped(),
3517            "a clone is the same stop; that is how the loop and its caller share one"
3518        );
3519    }
3520
3521    #[test]
3522    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
3523        let stop = Stop::new();
3524        stop.enter();
3525        assert!(
3526            !stop.finishing(),
3527            "a busy loop nobody has asked to stop is just running"
3528        );
3529
3530        stop.stop();
3531        assert!(
3532            stop.finishing(),
3533            "a stop asked for mid-run has not landed until the run is settled"
3534        );
3535
3536        stop.exit();
3537        assert!(
3538            !stop.finishing(),
3539            "once the run is settled the stop has landed and there is nothing to finish"
3540        );
3541    }
3542
3543    #[test]
3544    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
3545        let stop = Stop::new();
3546        stop.enter();
3547        stop.enter();
3548        stop.stop();
3549        assert!(stop.finishing(), "two runs still in flight");
3550
3551        stop.exit();
3552        assert!(
3553            stop.finishing(),
3554            "one run finished, but a sibling is still working"
3555        );
3556
3557        stop.exit();
3558        assert!(
3559            !stop.finishing(),
3560            "the last run out is what actually lands the stop"
3561        );
3562    }
3563
3564    #[tokio::test]
3565    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
3566        let dir = tempfile::tempdir().unwrap();
3567        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
3568        let stop = Stop::new();
3569        stop.stop();
3570
3571        let began = std::time::Instant::now();
3572        tokio::time::timeout(
3573            Duration::from_secs(2),
3574            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
3575        )
3576        .await
3577        .expect("a stopped loop must return, not sit out its poll interval")
3578        .expect("the loop's own setup and teardown must not fail");
3579        assert!(
3580            began.elapsed() < opts.poll,
3581            "returned only after {:?}, which is a poll interval, not a stop",
3582            began.elapsed()
3583        );
3584    }
3585
3586    #[tokio::test]
3587    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
3588        let dir = tempfile::tempdir().unwrap();
3589        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
3590        let stop = Stop::new();
3591
3592        // Asked for after the loop is already parked on its empty queue, which
3593        // is the case an operator tapping stop on a phone actually hits.
3594        let asker = {
3595            let stop = stop.clone();
3596            tokio::spawn(async move {
3597                tokio::time::sleep(Duration::from_millis(20)).await;
3598                stop.stop();
3599            })
3600        };
3601
3602        let began = std::time::Instant::now();
3603        tokio::time::timeout(
3604            Duration::from_secs(2),
3605            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
3606        )
3607        .await
3608        .expect("a stop asked for while idle must wake the wait")
3609        .expect("the loop's own setup and teardown must not fail");
3610        asker.await.unwrap();
3611        assert!(
3612            began.elapsed() < opts.poll,
3613            "returned only after {:?}, so the stop waited on the sleep",
3614            began.elapsed()
3615        );
3616    }
3617
3618    #[tokio::test]
3619    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
3620        let dir = tempfile::tempdir().unwrap();
3621        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
3622        let stop = Stop::new();
3623        stop.stop();
3624
3625        tokio::time::timeout(
3626            Duration::from_secs(2),
3627            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
3628        )
3629        .await
3630        .expect("a stopped loop must return")
3631        .expect("the loop's own setup and teardown must not fail");
3632
3633        assert!(
3634            home.is_dir(),
3635            "the loop did publish a status file, so its removal is the teardown and not an absence"
3636        );
3637        assert!(
3638            !status_file.exists(),
3639            "a stopped loop clears its status file"
3640        );
3641        assert!(
3642            read_status(&home).is_none(),
3643            "a reader must see no daemon at all, not a heartbeat that merely stopped"
3644        );
3645    }
3646
3647    #[tokio::test]
3648    async fn once_runs_startup_housekeeping_before_an_empty_queue_exits() {
3649        let dir = tempfile::tempdir().unwrap();
3650        let (mut opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
3651        opts.once = true;
3652
3653        let mut settled = RunState::new(
3654            dir.path().join("repo"),
3655            "main".to_owned(),
3656            "abc1234".to_owned(),
3657            "fixture".to_owned(),
3658            Config::default(),
3659        );
3660        settled.status = RunStatus::Ready;
3661        let run_dir = home.join("runs").join(&settled.id);
3662        std::fs::create_dir_all(&run_dir).unwrap();
3663        std::fs::write(
3664            run_dir.join("run.json"),
3665            serde_json::to_string_pretty(&settled).unwrap(),
3666        )
3667        .unwrap();
3668        let questions = Questions::at(home.join("questions"));
3669        let mut question = ask::Question::new(
3670            settled.id.clone(),
3671            "review".to_owned(),
3672            "reviewer-1".to_owned(),
3673            "Continue?".to_owned(),
3674            String::new(),
3675            Vec::new(),
3676        );
3677        questions.put(&mut question).unwrap();
3678
3679        drive(&opts, &queue, &status_file, &home, &worktrees, &Stop::new())
3680            .await
3681            .unwrap();
3682
3683        assert_eq!(
3684            questions.get(&question.id).unwrap().status,
3685            ask::QuestionStatus::Abandoned,
3686            "an empty --once drain still performs startup question cleanup"
3687        );
3688    }
3689
3690    #[test]
3691    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
3692        let dir = tempfile::tempdir().unwrap();
3693        let queue = Queue::at(dir.path().join("queue"));
3694        let questions = Questions::at(dir.path().join("questions"));
3695        let mut task = task();
3696        queue.put(&mut task).unwrap();
3697
3698        let mut task_question = ask::Question::new(
3699            task.id.clone(),
3700            crate::conduct::NODE.to_owned(),
3701            "conduct".to_owned(),
3702            "Which backend?".to_owned(),
3703            String::new(),
3704            Vec::new(),
3705        );
3706        questions.put(&mut task_question).unwrap();
3707        task.block(vec![task_question.id.clone()], None);
3708        queue.put(&mut task).unwrap();
3709
3710        let mut run_question = ask::Question::new(
3711            "20260101-000000-run1".to_owned(),
3712            "review".to_owned(),
3713            "reviewer-1".to_owned(),
3714            "Run question".to_owned(),
3715            String::new(),
3716            Vec::new(),
3717        );
3718        questions.put(&mut run_question).unwrap();
3719
3720        // A question from another node whose `run` happens to equal this
3721        // task's id — the same field, filled in for an unrelated reason. Only
3722        // `crate::conduct::NODE` questions use `run` as a task id; this one
3723        // must never be touched by this reconciliation, even after release.
3724        let mut coincidental = ask::Question::new(
3725            task.id.clone(),
3726            "review".to_owned(),
3727            "reviewer-1".to_owned(),
3728            "Unrelated review question".to_owned(),
3729            String::new(),
3730            Vec::new(),
3731        );
3732        questions.put(&mut coincidental).unwrap();
3733
3734        reconcile_task_questions(&queue, &questions);
3735        assert!(questions.get(&task_question.id).unwrap().status.open());
3736        assert!(questions.get(&run_question.id).unwrap().status.open());
3737        assert!(questions.get(&coincidental.id).unwrap().status.open());
3738
3739        task.release();
3740        queue.put(&mut task).unwrap();
3741        reconcile_task_questions(&queue, &questions);
3742        assert_eq!(
3743            questions.get(&task_question.id).unwrap().status,
3744            ask::QuestionStatus::Abandoned
3745        );
3746        assert!(
3747            questions.get(&run_question.id).unwrap().status.open(),
3748            "run questions remain the run janitor's responsibility"
3749        );
3750        assert!(
3751            questions.get(&coincidental.id).unwrap().status.open(),
3752            "a non-conductor question must not be abandoned just because its \
3753             run id coincides with a task id"
3754        );
3755    }
3756
3757    #[test]
3758    fn a_freshly_started_running_task_is_never_stalled() {
3759        let dir = tempfile::tempdir().unwrap();
3760        let mut t = task();
3761        t.start("run-1".to_owned());
3762        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
3763        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
3764        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
3765    }
3766
3767    #[test]
3768    fn a_long_running_task_with_no_live_daemon_is_stalled() {
3769        let dir = tempfile::tempdir().unwrap();
3770        let mut t = task();
3771        t.start("run-1".to_owned());
3772        t.updated_at = Timestamp::now()
3773            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
3774        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
3775        assert_eq!(
3776            stalled_tasks(
3777                &Queue::at(dir.path().join("q")),
3778                dir.path(),
3779                Timestamp::now()
3780            )
3781            .len(),
3782            0,
3783            "the task was never written to this queue"
3784        );
3785    }
3786
3787    #[test]
3788    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
3789        let dir = tempfile::tempdir().unwrap();
3790        let mut t = task();
3791        t.id = "20260903-080340-0167".to_owned();
3792        t.start("20260903-080619-01c2".to_owned());
3793        t.updated_at = Timestamp::now()
3794            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
3795
3796        let mut status = Status::new();
3797        status.current = vec![Current {
3798            task: t.id.clone(),
3799            run: "20260903-080619-01c2".to_owned(),
3800        }];
3801        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
3802
3803        assert!(
3804            !is_stalled(&t, dir.path(), Timestamp::now()),
3805            "a live daemon's own heartbeat rules out stalled, however long the task has run"
3806        );
3807    }
3808
3809    /// Rewrite a task's `updated_at` on disk directly, bypassing
3810    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
3811    /// a fixture look like it has genuinely been `running` for a while.
3812    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
3813        let path = queue.path_of(id);
3814        let body = std::fs::read_to_string(&path).unwrap();
3815        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
3816        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
3817        v["updated_at"] = serde_json::Value::String(old.to_string());
3818        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
3819    }
3820
3821    #[test]
3822    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
3823        // The realistic `poll()` ordering, not `is_stalled` in isolation:
3824        // `reclaim_orphaned_running` runs first, on every poll, and settles
3825        // any `running` task whose claim it can actually take. For most
3826        // crashes that is immediate - a dead pid is proof enough for
3827        // `sweep_stale_claims` to drop the lock the same tick, and the very
3828        // next claim attempt succeeds. But a lock whose pid cannot be parsed
3829        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
3830        // `sweep_stale_claims`'s own doc), so the lock - and the claim
3831        // failure behind it - can legitimately outlive many polls. This is
3832        // exactly the gap `stalled_tasks` exists to surface well before that
3833        // six-hour sweep would: reclaim leaves the task `running`, and it
3834        // must still reach the conductor as stalled.
3835        let dir = tempfile::tempdir().unwrap();
3836        let queue = Queue::at(dir.path().join("queue"));
3837        let home = dir.path().join("home");
3838
3839        let mut t = task();
3840        t.id = "20260101-000001-lock".to_owned();
3841        t.start("run-1".to_owned());
3842        queue.put(&mut t).unwrap();
3843        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
3844        std::fs::write(
3845            dir.path().join("queue").join(format!("{}.lock", t.id)),
3846            "not a pid",
3847        )
3848        .unwrap();
3849
3850        let now = Timestamp::now();
3851        assert!(
3852            reclaim_orphaned_running(&queue, 2).is_empty(),
3853            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
3854             and reclaim must leave the task alone"
3855        );
3856        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
3857
3858        let stalled = stalled_tasks(&queue, &home, now);
3859        assert_eq!(
3860            stalled.len(),
3861            1,
3862            "reclaim's inability to claim it yet must not hide it from the conductor"
3863        );
3864        assert_eq!(stalled[0].id, t.id);
3865    }
3866
3867    #[test]
3868    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
3869        let dir = tempfile::tempdir().unwrap();
3870        crate::run::set_home(dir.path().join("run-home"));
3871        let queue = Queue::at(dir.path().join("queue"));
3872        let home = dir.path().join("home");
3873        let questions = Questions::at(dir.path().join("questions"));
3874
3875        let mut t = task();
3876        t.id = "20260101-000003-dead".to_owned();
3877        t.start("missing-run".to_owned());
3878        queue.put(&mut t).unwrap();
3879        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
3880
3881        // This is the real poll ordering: retain the deterministic stalled
3882        // input before a claim proves the owner is gone and reclaims it.
3883        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
3884        assert_eq!(
3885            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
3886            [&t.id]
3887        );
3888        assert_eq!(reclaim_orphaned_running(&queue, 2), [t.id.clone()]);
3889        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
3890
3891        // Reclaim drops its guard before conductor decisions are applied, so
3892        // the decision for the captured stalled input has a real write path.
3893        crate::conduct::apply(
3894            &queue,
3895            &questions,
3896            &crate::conduct::Verdict {
3897                decisions: vec![crate::conduct::Decision {
3898                    id: t.id.clone(),
3899                    recovery: Some(crate::conduct::Recovery::Requeue),
3900                    ..crate::conduct::Decision::default()
3901                }],
3902            },
3903        )
3904        .unwrap();
3905        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
3906    }
3907
3908    #[test]
3909    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
3910        let dir = tempfile::tempdir().unwrap();
3911        let queue = Queue::at(dir.path().join("queue"));
3912        let home = dir.path().join("home");
3913
3914        let mut fresh = task();
3915        fresh.id = "20260101-000001-aaaa".to_owned();
3916        fresh.start("run-1".to_owned());
3917        queue.put(&mut fresh).unwrap();
3918
3919        let mut old = task();
3920        old.id = "20260101-000002-bbbb".to_owned();
3921        old.start("run-2".to_owned());
3922        queue.put(&mut old).unwrap();
3923        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
3924
3925        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
3926        assert_eq!(stalled.len(), 1);
3927        assert_eq!(stalled[0].id, old.id);
3928    }
3929
3930    #[test]
3931    fn queued_and_finished_task_views_partition_by_status() {
3932        let dir = tempfile::tempdir().unwrap();
3933        let queue = Queue::at(dir.path().join("queue"));
3934
3935        let mut queued = task();
3936        queued.id = "20260101-000001-aaaa".to_owned();
3937        queue.put(&mut queued).unwrap();
3938
3939        let mut failed = task();
3940        failed.id = "20260101-000002-bbbb".to_owned();
3941        failed.start("run-1".to_owned());
3942        failed.fail("gate red", 5);
3943        queue.put(&mut failed).unwrap();
3944
3945        let mut held = task();
3946        held.id = "20260101-000003-cccc".to_owned();
3947        held.hold_machine(None);
3948        queue.put(&mut held).unwrap();
3949
3950        let mut running = task();
3951        running.id = "20260101-000004-dddd".to_owned();
3952        running.start("run-2".to_owned());
3953        queue.put(&mut running).unwrap();
3954
3955        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
3956        assert_eq!(queued_ids, [queued.id.clone()]);
3957
3958        let mut finished_ids: Vec<String> =
3959            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
3960        finished_ids.sort_unstable();
3961        let mut want = vec![failed.id.clone(), held.id.clone()];
3962        want.sort_unstable();
3963        assert_eq!(finished_ids, want);
3964    }
3965
3966    #[test]
3967    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
3968        let dir = tempfile::tempdir().unwrap();
3969        let queue = Queue::at(dir.path().join("queue"));
3970        let questions = ask::Questions::at(dir.path().join("questions"));
3971
3972        let mut dep = task();
3973        dep.id = "20260101-000001-dep0".to_owned();
3974        dep.succeed();
3975        queue.put(&mut dep).unwrap();
3976
3977        let mut still_going = task();
3978        still_going.id = "20260101-000002-dep1".to_owned();
3979        queue.put(&mut still_going).unwrap();
3980
3981        let mut blocked = task();
3982        blocked.id = "20260101-000003-main".to_owned();
3983        blocked.block(
3984            vec![dep.id.clone(), still_going.id.clone()],
3985            Some("waits on both".to_owned()),
3986        );
3987        queue.put(&mut blocked).unwrap();
3988
3989        resolve_blockers(&queue, &questions);
3990
3991        let after = queue.get(&blocked.id).unwrap();
3992        assert_eq!(
3993            after.status,
3994            TaskStatus::Blocked,
3995            "one dependency is still outstanding"
3996        );
3997        assert_eq!(after.blocked_by, [still_going.id.clone()]);
3998    }
3999
4000    #[test]
4001    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
4002        let dir = tempfile::tempdir().unwrap();
4003        let queue = Queue::at(dir.path().join("queue"));
4004        let questions = ask::Questions::at(dir.path().join("questions"));
4005
4006        let mut q = crate::ask::Question::new(
4007            "20260101-000001-main".to_owned(),
4008            crate::conduct::NODE.to_owned(),
4009            "conduct".to_owned(),
4010            "Which backend?".to_owned(),
4011            String::new(),
4012            Vec::new(),
4013        );
4014        questions.put(&mut q).unwrap();
4015        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
4016            .unwrap();
4017        questions.put(&mut q).unwrap();
4018
4019        let mut blocked = task();
4020        blocked.id = "20260101-000001-main".to_owned();
4021        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
4022        queue.put(&mut blocked).unwrap();
4023
4024        resolve_blockers(&queue, &questions);
4025
4026        let after = queue.get(&blocked.id).unwrap();
4027        assert_eq!(
4028            after.status,
4029            TaskStatus::Queued,
4030            "the only blocker resolved"
4031        );
4032        assert_eq!(after.answers.len(), 1);
4033        assert_eq!(after.answers[0].question, "Which backend?");
4034        assert_eq!(after.answers[0].answer, "SQLite");
4035
4036        // And the run this task starts next is told about it.
4037        let instruction = instruction_for(&after);
4038        assert!(instruction.contains("Which backend?"));
4039        assert!(instruction.contains("SQLite"));
4040    }
4041
4042    #[test]
4043    fn instruction_for_is_unchanged_without_any_answers() {
4044        let t = task();
4045        assert_eq!(instruction_for(&t), t.instruction);
4046    }
4047
4048    #[test]
4049    fn resumed_instruction_is_unchanged_without_any_answers() {
4050        let t = task();
4051        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
4052    }
4053
4054    #[test]
4055    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
4056        let mut t = task();
4057        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
4058        // The run's own instruction on disk predates the answer: it is the
4059        // plain original text `Runner::start` saved before the operator was
4060        // ever asked anything.
4061        let old = t.instruction.clone();
4062
4063        let refreshed = resumed_instruction(&old, &t);
4064        assert!(refreshed.starts_with(&old), "the original text is kept");
4065        assert!(refreshed.contains("Which backend?"));
4066        assert!(refreshed.contains("SQLite"));
4067    }
4068
4069    #[test]
4070    fn resumed_instruction_keeps_an_original_answers_heading() {
4071        let mut t = task();
4072        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
4073        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
4074
4075        let refreshed = resumed_instruction(&t.instruction, &t);
4076
4077        assert!(
4078            refreshed.starts_with(&t.instruction),
4079            "an answers heading in the original instruction is not the appended block"
4080        );
4081        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
4082        assert!(refreshed.contains("Which backend?"));
4083        assert!(refreshed.contains("SQLite"));
4084
4085        let repeated = resumed_instruction(&refreshed, &t);
4086        assert_eq!(
4087            repeated, refreshed,
4088            "only the final appended block is refreshed"
4089        );
4090    }
4091
4092    #[test]
4093    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
4094        let mut t = task();
4095        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
4096
4097        // A first resume appends the block; a second resume of the same run,
4098        // with no new answer in between, must reproduce exactly the same
4099        // text rather than appending the block a second time.
4100        let once = resumed_instruction(&t.instruction, &t);
4101        let twice = resumed_instruction(&once, &t);
4102        assert_eq!(once, twice);
4103        assert_eq!(once.matches("Which backend?").count(), 1);
4104
4105        // A later answer replaces the block wholesale rather than growing it.
4106        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
4107        let refreshed = resumed_instruction(&once, &t);
4108        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
4109        assert!(refreshed.contains("Which backend?"));
4110        assert!(refreshed.contains("Which cache?"));
4111    }
4112
4113    #[test]
4114    fn prepare_instruction_covers_all_three_starters() {
4115        let mut t = task();
4116        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
4117
4118        // Start: a fresh run gets the task text plus every answer so far —
4119        // exactly `instruction_for`.
4120        assert_eq!(
4121            prepare_instruction(&Starter::Start, None, &t),
4122            Some(instruction_for(&t))
4123        );
4124
4125        // Resume: the run's prior instruction is refreshed with the answer,
4126        // not discarded and not left stale.
4127        let old = t.instruction.clone();
4128        assert_eq!(
4129            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
4130            Some(resumed_instruction(&old, &t))
4131        );
4132
4133        // Review: a review-only pass builds its own instruction from the
4134        // branch's history in `crate::graph`, with no task statement at all -
4135        // this boundary must leave it alone.
4136        assert_eq!(
4137            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
4138            None
4139        );
4140    }
4141
4142    #[test]
4143    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
4144        assert_eq!(
4145            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
4146            Starter::Review("magi/eba2/A".to_owned())
4147        );
4148    }
4149
4150    #[test]
4151    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
4152        assert_eq!(
4153            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
4154            Starter::Start,
4155            "a vanished review branch must not fall back to resuming the old run either"
4156        );
4157    }
4158
4159    #[test]
4160    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
4161        assert_eq!(
4162            choose_starter(None, false, Some("some-run")),
4163            Starter::Resume("some-run".to_owned())
4164        );
4165        assert_eq!(choose_starter(None, false, None), Starter::Start);
4166    }
4167
4168    #[test]
4169    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
4170        let mut released = task();
4171        released.start("stalled-run".to_owned());
4172        released.requeue();
4173        let unfinished = (!released.fresh_start)
4174            .then(|| Some("stalled-run".to_owned()))
4175            .flatten();
4176        assert_eq!(
4177            choose_starter(None, false, unfinished.as_deref()),
4178            Starter::Start,
4179            "release keeps run history but must not resume it"
4180        );
4181        assert_eq!(released.runs, ["stalled-run"]);
4182    }
4183
4184    #[test]
4185    fn an_ordinary_release_keeps_a_resumable_run_available() {
4186        let mut released = task();
4187        released.start("stalled-run".to_owned());
4188        released.release();
4189        let unfinished = (!released.fresh_start)
4190            .then(|| Some("stalled-run".to_owned()))
4191            .flatten();
4192        assert_eq!(
4193            choose_starter(None, false, unfinished.as_deref()),
4194            Starter::Resume("stalled-run".to_owned()),
4195            "manual release must preserve the normal resume path"
4196        );
4197    }
4198
4199    #[test]
4200    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
4201        let mut state = run_state(RunStatus::Blocked);
4202        state.config.graph.review_rounds = 3;
4203        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
4204        assert!(exhausted_review_budget(&state));
4205
4206        // One round still unused: resuming can still ask a reviewer something.
4207        state.reviews.pop();
4208        assert!(!exhausted_review_budget(&state));
4209
4210        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
4211        // count: only a `Blocked` run re-enters the review loop on resume.
4212        let mut stalled = run_state(RunStatus::Stalled);
4213        stalled.config.graph.review_rounds = 1;
4214        stalled.reviews = vec![review_round(1)];
4215        assert!(!exhausted_review_budget(&stalled));
4216    }
4217
4218    fn review_round(round: usize) -> crate::run::ReviewRound {
4219        crate::run::ReviewRound {
4220            round,
4221            head: "deadbeef".to_owned(),
4222            verified_head: None,
4223            reviews: Vec::new(),
4224            e2e: Vec::new(),
4225            verify_retried: false,
4226            e2e_deferred: false,
4227            e2e_defer_reason: None,
4228            fix: None,
4229            blocking: 0,
4230            answered: 1,
4231            expected: 1,
4232            clean: false,
4233            progressed: true,
4234            vote_split: false,
4235            reconsideration: Vec::new(),
4236            verdict: None,
4237        }
4238    }
4239
4240    #[test]
4241    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
4242        // Mirrors the failure this exists to close: a task's last run ended
4243        // `Blocked` with the review budget spent, `crate::conduct` chose
4244        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
4245        // evidence), and without this check `attempt` would go on treating
4246        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
4247        // review loop iterates zero times over an already-spent budget, so
4248        // the resumed run settles right back to `Blocked` having asked nobody
4249        // anything, and `Requeue`'s promised fresh competition never happens.
4250        let mut exhausted = RunState::new(
4251            PathBuf::from("/repo"),
4252            "main".to_owned(),
4253            "abc1234def".to_owned(),
4254            "add retries".to_owned(),
4255            Config::default(),
4256        );
4257        exhausted.status = RunStatus::Blocked;
4258        exhausted.config.graph.review_rounds = 1;
4259        exhausted.reviews = vec![review_round(1)];
4260
4261        assert_eq!(
4262            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
4263            None,
4264            "an exhausted `Blocked` run must not be offered as resumable"
4265        );
4266
4267        // A `Blocked` run with rounds still unused is genuinely worth
4268        // resuming, and must still be found.
4269        let mut has_budget_left = RunState::new(
4270            PathBuf::from("/repo"),
4271            "main".to_owned(),
4272            "abc1234def".to_owned(),
4273            "add retries".to_owned(),
4274            Config::default(),
4275        );
4276        has_budget_left.status = RunStatus::Blocked;
4277        has_budget_left.config.graph.review_rounds = 3;
4278        has_budget_left.reviews = vec![review_round(1)];
4279
4280        assert_eq!(
4281            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
4282                Ok(has_budget_left.clone())
4283            }),
4284            Some(has_budget_left.id.clone())
4285        );
4286    }
4287
4288    #[test]
4289    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
4290        // A task whose history holds an *older* run that still looks
4291        // resumable (say, a competition `Runner::review` was started
4292        // alongside after that older run went `Stalled`) and a *newest* run
4293        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
4294        // on this task must mean a fresh competition — falling back to the
4295        // stale, superseded `Stalled` run instead would resurrect history
4296        // nothing asked to revisit and silently defeat the requeue.
4297        let mut older_stalled = RunState::new(
4298            PathBuf::from("/repo"),
4299            "main".to_owned(),
4300            "abc1234def".to_owned(),
4301            "add retries".to_owned(),
4302            Config::default(),
4303        );
4304        older_stalled.status = RunStatus::Stalled;
4305
4306        let mut newest_exhausted = RunState::new(
4307            PathBuf::from("/repo"),
4308            "main".to_owned(),
4309            "abc1234def".to_owned(),
4310            "add retries".to_owned(),
4311            Config::default(),
4312        );
4313        newest_exhausted.status = RunStatus::Blocked;
4314        newest_exhausted.config.graph.review_rounds = 1;
4315        newest_exhausted.reviews = vec![review_round(1)];
4316
4317        assert_eq!(
4318            unfinished_run_with(
4319                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
4320                "t",
4321                |_| Ok(newest_exhausted.clone())
4322            ),
4323            None,
4324            "the newest run is exhausted, so nothing here is worth resuming - \
4325             least of all the older, already-superseded run"
4326        );
4327    }
4328
4329    #[test]
4330    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
4331        assert_eq!(
4332            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
4333                Err(anyhow::anyhow!("fixture is absent"))
4334            }),
4335            None
4336        );
4337    }
4338}