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::notices::{self, Link, Notice};
67use crate::queue::{Queue, Task, TaskStatus};
68use crate::run::{Liveness, QuotaLoss, RunState, RunStatus};
69use crate::triage;
70
71/// On-disk format for [`Status`]. Bumped when a field's meaning changes.
72pub const SCHEMA: u32 = 1;
73
74/// How often the status file is refreshed. A reader treats a status file older
75/// than [`STALE_SECS`] as "no daemon", so the heartbeat has to be brisk enough
76/// that a busy daemon is never mistaken for a dead one.
77pub const HEARTBEAT: Duration = Duration::from_secs(5);
78
79/// How old a heartbeat may be before a reader calls the daemon dead. Six
80/// missed beats: long enough to survive a slow filesystem, short enough that
81/// a crashed daemon is not still reported as running a task.
82///
83/// The single threshold every reader shares — the web UI's `/api/health` and
84/// `magi doctor` both call [`Reading::running`] rather than each comparing
85/// against their own copy of this number, so a crashed daemon cannot look
86/// alive on one screen and dead on another.
87pub const STALE_SECS: i64 = 30;
88
89/// Default queue poll interval.
90pub const POLL: Duration = Duration::from_secs(5);
91
92/// How old a claim has to be before startup sweeps it. Longer than any run
93/// this graph plausibly takes, so a sweep cannot pull a task out from under a
94/// daemon that is merely slow.
95pub const STALE_CLAIM: Duration = Duration::from_secs(6 * 60 * 60);
96
97/// How long a task may sit [`TaskStatus::Running`] with no live daemon's
98/// heartbeat naming it before [`crate::conduct`] is shown it as stalled.
99///
100/// [`reclaim_orphaned_running`] settles most crashes immediately, on every
101/// poll, by attempting the task's own claim: a dead pid is proof enough for
102/// [`sweep_stale_claims`] to drop the lock the same tick, and the very next
103/// claim attempt succeeds. But a lock whose pid cannot be parsed at all — an
104/// empty or corrupt `.lock` file — falls back to [`STALE_CLAIM`]'s six-hour
105/// age instead, since there is nothing else to check (see
106/// [`sweep_stale_claims`]'s own doc). For as long as that lock survives, the
107/// claim keeps failing and `reclaim_orphaned_running` correctly leaves the
108/// task `running` — see
109/// `stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet` for
110/// exactly this ordering. `stalled_tasks` is what surfaces that task to the
111/// conductor well before the mechanical six-hour sweep would, and thirty
112/// minutes is comfortably below `STALE_CLAIM` while still being generous
113/// enough that a task merely late to publish its first [`HEARTBEAT`] is
114/// never mistaken for abandoned.
115pub const STALLED_RUNNING: Duration = Duration::from_secs(30 * 60);
116
117/// What the loop is working on, for the status file.
118#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
119#[serde(default)]
120pub struct Current {
121    /// Task id being run.
122    pub task: String,
123    /// Run id the task produced.
124    pub run: String,
125}
126
127/// The daemon's liveness, published to `<home>/daemon.json`.
128///
129/// This is the only interface between the loop and the web UI, which is why it
130/// carries `updated_at` as well as `started_at`: a reader cannot tell a
131/// running daemon from a `SIGKILL`ed one by the file's existence alone, but it
132/// can compare the heartbeat against the clock.
133#[derive(Debug, Clone, Serialize, Deserialize)]
134pub struct Status {
135    /// On-disk format version.
136    pub schema: u32,
137    /// Process id, so a human can find or kill the daemon.
138    pub pid: u32,
139    /// When this process started.
140    pub started_at: Timestamp,
141    /// Last heartbeat.
142    pub updated_at: Timestamp,
143    /// True when the queue has nothing runnable.
144    pub idle: bool,
145    /// Every task and run currently in flight. More than one entry means the
146    /// loop is driving more than one run at once — see
147    /// [`crate::config::Daemon::max_concurrent_runs`]. Empty, not absent, when
148    /// nothing is running, so a reader never has to treat "no field" and "an
149    /// empty list" as two different kinds of idle.
150    pub current: Vec<Current>,
151    /// Tasks that reached a terminal status in this process.
152    pub completed: usize,
153    /// Queue polls since start, so a wedged loop shows up as a frozen count.
154    pub polls: u64,
155    /// Effective startup capabilities of the question recovery loops.
156    #[serde(default)]
157    pub question_recovery: Option<crate::question_delivery::Recovery>,
158}
159
160impl Status {
161    /// A fresh, idle status for this process.
162    #[must_use]
163    pub fn new() -> Self {
164        let now = Timestamp::now();
165        Self {
166            schema: SCHEMA,
167            pid: std::process::id(),
168            started_at: now,
169            updated_at: now,
170            idle: true,
171            current: Vec::new(),
172            completed: 0,
173            polls: 0,
174            question_recovery: None,
175        }
176    }
177}
178
179impl Default for Status {
180    fn default() -> Self {
181        Self::new()
182    }
183}
184
185/// How the loop should behave.
186#[derive(Debug, Clone)]
187pub struct Opts {
188    /// Repository used by tasks that name none.
189    pub repo: PathBuf,
190    /// Explicit `magi.toml`, instead of the discovered layer stack.
191    pub config: Option<PathBuf>,
192    /// Queue poll interval.
193    pub poll: Duration,
194    /// Attempts a task gets before it is held for a human.
195    pub max_attempts: usize,
196    /// Drain what is runnable now, then return, instead of waiting for more.
197    pub once: bool,
198    /// Merge mode override (`none`, `local`, `pr`); `None` keeps the config's.
199    pub merge: Option<String>,
200    /// Where the janitor's [`crate::clean::fold_orphaned_worktrees`] and
201    /// [`crate::git::worktree_prune`] look for and reclaim worktrees.
202    /// `None` resolves to [`crate::run::default_worktree_root`] - the
203    /// operator's real `~/wt/<repo>` - the same way a run with no
204    /// [`crate::config::Graph::worktree_root`] resolves its own. A caller
205    /// that does not own that directory (a test, an embedding that manages
206    /// worktrees itself) must set this, or every idle tick reclaims worktrees
207    /// out from under whoever actually does.
208    pub worktrees_root: Option<PathBuf>,
209}
210
211impl Default for Opts {
212    fn default() -> Self {
213        Self {
214            repo: PathBuf::from("."),
215            config: None,
216            poll: POLL,
217            max_attempts: 2,
218            once: false,
219            merge: None,
220            worktrees_root: None,
221        }
222    }
223}
224
225/// How many runs a plain `usize` from config may drive concurrently, floored
226/// at one. A `0` in a config file would otherwise stall the loop entirely -
227/// no runnable task could ever start - which is never what an operator who
228/// wrote `0` meant.
229fn max_concurrent(n: usize) -> usize {
230    n.max(1)
231}
232
233/// Where the status file lives.
234#[must_use]
235pub fn status_path() -> PathBuf {
236    crate::run::home().join("daemon.json")
237}
238
239/// Publish the status file for this process.
240pub fn write_status(status: &Status) -> Result<()> {
241    write_status_to(&status_path(), status)
242}
243
244/// Publish a status to an explicit path.
245///
246/// Written to a sibling `.tmp` and renamed, because the web UI reads this file
247/// on every health poll and must never see a half-written one.
248pub fn write_status_to(path: &Path, status: &Status) -> Result<()> {
249    if let Some(parent) = path.parent() {
250        std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
251    }
252    let body = serde_json::to_string_pretty(status).context("serialize daemon status")?;
253    let tmp = path.with_extension("json.tmp");
254    std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
255    std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
256    Ok(())
257}
258
259/// Delete the status file. Called on the way out so a clean exit reads as
260/// "no daemon" rather than as a daemon whose heartbeat merely stopped.
261pub fn clear_status() {
262    clear_status_at(&status_path());
263}
264
265/// Delete a status file at an explicit path, so the loop's teardown and
266/// [`clear_status`] cannot drift apart: the loop is handed the path it
267/// published to, and a test can watch a temp file disappear.
268fn clear_status_at(path: &Path) {
269    let _ = std::fs::remove_file(path);
270}
271
272/// A cooperative stop, shared with whoever asked the loop to run.
273///
274/// Cloning is how the request travels: [`serve_until`] keeps one handle, the
275/// Ctrl-C listener and the web UI keep others, and every clone points at the
276/// same flag. There is no channel because there is nothing to send — the only
277/// message is "stop", it is idempotent, and a flag cannot be missed by a
278/// receiver that was not listening yet.
279///
280/// The handle also answers the question the operator's screen asks next: a
281/// stop does not take effect until the run in flight has finished, so
282/// [`Stop::finishing`] reports "asked to stop, still working" rather than
283/// leaving a caller to infer it from a heartbeat and hope.
284#[derive(Debug, Clone, Default)]
285pub struct Stop {
286    /// Set once, never cleared: a stop is not something an operator takes back
287    /// half way through, and a clearable flag would let a start racing a stop
288    /// resurrect a loop that is already unwinding.
289    stopped: Arc<AtomicBool>,
290    /// How many runs are in flight, so `finishing` can distinguish a stop
291    /// that has landed from one that is waiting on `execute`. A count, not a
292    /// flag, because more than one run can be in flight at once - see
293    /// [`crate::config::Daemon::max_concurrent_runs`] - and the last one to
294    /// finish is the one that should turn "finishing" off.
295    busy: Arc<std::sync::atomic::AtomicUsize>,
296    /// Wakes the idle wait. Without this a stop would not be seen until the
297    /// poll interval elapsed, and an operator tapping stop on a phone would
298    /// watch a button do nothing for five seconds.
299    wake: Arc<Notify>,
300    /// Handed to the run in flight, so a stop can also mean "park at the next
301    /// node boundary" instead of "finish the whole competition first".
302    pause: crate::graph::Pause,
303}
304
305impl Stop {
306    /// A stop nobody has asked for yet.
307    #[must_use]
308    pub fn new() -> Self {
309        Self::default()
310    }
311
312    /// Ask the loop to stop. Idempotent, and safe to call before the loop
313    /// starts: the flag is checked before the first poll.
314    pub fn stop(&self) {
315        self.stopped.store(true, Ordering::SeqCst);
316        // `notify_one` rather than `notify_waiters` because the loop may not be
317        // parked yet: this stores a permit, so a wait that registers a moment
318        // later returns at once instead of sleeping out the whole interval.
319        self.wake.notify_one();
320    }
321
322    /// Has a stop been asked for?
323    #[must_use]
324    pub fn stopped(&self) -> bool {
325        self.stopped.load(Ordering::SeqCst)
326    }
327
328    /// Has a stop been asked for that has not taken effect yet, because a run
329    /// is still in flight?
330    ///
331    /// This is the state a screen has to be able to show. A stop never abandons
332    /// a run — see [`serve_until`] — so between the tap and the loop's return
333    /// there is a window of tens of minutes in which "running" and "stopped"
334    /// are both misleading answers.
335    #[must_use]
336    pub fn finishing(&self) -> bool {
337        self.stopped() && self.busy_now()
338    }
339
340    /// Ask the loop to stop *and* the run in flight to park at its next node
341    /// boundary.
342    ///
343    /// The plain [`Stop::stop`] never abandons a run, which is right when the
344    /// operator only wants the queue to drain: a competition is tens of
345    /// minutes and its worktrees are paid for. But an operator who wants to
346    /// replace the binary cannot wait out a run that has an hour left, and
347    /// killing the process loses whatever the seats in flight had not written.
348    /// Parking costs at most the node in progress and leaves the run
349    /// resumable.
350    pub fn park(&self, cause: crate::run::ParkCause) {
351        self.pause.park_for(cause);
352        self.stop();
353    }
354
355    /// Has a park been asked for?
356    #[must_use]
357    pub fn parking(&self) -> bool {
358        self.pause.parked()
359    }
360
361    /// The pause handle to give a runner.
362    #[must_use]
363    pub fn pause(&self) -> crate::graph::Pause {
364        self.pause.clone()
365    }
366
367    /// Is any run in flight right now?
368    ///
369    /// `finishing` answers "a stop is waiting on a run", which is false until
370    /// someone asks to stop. An upgrade needs the plain question, because it
371    /// is about to be the one asking.
372    #[must_use]
373    pub fn busy_now(&self) -> bool {
374        self.busy.load(Ordering::SeqCst) > 0
375    }
376
377    /// Mark one more run as in flight, for [`Stop::finishing`].
378    fn enter(&self) {
379        self.busy.fetch_add(1, Ordering::SeqCst);
380    }
381
382    /// Mark one run as finished. The last one out is what makes
383    /// [`Stop::busy_now`] false again.
384    fn exit(&self) {
385        self.busy.fetch_sub(1, Ordering::SeqCst);
386    }
387
388    /// Wait out one poll interval, returning early once a stop is asked for.
389    async fn idle(&self, poll: Duration) {
390        tokio::select! {
391            () = tokio::time::sleep(poll) => {}
392            () = self.wake.notified() => {}
393        }
394    }
395}
396
397/// The daemon's published state, read permissively.
398///
399/// This mirrors [`Status`], but is a separate declaration on purpose: every
400/// field defaults, so a status file from an older or newer magi still yields
401/// a usable reading — one this build has never heard of — instead of a parse
402/// error that hides the daemon entirely.
403#[derive(Debug, Clone, Default, Deserialize)]
404#[serde(default)]
405pub struct Reading {
406    /// Format version the daemon claims.
407    pub schema: u32,
408    /// Daemon process id, for an operator who wants to stop it.
409    pub pid: Option<u32>,
410    /// When that process started.
411    pub started_at: Option<Timestamp>,
412    /// Last heartbeat. Absent means the file is unusable, hence not running.
413    pub updated_at: Option<Timestamp>,
414    /// True when the queue had nothing runnable at the last poll.
415    pub idle: bool,
416    /// What the daemon is working on. Empty means idle; more than one entry
417    /// means more than one run is in flight at once.
418    ///
419    /// `deserialize_with` rather than the plain derive: a daemon started
420    /// before this field became a list is still out there writing the old
421    /// shape — a single `{"task":...,"run":...}` object, or its absence —
422    /// on every heartbeat until it is restarted, and a live process reading
423    /// that file during the rollout must still see it as running rather than
424    /// as absent. A bare type change here would fail the whole struct's
425    /// deserialization on a type mismatch, defeating the permissiveness this
426    /// type exists for.
427    #[serde(deserialize_with = "de_current")]
428    pub current: Vec<Current>,
429    /// Tasks this daemon process has finished.
430    pub completed: u64,
431    /// Queue polls this daemon process has made.
432    pub polls: u64,
433    /// Effective startup capabilities of the question recovery loops.
434    #[serde(default)]
435    pub question_recovery: Option<crate::question_delivery::Recovery>,
436}
437
438/// Accept the old single-`Current`-or-absent shape as well as the current
439/// list, so a reader never has to know which build wrote the file.
440fn de_current<'de, D>(deserializer: D) -> std::result::Result<Vec<Current>, D::Error>
441where
442    D: serde::Deserializer<'de>,
443{
444    #[derive(Deserialize)]
445    #[serde(untagged)]
446    enum Shape {
447        Many(Vec<Current>),
448        One(Current),
449    }
450    Ok(
451        Option::<Shape>::deserialize(deserializer)?.map_or_else(Vec::new, |shape| match shape {
452            Shape::Many(v) => v,
453            Shape::One(c) => vec![c],
454        }),
455    )
456}
457
458impl Reading {
459    /// Seconds since the last heartbeat, or `None` when there has never been
460    /// one.
461    #[must_use]
462    pub fn age_secs(&self, now: Timestamp) -> Option<i64> {
463        self.updated_at
464            .map(|at| (now.as_second() - at.as_second()).max(0))
465    }
466
467    /// Whether the loop counts as running: a heartbeat no older than
468    /// [`STALE_SECS`]. The alternative is a reader that claims a task is in
469    /// progress hours after the daemon that owned it was killed.
470    #[must_use]
471    pub fn running(&self, now: Timestamp) -> bool {
472        self.age_secs(now).is_some_and(|secs| secs <= STALE_SECS)
473    }
474}
475
476/// Read `<home>/daemon.json` permissively, or `None` when there is nothing
477/// usable there.
478///
479/// Missing, half-written and unparseable all collapse to `None`, because the
480/// only question a reader asks is whether a daemon is alive, and a file it
481/// cannot read is not evidence that one is.
482#[must_use]
483pub fn read_status(home: &Path) -> Option<Reading> {
484    let body = std::fs::read_to_string(home.join("daemon.json")).ok()?;
485    serde_json::from_str(&body).ok()
486}
487
488/// Every run a live daemon is working on right now.
489///
490/// One definition of liveness, because deleting a task and deleting a run are
491/// both gated on it from both the CLI and the web UI - four callers that must
492/// never disagree about whether the same thing is in flight. A stale heartbeat
493/// reads as "no daemon": that is [`Reading::running`]'s judgement, and a task
494/// left at `running` or a run left at `implementing` by a killed daemon is a
495/// leftover record rather than work in progress. More than one entry once
496/// [`crate::config::Daemon::max_concurrent_runs`] is more than one - a caller
497/// after "the one thing in flight" wants [`is_working_on`] or
498/// [`is_working_on_task`], not this directly.
499#[must_use]
500pub fn current_work(home: &Path, now: Timestamp) -> Vec<Current> {
501    read_status(home)
502        .filter(|reading| reading.running(now))
503        .map(|reading| reading.current)
504        .unwrap_or_default()
505}
506
507/// Whether a live daemon is working on this run at this moment.
508#[must_use]
509pub fn is_working_on(home: &Path, run: &str, now: Timestamp) -> bool {
510    current_work(home, now).iter().any(|c| c.run == run)
511}
512
513/// Whether a live daemon is working on a run whose short id is this one.
514///
515/// For a worktree that has no run record to compare against at all -
516/// [`crate::clean::fold_orphaned_worktrees`]'s whole reason to exist - a full
517/// id is not available to hand to [`is_working_on`]. The short id is: a run's
518/// worktree bay is named after it (see [`crate::run::RunState::worktree_root`]),
519/// and it is exactly the gap between the daemon claiming a task and
520/// `RunState::new` saving the first `run.json` that this exists to protect -
521/// a run genuinely in flight but invisible to a scan of `runs/`.
522#[must_use]
523pub fn is_working_on_short(home: &Path, short: &str, now: Timestamp) -> bool {
524    current_work(home, now)
525        .iter()
526        .any(|c| crate::run::short_of(&c.run) == short)
527}
528
529/// Whether a live daemon is working on this task at this moment.
530#[must_use]
531pub fn is_working_on_task(home: &Path, task: &str, now: Timestamp) -> bool {
532    current_work(home, now).iter().any(|c| c.task == task)
533}
534
535/// Remove claim files whose owner is provably dead, or that have simply
536/// outlived `older_than`, and return the task ids swept.
537///
538/// A daemon killed with `SIGKILL` never runs [`crate::queue::Claim`]'s
539/// destructor, and the orphaned `.lock` file would make its task permanently
540/// unclaimable — the backlog would stop for good at exactly the task that was
541/// in flight when the machine went down.
542///
543/// The pid recorded in the lock is the authority whenever it can be read at
544/// all; age is only a fallback for when it cannot be.
545///
546/// - **A parseable pid wins outright.** [`crate::proc::pid_alive`] decides,
547///   full stop — dead sweeps the lock immediately, regardless of age; alive
548///   protects it, regardless of age. This is what lets a lock be reclaimed in
549///   seconds instead of waiting out [`STALE_CLAIM`]: a lock made 33 minutes
550///   before this daemon even started, next to a `queued` task, no longer has
551///   to sit for six hours before anything notices its owner is gone.
552/// - **A pid that cannot be parsed at all** — an empty or corrupt lock file —
553///   falls back to `older_than`, since there is nothing else to check.
554///
555/// Age must never override a *positive* liveness confirmation. `sweep`
556/// [`poll`]s concurrently with every attempt this daemon itself has spawned —
557/// see [`InFlightGuard`] — not only between them the way a single sequential
558/// loop once did, so a run that legitimately runs longer than `older_than`
559/// (a multi-round review, a long land wait carried across several resumed
560/// attempts) still has this very process's own live pid sitting in its own
561/// lock file on every later sweep. Deciding by age alone in that case would
562/// delete this daemon's own still-valid claim on its own in-flight task,
563/// which [`reclaim_orphaned_running`] would then read as abandoned and hand
564/// to a second attempt — two `Runner`s writing the same `run.json` and the
565/// same worktree at once. `pid_alive` answering "alive" for anything it
566/// cannot determine (a live process, a pid this build cannot check, one
567/// under another account) is exactly what keeps that path from ever
568/// firing on a guess.
569///
570/// [`STALE_CLAIM`] itself stays large: a helper program missing or its
571/// output unreadable must not be license to guess, and the risk of an
572/// unparseable lock outliving a genuinely dead owner is bounded by an order
573/// of magnitude above any plausible run rather than by a positive check.
574///
575/// Runs on every poll, not only at startup — a daemon up for days must keep
576/// noticing a lock some other, now-dead, daemon left behind just as readily
577/// as one it trips over on the way up.
578pub fn sweep_stale_claims(queue: &Queue, older_than: Duration) -> Vec<String> {
579    sweep_stale_claims_with(queue, older_than, crate::proc::pid_alive)
580}
581
582/// [`sweep_stale_claims`] with its process-query boundary supplied by the
583/// caller. This keeps the lock policy testable where process listing is
584/// unavailable, while production still uses the platform query above.
585fn sweep_stale_claims_with<F>(queue: &Queue, older_than: Duration, pid_alive: F) -> Vec<String>
586where
587    F: Fn(u32) -> bool,
588{
589    let this_process = std::process::id();
590    let mut swept: Vec<String> = std::fs::read_dir(queue.root())
591        .into_iter()
592        .flatten()
593        .flatten()
594        .map(|e| e.path())
595        .filter(|p| p.extension().is_some_and(|x| x == "lock"))
596        .filter(|p| {
597            match std::fs::read_to_string(p)
598                .ok()
599                .and_then(|body| body.trim().parse::<u32>().ok())
600            {
601                // This process wrote it and is asking the question right
602                // now, so it is definitionally still alive - settled without
603                // spawning a helper process at all.
604                Some(pid) if pid == this_process => false,
605                Some(pid) => !pid_alive(pid),
606                None => p
607                    .metadata()
608                    .and_then(|m| m.modified())
609                    .and_then(|t| t.elapsed().map_err(std::io::Error::other))
610                    .is_ok_and(|age| age >= older_than),
611            }
612        })
613        .filter(|p| std::fs::remove_file(p).is_ok())
614        .filter_map(|p| {
615            p.file_stem()
616                .and_then(|s| s.to_str())
617                .map(std::borrow::ToOwned::to_owned)
618        })
619        .collect();
620    swept.sort_unstable();
621    swept
622}
623
624/// Is `task` stalled: [`TaskStatus::Running`], past [`STALLED_RUNNING`], with
625/// no live daemon's heartbeat naming it? Deterministic — no model call, and
626/// the exact test [`stalled_tasks`] uses to decide what `crate::conduct` is
627/// shown.
628fn is_stalled(task: &Task, home: &Path, now: Timestamp) -> bool {
629    task.status == TaskStatus::Running
630        && (now.as_second() - task.updated_at.as_second()) >= STALLED_RUNNING.as_secs() as i64
631        && !is_working_on_task(home, &task.id, now)
632}
633
634/// Every task [`is_stalled`] right now — "止まったタスク" in
635/// `crate::conduct`'s vocabulary.
636fn stalled_tasks(queue: &Queue, home: &Path, now: Timestamp) -> Vec<Task> {
637    queue
638        .list()
639        .into_iter()
640        .filter(|t| is_stalled(t, home, now))
641        .collect()
642}
643
644/// Runnable tasks a dependency can still be set on — "runnable なタスク" in
645/// `crate::conduct`'s vocabulary. Deliberately `Queued` only, not
646/// `Failed`-and-so-also-runnable: a task that already attempted and lost
647/// belongs in [`finished_tasks`], where the question is a recovery, not a
648/// dependency.
649fn queued_tasks(queue: &Queue) -> Vec<Task> {
650    queue
651        .list()
652        .into_iter()
653        .filter(|t| t.status == TaskStatus::Queued)
654        .collect()
655}
656
657/// `Failed`/`Held` tasks nobody has decided a recovery for yet — "終わった
658/// タスク" in `crate::conduct`'s vocabulary.
659fn finished_tasks(queue: &Queue) -> Vec<Task> {
660    queue
661        .list()
662        .into_iter()
663        .filter(|t| matches!(t.status, TaskStatus::Failed | TaskStatus::Held))
664        .collect()
665}
666
667/// Deterministically resolve `Task::blocked_by`: a dependency task that
668/// reached `Done`, or a question that was answered, is removed — no model
669/// involved, on every poll. An answered question's content is copied onto
670/// the task ([`Task::record_answer`]) before its id is dropped, so it
671/// reaches the next `crate::conduct` prompt and the next run's instruction
672/// (see [`instruction_for`]) rather than only clearing the block.
673///
674/// A `blocked_by` id that names neither an existing task nor an existing
675/// question - `magi task rm` (or an operator by hand) deleted it while this
676/// task was still waiting - is caught before any of that: it can never
677/// become `Done` or `Answered`, so the ordinary loop below would otherwise
678/// leave the task `blocked` forever with nothing to notice. Such a task is
679/// quarantined to a machine hold instead ([`crate::queue::missing_blocker_hold_reason`]),
680/// which puts it in front of `crate::triage::run_once`'s own walk the next
681/// time it runs - see that module's doc for why the choice is "ask a human",
682/// never "assume the missing dependency was satisfied and unblock anyway".
683fn resolve_blockers(queue: &Queue, questions: &Questions) {
684    for listed in queue.list() {
685        if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
686            continue;
687        }
688        let Ok(_claim) = queue.claim(&listed.id) else {
689            continue;
690        };
691        let Ok(mut task) = queue.get(&listed.id) else {
692            continue;
693        };
694        if task.status != TaskStatus::Blocked {
695            continue;
696        }
697        // A dependency deleted on purpose is released, not held - and before
698        // the missing check, so a pass that races the delete (or a claim that
699        // made `Queue::remove` skip this task) settles it quietly.
700        let deleted = queue.apply_deleted_blockers(&mut task, questions);
701        if !deleted.is_empty() {
702            record(queue, &mut task);
703            for id in &deleted {
704                queue.note_dependency_deleted(&task, id);
705            }
706            if task.status != TaskStatus::Blocked {
707                continue;
708            }
709        }
710        let missing = crate::queue::missing_blockers(queue, questions, &task.blocked_by);
711        if !missing.is_empty() {
712            let language = language_of(&task, Path::new("."));
713            let mut cause = missing.clone();
714            cause.sort();
715            cause.dedup();
716            task.notice_cause(&format!("missing-blockers:{}", cause.join(",")), None, None);
717            task.hold_machine(Some(crate::queue::missing_blocker_hold_reason_in(
718                &task.blocked_by,
719                &missing,
720                &language,
721            )));
722            record(queue, &mut task);
723            continue;
724        }
725        // A conductor question nobody answered in time is retired by the
726        // waiter, and nothing else would ever move the task it blocks.
727        if let Some(q) = task.blocked_by.iter().find_map(|id| {
728            let crate::queue::Dependency::Question(full) =
729                crate::queue::dependency(queue, questions, id)
730            else {
731                return None;
732            };
733            questions.get(&full).ok().filter(|q| {
734                q.node == crate::conduct::NODE && q.status == ask::QuestionStatus::Abandoned
735            })
736        }) {
737            let language = language_of(&task, Path::new("."));
738            task.notice_cause(&format!("unanswered-question:{}", q.id), None, None);
739            task.hold_machine(Some(unanswered_question_hold_reason(&q, &language)));
740            record(queue, &mut task);
741            continue;
742        }
743        let mut changed = false;
744        for id in task.blocked_by.clone() {
745            let resolved = crate::queue::dependency(queue, questions, &id);
746            if let crate::queue::Dependency::Task(full) = &resolved {
747                if queue
748                    .get(full)
749                    .is_ok_and(|dep| dep.status == TaskStatus::Done)
750                {
751                    task.unblock(&id);
752                    changed = true;
753                }
754                continue;
755            }
756            if let crate::queue::Dependency::Question(full) = resolved
757                && let Ok(q) = questions.get(&full)
758                && q.status == ask::QuestionStatus::Answered
759            {
760                // The action sweep releases conductor blockers atomically
761                // with their selected operation. A fresh deputy lease must
762                // never leave an answered hold temporarily runnable.
763                if q.node == crate::conduct::NODE
764                    && q.chosen_action().is_some()
765                    && !task.action_applied(&q.id)
766                {
767                    continue;
768                }
769                let answer = match &q.answer {
770                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
771                    None => String::new(),
772                };
773                task.record_answer(q.summary.clone(), answer);
774                task.unblock(&id);
775                changed = true;
776            }
777        }
778        if changed {
779            record(queue, &mut task);
780        }
781    }
782}
783
784/// The `hold_reason` of a task whose conductor question went unanswered.
785fn unanswered_question_hold_reason(q: &ask::Question, language: &str) -> String {
786    if crate::lang::is_japanese(language) {
787        format!(
788            "質問 {} 「{}」 に期限内の回答がなく、取り下げられました - `magi task triage` を参照",
789            q.short(),
790            q.summary
791        )
792    } else {
793        format!(
794            "question {} \"{}\" went unanswered and was abandoned - see `magi task triage`",
795            q.short(),
796            q.summary
797        )
798    }
799}
800
801/// Where `q`'s chosen action stands for `task`. `daemon_will_act` is false
802/// for several unrelated reasons, and the waiter must not read them alike.
803#[derive(Debug, Clone, Copy, PartialEq, Eq)]
804pub(crate) enum ActionStanding {
805    /// The answer carries no action: the waiter delivers it as before.
806    NoAction,
807    /// The daemon will apply it (not applied, task idle, current attempt).
808    Pending,
809    /// Already applied (`Task::actions_applied`): the daemon has acted, so
810    /// delivering the word to the old seat would run it beside the new work.
811    Applied,
812    /// The question is about an earlier attempt than the task's latest.
813    Stale,
814    /// The task is running / blocked / done: the daemon defers for now.
815    Busy,
816}
817
818impl ActionStanding {
819    /// The daemon has acted or will act: the waiter must not deliver.
820    pub(crate) fn daemon_owns(self) -> bool {
821        matches!(self, Self::Pending | Self::Applied | Self::Stale)
822    }
823}
824
825/// Classify `q`'s chosen action against `task`. `Stale` is judged before
826/// `Busy`: a question about an earlier attempt must be stopped even while a
827/// newer competition is running.
828pub(crate) fn action_standing(task: &Task, q: &ask::Question) -> ActionStanding {
829    if q.chosen_action().is_none() {
830        ActionStanding::NoAction
831    } else if task.action_applied(&q.id) {
832        ActionStanding::Applied
833    } else if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
834        ActionStanding::Stale
835    } else if matches!(
836        task.status,
837        TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
838    ) {
839        ActionStanding::Busy
840    } else {
841        ActionStanding::Pending
842    }
843}
844
845/// What [`decide_action`] concluded about one answered question.
846#[derive(Debug, Clone, PartialEq, Eq)]
847enum ActionDecision {
848    /// Nothing to do now (no action, already applied, or the task is busy).
849    Skip,
850    /// Continue the named run instead of competing again.
851    Resume(String),
852    /// Requeue as a fresh competition.
853    Requeue,
854    /// Hold the task by explicit operator choice.
855    Hold,
856    /// Close the task as done.
857    Done,
858    /// The question is about an earlier attempt than the task's latest; it
859    /// is recorded as handled and changes nothing.
860    Stale,
861    /// The action cannot be carried out; hold the task and say why. Never
862    /// falls back to something else, because the operator chose this one.
863    Refuse(String),
864}
865
866/// Decide what the choice answered on `q` means for `task`. Pure: `load`
867/// reads a run's state, as with [`unfinished_run_with`].
868///
869/// `Resume` only fires on the task's *latest* run, and only while that run
870/// could actually make progress ([`RunStatus::resumable`], not released, review
871/// budget left); an answer naming anything else is refused rather than
872/// reinterpreted as a fresh competition.
873fn decide_action<F>(task: &Task, q: &ask::Question, p: &Phrases, load: F) -> ActionDecision
874where
875    F: FnOnce(&str) -> Result<RunState>,
876{
877    let Some(action) = q.chosen_action() else {
878        return ActionDecision::Skip;
879    };
880    if task.action_applied(&q.id)
881        || matches!(
882            task.status,
883            TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
884        )
885    {
886        return ActionDecision::Skip;
887    }
888    // A question about an earlier attempt must not act on a newer one. A
889    // conductor question is keyed by the task id, not a run, so it is exempt.
890    if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
891        return ActionDecision::Stale;
892    }
893    let repair = q.node == land::APPROVAL_NODE && q.resolution().as_deref() == Some(land::REPAIR);
894    let stopping = q.node == land::APPROVAL_NODE
895        && q.resolution()
896            .as_deref()
897            .is_some_and(crate::merge_decision::stops);
898    // Repair and stop actions are new decisions on an existing approval card. A
899    // manual hold before that answer must not discard it just because the
900    // card predates the hold. Keep the older policy for other choice actions.
901    let decision_at = if repair || stopping {
902        q.answered_at.unwrap_or(q.asked_at)
903    } else {
904        q.asked_at
905    };
906    if task.operator_decided_at.is_some_and(|at| at > decision_at) {
907        return if repair || stopping {
908            ActionDecision::Refuse(format!(
909                "{} answer {} was superseded by a later operator decision; the task stays held. Inspect `magi show {}`; if this action is still wanted, explicitly release the existing owner with `magi task release {}`",
910                if repair { "repair" } else { "stop" },
911                q.id,
912                q.run,
913                task.id
914            ))
915        } else {
916            ActionDecision::Stale
917        };
918    }
919    match action {
920        ask::ChoiceAction::Requeue => ActionDecision::Requeue,
921        ask::ChoiceAction::Hold => ActionDecision::Hold,
922        ask::ChoiceAction::Done => ActionDecision::Done,
923        ask::ChoiceAction::Resume { run } => {
924            if task.runs.last() != Some(run) {
925                return ActionDecision::Refuse((p.resume_not_latest)(
926                    q.short(),
927                    ask::short_id(run),
928                ));
929            }
930            match load(run) {
931                Ok(s) if stopping => {
932                    if s.merge_decision.as_ref().is_some_and(|d| d.closed)
933                        || !s
934                            .land_approval
935                            .as_ref()
936                            .is_some_and(|binding| binding.question == q.id)
937                    {
938                        ActionDecision::Stale
939                    } else if s.liveness(false) == Liveness::Live {
940                        ActionDecision::Skip
941                    } else if s.status == RunStatus::Landing && !s.released() {
942                        ActionDecision::Resume(run.clone())
943                    } else {
944                        ActionDecision::Refuse("Owner stop decision cannot resume its original landing execution; inspect the existing run. No replacement or merge was started.".into())
945                    }
946                }
947                Ok(s)
948                    if q.node == land::APPROVAL_NODE
949                        && q.resolution().as_deref() == Some(land::REPAIR) =>
950                {
951                    if s.merge_repairs.iter().any(|r| r.question == q.id)
952                        || s.land_approval.as_ref().is_some_and(|a| a.question != q.id)
953                    {
954                        // A live/manual driver already consumed or superseded
955                        // this answer. Do not hold its fresh approval wait.
956                        ActionDecision::Stale
957                    } else if s.liveness(false) == Liveness::Live {
958                        ActionDecision::Skip
959                    } else if s.status != RunStatus::Landing
960                        || s.released()
961                        || s.reviews.is_empty()
962                        || !implementers_match(task, &s)
963                        || !s
964                            .land_approval
965                            .as_ref()
966                            .is_some_and(|a| a.question == q.id && !a.head.is_empty())
967                    {
968                        ActionDecision::Refuse(format!(
969                            "repair question {} no longer names a supported current approval on run {}; inspect `magi show {}` and restore the existing owner's approval before retrying; do not file another task",
970                            q.id, run, run
971                        ))
972                    } else {
973                        ActionDecision::Resume(run.clone())
974                    }
975                }
976                Ok(s) if s.status.resumable() && !s.released() && !exhausted_review_budget(&s) => {
977                    ActionDecision::Resume(run.clone())
978                }
979                Ok(_) => ActionDecision::Refuse((p.resume_cannot_progress)(
980                    q.short(),
981                    ask::short_id(run),
982                )),
983                Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
984                    q.short(),
985                    ask::short_id(run),
986                    &format!("{e:#}"),
987                )),
988            }
989        }
990    }
991}
992
993/// The fixed prose the daemon writes into [`Task::last_error`] and
994/// [`Task::hold_reason`], in the language of `[graph] language`. Same shape as
995/// `triage::Wording` and `land::Words`: only English and Japanese are
996/// translated, anything else falls back to English.
997///
998/// Rendered when the reason is *generated*, so a reason keeps the language it
999/// was written in if the setting changes later. The notification frame
1000/// (`Task <id> is held:`) is not here and stays English.
1001///
1002/// Deliberately **not** translated, because other code reads them back by
1003/// string: the disk gate prefixes (`triage::is_disk_hold`), `out of attempts`
1004/// and `gate red`. IDs, node names, paths and external error text are embedded
1005/// as they are.
1006struct Phrases {
1007    /// `{}` = status label, then the detail.
1008    graph_stopped: fn(&str, &str) -> String,
1009    quorum_lost: &'static str,
1010    /// Followed by the seats' names.
1011    quota_took_out: &'static str,
1012    /// Followed by the status label.
1013    run_ended: &'static str,
1014    /// Followed by the question's short id.
1015    waiting_for_answer: &'static str,
1016    recovered_running: &'static str,
1017    no_run_to_recover: &'static str,
1018    could_not_start: &'static str,
1019    resume_not_latest: fn(&str, &str) -> String,
1020    resume_cannot_progress: fn(&str, &str) -> String,
1021    resume_unreadable: fn(&str, &str, &str) -> String,
1022    /// A takeover refusal: the operator-facing text. English is the error's own
1023    /// `Display`; a translation keeps the machine detail apart in parentheses.
1024    handover_refused: fn(&crate::handover::Refused) -> String,
1025    /// Appended to a refused handover's hold reason (leading space included).
1026    handover_hint: &'static str,
1027    /// (seats that never answered, review rounds) for the review loop's
1028    /// "refusing to call it clean" stop.
1029    reviewers_never_answered: fn(usize, usize) -> String,
1030}
1031
1032const PHRASES_EN: Phrases = Phrases {
1033    graph_stopped: |status, detail| {
1034        format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
1035    },
1036    quorum_lost: "the judging panel lost its quorum",
1037    quota_took_out: "; quota took out ",
1038    run_ended: "run ended ",
1039    waiting_for_answer: " - waiting for operator answer to question ",
1040    recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
1041    no_run_to_recover: "task was `running` with no live daemon and no readable \
1042                        run to recover; held for a human to check what happened",
1043    could_not_start: "could not start the run: ",
1044    resume_not_latest: |q, run| {
1045        format!("question {q} asked to resume run {run}, which is not this task's latest run")
1046    },
1047    resume_cannot_progress: |q, run| {
1048        format!("question {q} asked to resume run {run}, which cannot make progress")
1049    },
1050    resume_unreadable: |q, run, e| {
1051        format!("question {q} asked to resume run {run}, which could not be read: {e}")
1052    },
1053    handover_refused: |r| r.to_string(),
1054    handover_hint: " (clean up the other worktree, then release the task from the queue)",
1055    reviewers_never_answered: |missing, rounds| {
1056        format!(
1057            "{missing} reviewer seat(s) never answered after {rounds} rounds; \
1058             refusing to call it clean"
1059        )
1060    },
1061};
1062
1063const PHRASES_JA: Phrases = Phrases {
1064    graph_stopped: |status, detail| {
1065        format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
1066    },
1067    quorum_lost: "審査パネルが定足数を失いました",
1068    quota_took_out: "。クォータで脱落: ",
1069    run_ended: "run 終了: ",
1070    waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
1071    recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
1072    no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
1073                        何が起きたか人が確認するため保留にしました",
1074    could_not_start: "run を開始できませんでした: ",
1075    resume_not_latest: |q, run| {
1076        format!(
1077            "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
1078        )
1079    },
1080    resume_cannot_progress: |q, run| {
1081        format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません")
1082    },
1083    resume_unreadable: |q, run, e| {
1084        format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
1085    },
1086    handover_refused: |r| {
1087        use crate::handover::Refused;
1088        match r {
1089            Refused::Foreign { branch, path, why } => format!(
1090                "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
1091                 削除しません。不要なら `git worktree remove` でその worktree を削除して\
1092                 から、やり直してください(詳細: {why})"
1093            ),
1094            Refused::Unsafe { branch, path, why } => format!(
1095                "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
1096                 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
1097                 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
1098            ),
1099            Refused::ReleaseFailed { branch, path, run } => format!(
1100                "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
1101                 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1102                 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1103            ),
1104        }
1105    },
1106    handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1107    reviewers_never_answered: |missing, rounds| {
1108        format!(
1109            "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1110             クリーンとは認めません"
1111        )
1112    },
1113};
1114
1115fn phrases(language: &str) -> &'static Phrases {
1116    if crate::lang::is_japanese(language) {
1117        &PHRASES_JA
1118    } else {
1119        &PHRASES_EN
1120    }
1121}
1122
1123/// The language of the repository a task belongs to, read best-effort for the
1124/// paths that have no run (and so no config of their own) to ask. An unreadable
1125/// config is English, not an error: a hold reason must still get written.
1126fn language_of(task: &Task, fallback: &Path) -> String {
1127    crate::lang::of_repo(&repo_for(task, fallback))
1128}
1129
1130/// The task an answered question speaks for: the one whose runs include the
1131/// question's run, or - for a conductor question, filed under the task's own
1132/// id - the task with that id.
1133pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1134    if q.node == crate::conduct::NODE {
1135        return tasks.iter().find(|t| t.id == q.run);
1136    }
1137    tasks.iter().find(|t| t.runs.contains(&q.run))
1138}
1139
1140/// Carry out the [`ask::ChoiceAction`] attached to each answered choice, once.
1141///
1142/// Runs on every poll before the conductor looks at the queue. The task is
1143/// re-read under its claim, so a task somebody completed or held by hand in
1144/// the meantime is judged on what it is now. `Resume` releases the task and
1145/// records a pinned [`crate::queue::OperatorResume`], which `crate::conduct`
1146/// honours (no re-hold, no requeue) until the task runs and [`attempt`]'s
1147/// ordinary `unfinished_run` logic resumes that same run.
1148pub(crate) fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1149    let tasks = queue.list();
1150    for q in questions.list() {
1151        // Dismissal is committed by the question writer, never a resume.
1152        if q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1153            continue;
1154        }
1155        if q.chosen_action().is_none() {
1156            continue;
1157        }
1158        let Some(listed) = task_of_question(&tasks, &q) else {
1159            if q.node == land::APPROVAL_NODE
1160                && q.resolution().as_deref().is_some_and(|choice| {
1161                    choice == land::REPAIR || crate::merge_decision::stops(choice)
1162                })
1163            {
1164                notices::raise_in(
1165                    home,
1166                    Notice::warn(
1167                        &format!("repair-owner:{}", q.id),
1168                        format!(
1169                            "Approval action is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing task.",
1170                            q.run, q.run
1171                        ),
1172                    ),
1173                );
1174            }
1175            continue;
1176        };
1177        if listed.action_applied(&q.id) {
1178            continue;
1179        }
1180        let Ok(_claim) = queue.claim(&listed.id) else {
1181            continue;
1182        };
1183        let Ok(mut task) = queue.get(&listed.id) else {
1184            continue;
1185        };
1186        // Work only on this local copy until the action can be committed.
1187        // In particular, a fresh lease below leaves the persisted task blocked.
1188        if q.node == crate::conduct::NODE && task.status == TaskStatus::Blocked {
1189            let blockers: Vec<_> = task
1190                .blocked_by
1191                .iter()
1192                .filter(|id| {
1193                    crate::queue::dependency(queue, questions, id)
1194                        == crate::queue::Dependency::Question(q.id.clone())
1195                })
1196                .cloned()
1197                .collect();
1198            if !blockers.is_empty() {
1199                for id in blockers {
1200                    task.unblock(&id);
1201                }
1202                let answer = match &q.answer {
1203                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
1204                    None => String::new(),
1205                };
1206                task.record_answer(q.summary.clone(), answer);
1207            }
1208        }
1209        let language = language_of(&task, Path::new("."));
1210        let decision = decide_action(&task, &q, phrases(&language), |id| {
1211            RunState::load_under(id, home)
1212        });
1213        let ran = matches!(
1214            decision,
1215            ActionDecision::Resume(_)
1216                | ActionDecision::Requeue
1217                | ActionDecision::Hold
1218                | ActionDecision::Done
1219        );
1220        if ran && asker_may_still_read(questions, &q, home) {
1221            // The asking process or its seat can still take the word; act
1222            // once it has gone quiet. Bound on the remaining window: the
1223            // check is not atomic with the write below, so an asker that
1224            // takes the word in between (at most one poll, never more than
1225            // `ask::LEASE_TTL`) only prints it - it never touches the task,
1226            // and `Task::actions_applied` under the claim keeps the action to
1227            // one application. The waiter does not deliver an answer that
1228            // carries an action (`waiter::decide_owned`), so it cannot race.
1229            continue;
1230        }
1231        let done = matches!(decision, ActionDecision::Done);
1232        match decision {
1233            ActionDecision::Skip => continue,
1234            ActionDecision::Resume(run) => {
1235                task.release_operator("choice", Some(&q.id));
1236                task.resume_override = Some(crate::queue::OperatorResume {
1237                    question_id: q.id.clone(),
1238                    at: Timestamp::now(),
1239                    conductor_rehold: None,
1240                    forced: true,
1241                    pinned_run: Some(run),
1242                });
1243            }
1244            ActionDecision::Stale => {}
1245            ActionDecision::Requeue => {
1246                task.release_operator("choice-requeue", Some(&q.id));
1247                task.requeue();
1248            }
1249            ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1250            ActionDecision::Done => task.succeed(),
1251            ActionDecision::Refuse(why) => {
1252                if task.operator_held() {
1253                    // A rejected answer does not release the operator's hold
1254                    // or reclassify it as recoverable by the conductor.
1255                    task.hold_reason = Some(match task.hold_reason.take() {
1256                        Some(reason) => format!("{reason}\n\n{why}"),
1257                        None => why,
1258                    });
1259                } else {
1260                    task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1261                    task.hold_machine(Some(why));
1262                }
1263                notices::raise(
1264                    Notice::warn(
1265                        &format!("action:{}", q.id),
1266                        "An answer asked the daemon to resume a run that cannot be resumed; the task stays held.",
1267                    )
1268                    .link(Link::Task {
1269                        id: task.id.clone(),
1270                    }),
1271                );
1272            }
1273        }
1274        task.mark_action_applied(&q.id);
1275        // The applied id travels with the transition, so a failed save loses
1276        // neither and the answer is acted on at the next poll.
1277        record(queue, &mut task);
1278        if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1279            supersede_prior_runs(&task, home);
1280        }
1281        // Delivery is only a note of who has read the answer; the task's own
1282        // mark above is the authority. Best effort.
1283        let _ = questions.update(&q.id, |r| {
1284            r.answer_delivered = true;
1285            Ok(())
1286        });
1287    }
1288}
1289
1290/// Whether something may still read the answer to `q`: a fresh lease, or the
1291/// asking seat still listed as active in its run (its CLI can outlive the
1292/// `magi ask` that was killed).
1293fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1294    let now = Timestamp::now();
1295    if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1296        return true;
1297    }
1298    q.node != crate::conduct::NODE
1299        && RunState::load_under(&q.run, home).is_ok_and(|s| {
1300            s.seats_active()
1301                .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1302        })
1303}
1304
1305/// Retire an unanswered conductor question after its task no longer refers to
1306/// it. Conductor questions use the task id in `Question::run`, so run-based
1307/// cleanup cannot observe a manual release or completion.
1308///
1309/// Restricted to `Question::node == crate::conduct::NODE`: an ordinary run's
1310/// own question also carries a `run`, and a run id that happens to collide
1311/// with some task's id is not this loop's business — only a conductor
1312/// question actually uses the task id that way. One `Questions::list()` scan
1313/// is taken up front and matched against the in-memory task set, rather than
1314/// calling `Questions::open_for` (a full disk scan on its own) once per task.
1315fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1316    let tasks = queue.list();
1317    let by_id: std::collections::BTreeMap<&str, &Task> =
1318        tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1319    let referenced: Vec<&str> = tasks
1320        .iter()
1321        .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1322        .collect();
1323
1324    for mut question in questions.list() {
1325        if !question.status.open() || question.node != crate::conduct::NODE {
1326            continue;
1327        }
1328        // Keep questions a task still names, including when the reference
1329        // moved to a dependent task.
1330        // Preserve even ambiguous references: retiring a possibly referenced
1331        // question is unsafe until the operator disambiguates it.
1332        if referenced
1333            .iter()
1334            .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1335        {
1336            continue;
1337        }
1338        let Some(task) = by_id.get(question.run.as_str()) else {
1339            continue;
1340        };
1341        question.abandon(format!(
1342            "task {} no longer waits for this answer",
1343            task.short()
1344        ));
1345        if let Err(e) = questions.put(&mut question) {
1346            tracing::warn!(
1347                "could not retire question {} for task {}: {e:#}",
1348                question.short(),
1349                task.short()
1350            );
1351        }
1352    }
1353}
1354
1355/// What a finished run tells the queue about the task it came from.
1356///
1357/// A struct rather than a fourth and fifth boolean argument: the two flags
1358/// answer different questions about the same run, and a call site passing
1359/// `(…, true, false)` is one transposition away from refunding attempts
1360/// forever.
1361#[derive(Debug, Clone, Copy)]
1362pub struct Verdict {
1363    /// Where the graph stopped.
1364    pub status: RunStatus,
1365    /// The run opened a pull request.
1366    pub left_pr: bool,
1367    /// At least one seat was lost to a rate limit.
1368    pub quota_hit: bool,
1369    /// The run parked at a node boundary because it was asked to.
1370    pub parked: bool,
1371    /// The run never produced a single candidate a judge could look at.
1372    ///
1373    /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
1374    /// still have another candidate worth judging, in which case the loss was
1375    /// not the reason nothing came of the run. This is `true` only when the
1376    /// implement wave ended with nothing viable at all.
1377    pub no_viable_candidates: bool,
1378}
1379
1380/// Record a finished run against the task it came from.
1381///
1382/// Kept pure and separate from the loop because this mapping *is* the retry
1383/// policy, and a policy that can only be exercised by spawning a graph is a
1384/// policy nobody checks. The table:
1385///
1386/// | run status                           | task becomes        | attempt spent |
1387/// |---------------------------------------|---------------------|---------------|
1388/// | parked at a boundary                  | `Parked` (requeued) | **no**        |
1389/// | `Merged`, `Ready`                      | `Done`               | yes          |
1390/// | `AlreadyInBase`                        | `Done`, with a note  | **no**        |
1391/// | `Stalled`, quota hit                   | `Failed` (requeued) | **no**        |
1392/// | `Failed`, quota hit, no viable cand.   | `Failed` (requeued) | **no**        |
1393/// | `Stalled`, no quota                    | `Failed`, or `Held`  | yes          |
1394/// | `Blocked` with a PR                    | `Held`               | yes          |
1395/// | `Blocked`, `Failed` otherwise          | `Failed`, or `Held`  | yes          |
1396/// | `VerifiedNoop`                          | `Held`               | yes          |
1397/// | anything non-terminal                  | `Failed`, or `Held`  | yes          |
1398///
1399/// The `VerifiedNoop` row is independent of the `Failed`-quota row above it,
1400/// deliberately: every candidate agreeing there is nothing to write is not a
1401/// machine fact about a rate limit, it is an unverified claim about the
1402/// *task* that a human still has to check — see [`RunStatus::VerifiedNoop`]'s
1403/// own doc and [`Task::handed_off`]. `Held` rather than `Done` on purpose: the
1404/// claim could be wrong (a misread instruction, a stale check), and closing
1405/// the task automatically on an implementer's say-so would be the exact
1406/// failure mode task 391f's own audit was raised to avoid. `attempt spent` is
1407/// `yes` here for the same reason it is on the `Blocked`-with-a-PR row just
1408/// above, which settles through the same [`Task::handed_off`]: `Held` is not
1409/// `Failed`-and-requeued, so nothing retries this task on the same unverified
1410/// claim regardless of whether the one already-spent attempt is refunded, and
1411/// [`Task::release`] resets the count to zero anyway the moment a human looks
1412/// at the evidence and lets it run again.
1413///
1414/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
1415/// twice, together. A quorum lost to rate limits is a property of the machine
1416/// and not of the task, so the attempt is refunded and a reset quota picks
1417/// the work up where it stopped — and that is just as true when every
1418/// implement seat lost the same race and `after_implement` bails with nothing
1419/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
1420/// machine fact. The `no_viable_candidates` guard is what keeps that row
1421/// narrow: a `Failed` run that produced a real candidate which then lost for
1422/// some other reason still spends the attempt, exactly like the quorum lost
1423/// to judges that answered with the wrong shape is ordinary flakiness, and
1424/// refunding *that* takes the bound off the retry loop entirely: run e633
1425/// stalled with `quota: []` after two judges wrote unusable JSON, was
1426/// refunded, and the next attempt paid for a fresh hour-long implement wave
1427/// before it could fail the same way. `max_attempts` exists precisely so
1428/// that cannot repeat forever.
1429///
1430/// A non-terminal status means `execute` returned while the graph was still
1431/// mid-flight, which is a bug rather than a verdict; it is treated as a
1432/// failure so that a task cannot loop on it either.
1433///
1434/// `left_pr` splits the `Blocked` row, and it is the difference between a run
1435/// that failed and a run that finished into a gate. See [`Task::handed_off`].
1436pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1437    settle_in(task, verdict, detail, max_attempts, &PHRASES_EN)
1438}
1439
1440/// [`settle`], with the daemon's own fixed prose in `p`'s language.
1441fn settle_in(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize, p: &Phrases) {
1442    // A parked run is the operator's own doing, and its work is intact on
1443    // disk. The task goes back in line with its attempt refunded so the next
1444    // loop resumes the same run - which `one_task` prefers over competing
1445    // again - and so that swapping the binary a few times cannot exhaust a
1446    // budget meant for agents that actually misbehaved.
1447    if verdict.parked {
1448        task.park(detail);
1449        return;
1450    }
1451    match verdict.status {
1452        RunStatus::Merged | RunStatus::Ready => task.succeed(),
1453        RunStatus::AlreadyInBase => task.already_landed(detail),
1454        RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1455        RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1456            task.stall(detail)
1457        }
1458        RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1459        RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1460        RunStatus::Blocked => task.fail(detail, max_attempts),
1461        RunStatus::VerifiedNoop => task.handed_off(detail),
1462        other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1463    }
1464}
1465
1466/// Rewrite this task's now-moot earlier attempts — [`Task::superseded_attempts`]
1467/// — from `Blocked`/`Stalled` to [`RunStatus::Superseded`], once the task
1468/// itself has actually finished *and* its own last attempt is provably why:
1469/// this loads that run and requires `Merged`/`Ready` before touching
1470/// anything earlier in `runs`, since `Task::succeed` can also be called
1471/// directly on a task whose last attempt never landed at all.
1472///
1473/// Called right after whatever call set `task.status` to
1474/// [`TaskStatus::Done`] — this module's own `settle`'s callers below and
1475/// `reclaim`'s, but also every other place a task can be closed by hand
1476/// without the loop ever settling it itself: `magi task done`
1477/// (`main::TaskCmd::Done`) and `POST /api/queue/{id}/done`
1478/// (`web::queue_done`). Closing a task by hand — after confirming a manual
1479/// GitHub merge, say, exactly the workflow this repository's own
1480/// "Landing a run's winner by hand" documents — is just as much "this task's
1481/// story is over" as a daemon-driven `Merged`/`Ready` is, and skipping it
1482/// there would leave every earlier attempt stuck at `Blocked`/`Stalled`
1483/// forever, which is the exact backlog this status exists to clear. `pub`
1484/// for those two out-of-module callers; everything else about this stays
1485/// internal bookkeeping.
1486///
1487/// A run something is still actually driving is left alone: a
1488/// task cannot be `Done` while one of its *own* attempts is still in flight,
1489/// so a live one at this point can only be an unrelated process — a manual
1490/// `--resume` of this old, now-moot run — and rewriting under it would just
1491/// be undone (back to `Blocked`/`Stalled`, or worse) the next time that
1492/// process itself saves. This is the same `daemon_claims` + [`RunState::liveness`]
1493/// pair `run_report`/`run_detail` use for the same question elsewhere:
1494/// `is_working_on` alone only ever proves a *daemon* claim, not a `magi run
1495/// --resume` invoked by hand outside it, which `liveness` also checks via
1496/// the run's own recorded `driver_pid`. Anything not `Blocked` or `Stalled`
1497/// (already terminal in some other way, or itself mid-run) is left untouched
1498/// too.
1499///
1500/// Best-effort, like the rest of this module's bookkeeping: a load or save
1501/// failure here is a `tracing::warn`, not a failed settle, and the next time
1502/// this same task's completion is recorded — or a daemon restart replays
1503/// `reclaim_orphaned_running` — is another chance to catch up. There is no
1504/// separate reconciliation pass; if that gap ever matters in practice, one
1505/// can be added then.
1506///
1507/// `home` is a parameter, not the process-global [`crate::run::home`], for
1508/// the same reason [`RunState::save_under`] takes one: `web::queue_done`
1509/// calls this with `ui.home`, which is `crate::run::home()` in a real
1510/// process but a fixture's own directory under test — falling through to
1511/// the global there would read and write through whichever home some other
1512/// test in the same binary happened to pin into that `OnceLock` first, not
1513/// the run this call actually means.
1514pub fn supersede_prior_runs(task: &Task, home: &Path) {
1515    let now = Timestamp::now();
1516    // `Task::superseded_attempts` cannot tell a loop-driven `Done` (always
1517    // right behind a `Merged`/`Ready` verdict) from one set directly by
1518    // `magi task done`/its web equivalent/the conductor on a task whose last
1519    // recorded attempt never actually landed - that requires reading the
1520    // run itself, which is exactly what this does before trusting anything
1521    // in `runs` is safe to relabel.
1522    let last_run_succeeded = task
1523        .runs
1524        .last()
1525        .and_then(|id| RunState::load_under(id, home).ok())
1526        .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
1527    for id in task.superseded_attempts(last_run_succeeded) {
1528        let mut state = match RunState::load_under(id, home) {
1529            Ok(s) => s,
1530            Err(e) => {
1531                tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
1532                continue;
1533            }
1534        };
1535        if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
1536            continue;
1537        }
1538        let daemon_claims = is_working_on(home, id, now);
1539        if state.liveness(daemon_claims) == Liveness::Live {
1540            continue;
1541        }
1542        state.status = RunStatus::Superseded;
1543        if let Err(e) = state.save_under(home) {
1544            tracing::warn!("could not mark run {id} superseded: {e:#}");
1545        }
1546    }
1547}
1548
1549/// Catch up every `Done` task [`supersede_prior_runs`] could not fully
1550/// finish the moment it was called, because one of its earlier attempts was
1551/// still live then - a `magi run --resume` invoked by hand on an old run,
1552/// most likely.
1553///
1554/// That skip is correct at the time (rewriting under a run something is
1555/// still actively saving would just be undone), but a task only ever
1556/// reaches `Done` once, so without this nothing would ever look at it
1557/// again: if that manual process later ends anywhere other than
1558/// `Merged`/`Ready` - abandoned, or landed as another `Blocked` - the
1559/// skipped attempt would sit at `Blocked`/`Stalled` forever, exactly the
1560/// backlog this status exists to clear. Called on the same idle-only
1561/// cadence as [`janitor`], next to it rather than folded into it: this
1562/// walks `queue` and `janitor` never otherwise needs one.
1563///
1564/// Simply re-running [`supersede_prior_runs`] over every `Done` task with
1565/// more than one attempt, every pass: each call is a handful of local file
1566/// reads bounded by that task's own attempt count, the same order of cost
1567/// [`clean::fold_due`] already pays scanning every run on disk on the same
1568/// cadence, and a task already fully resolved costs one failed liveness
1569/// check turned no-op the moment its lingering attempt is no longer live.
1570fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
1571    for task in queue.list() {
1572        if task.status != TaskStatus::Done || task.runs.len() < 2 {
1573            continue;
1574        }
1575        supersede_prior_runs(&task, home);
1576    }
1577}
1578
1579/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
1580/// task ends up held.
1581///
1582/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
1583/// dead daemon never got back to) share this, so the two cannot drift into
1584/// disagreeing about which held tasks get a diagnostic.
1585fn settle_and_diagnose(
1586    task: &mut Task,
1587    verdict: Verdict,
1588    detail: &str,
1589    max_attempts: usize,
1590    state: &RunState,
1591) {
1592    let p = phrases(&state.config.graph.language);
1593    // Shared by normal completion and crash recovery, under the task claim.
1594    // No new attempt can own the task until the old driver has exited.
1595    if let Some(d) = &state.merge_decision {
1596        use crate::merge_decision as md;
1597        if task.runs.last().is_some_and(|id| id != &state.id) {
1598            return;
1599        }
1600        if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
1601            task.succeed();
1602        } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
1603            if state.liveness(false) != Liveness::Dead {
1604                task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
1605                return;
1606            }
1607            let replacement = md::Replacement {
1608                question: d.question.clone(),
1609                run: state.id.clone(),
1610                pr: d.target.pr.clone(),
1611                agent: agent.to_owned(),
1612                context: format!(
1613                    "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
1614                    d.target.pr,
1615                    state.id,
1616                    serde_json::to_string(&state.reviews).unwrap_or_default()
1617                ),
1618            };
1619            task.requeue();
1620            task.pr_recovery = None;
1621            task.review_of = None;
1622            task.replacement = Some(replacement);
1623        } else {
1624            task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
1625                format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
1626            } else { format!("PR closure was not confirmed. Task held; inspect the existing run before starting replacement work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str())) }));
1627        }
1628        task.mark_action_applied(&d.question);
1629        if let Some(pass) = state.passes.last() {
1630            task.record_pass(&state.id, pass.index, task.attempts, None);
1631        }
1632        return;
1633    }
1634    if let Some(replacement) = &task.replacement
1635        && !state.parked
1636        && state.resource_block.is_none()
1637        && (state.viable().is_empty()
1638            || (state.status == RunStatus::Blocked && state.tally.is_none()))
1639    {
1640        task.hold_manual(Some(format!("Selected implementer `{}` was unavailable, failed or hit quota before producing a viable implementation. No other implementer was dispatched. Inspect the run, restore availability, then explicitly release this task.", replacement.agent)));
1641        return;
1642    }
1643    let attempts_before = task.attempts;
1644    // A run that stopped because a shared resource stayed busy was never a
1645    // failure of the task or of any agent: nothing was asked. The attempt is
1646    // refunded and the task is held by the machine, under a reason `triage`
1647    // can re-check, so the same run resumes with the same agents once the
1648    // resource is free. A park request still wins (it is the operator's).
1649    if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
1650        task.notice_cause(
1651            &format!("resource:{}:{}", block.kind, block.node),
1652            None,
1653            None,
1654        );
1655        task.last_error = Some(detail.to_owned());
1656        task.diagnostic = None;
1657        task.attempts = task.attempts.saturating_sub(1);
1658        task.hold_machine(Some(format!(
1659            "{}{} stayed busy past the resource-wait limit before `{}` could start; \
1660             no agent was asked and no attempt was spent",
1661            crate::cache::RESOURCE_HOLD,
1662            block.kind,
1663            block.node
1664        )));
1665        if let Some(pass) = state.passes.last() {
1666            task.record_pass(&state.id, pass.index, attempts_before, None);
1667        }
1668        return;
1669    }
1670    let unresolved = task.hold_notice_cause.clone();
1671    settle_in(task, verdict, detail, max_attempts, p);
1672    if state.prep_failure.is_some() {
1673        // Minting a run whose candidates could not be prepared is not work
1674        // on a newly approved attempt. Keep the unresolved outcome anchor.
1675        task.hold_notice_cause = unresolved;
1676        task.startup_notice_cause("startup-candidates");
1677    }
1678    // Written here, where the refund (or not) is decided, so the history is a
1679    // fact and not a later guess from the run's status.
1680    if let Some(pass) = state.passes.last() {
1681        let parked = match &pass.end {
1682            Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
1683            _ => None,
1684        };
1685        task.record_pass(&state.id, pass.index, attempts_before, parked);
1686    }
1687    if task.status == TaskStatus::Held {
1688        if state.prep_failure.is_none() {
1689            task.notice_cause(
1690                label(verdict.status),
1691                Some(&state.id),
1692                state.passes.last().map(|p| p.index),
1693            );
1694        }
1695        task.diagnostic = diagnostic(state);
1696        note_open_question(task, &state.id, p);
1697    }
1698}
1699
1700/// If `task` is held with a `magi ask` question still open on `run`, name the
1701/// question in [`Task::hold_reason`] rather than leaving the hold reading
1702/// only [`describe`]'s run summary.
1703///
1704/// This is the shape task 20260928-191407-05fd left underspecified: an
1705/// implementer settled a verified no-op and filed a question for the
1706/// operator, and the hold that followed said nothing about the question
1707/// waiting on them. Appended, not substituted - [`crate::triage`] parses the
1708/// existing text ([`is_disk_hold`](crate::triage), the answered-question
1709/// marker) and must keep seeing it unchanged.
1710///
1711/// Best-effort: an unreadable question store must not stop a run from
1712/// settling, so this is a no-op rather than a propagated error when
1713/// [`crate::run::try_home`] has nothing to offer or the store is empty.
1714fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
1715    let Some(home) = crate::run::try_home() else {
1716        return;
1717    };
1718    let open = Questions::at(home.join("questions")).open_for(run);
1719    let Some(q) = open.first() else {
1720        return;
1721    };
1722    let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
1723    decisions.sort_unstable();
1724    task.notice_cause(
1725        &format!("questions:{}", decisions.join(",")),
1726        Some(run),
1727        None,
1728    );
1729    let base = task.hold_reason.clone().unwrap_or_default();
1730    task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
1731}
1732
1733/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
1734/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
1735/// by some other means entirely, like a manual `magi run` resume that
1736/// finishes the graph outside the queue's bookkeeping.
1737///
1738/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
1739/// `settle` is separate from `attempt`: a task recovered this way must land
1740/// exactly where a live daemon would have put it — the same policy table,
1741/// not a second one that quietly drifts from it — and that is only checkable
1742/// without spawning a real run.
1743fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
1744    match last_run {
1745        Some(state) => {
1746            let verdict = Verdict {
1747                status: state.status,
1748                left_pr: state.pr.is_some(),
1749                quota_hit: !state.quota.is_empty(),
1750                parked: state.parked,
1751                no_viable_candidates: state.viable().is_empty(),
1752            };
1753            let detail = format!(
1754                "{}{}",
1755                phrases(&state.config.graph.language).recovered_running,
1756                describe(&state)
1757            );
1758            settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
1759        }
1760        None => {
1761            // No run, so no config of its own: `language` is the task's
1762            // repository's setting, read by the caller.
1763            let why = phrases(language).no_run_to_recover;
1764            task.last_error = Some(why.to_owned());
1765            // The phone shows `hold_reason`, so a task held by the machine
1766            // says why there too and not only in `last_error`.
1767            task.notice_cause("missing-run", None, None);
1768            task.hold_machine(Some(why.to_owned()));
1769        }
1770    }
1771}
1772
1773/// Find every task left at `running` that no live process is actually
1774/// driving, and settle each one against whatever its last run became.
1775///
1776/// # Why a claim is proof, not a guess
1777///
1778/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
1779/// `running`, and the guard is held for the task's whole time in that status:
1780/// `attempt` does not return, and the loop does not move past the scope
1781/// holding the claim, until the run has settled. So a `running` task whose
1782/// lock is gone cannot have a live owner — this process or any other —
1783/// without needing a staleness threshold or a pid check the way
1784/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
1785/// task that never got as far as `running` at all. Taking the claim here is
1786/// the whole test: it either fails, because something really does hold it
1787/// and the task is left alone, or it succeeds, which is the proof — and it is
1788/// kept for the rest of the decision so nothing else can start a competing
1789/// run while this one is being written.
1790///
1791/// Called on every poll, not only at startup, for the reason
1792/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
1793/// keep noticing this, not only on the one morning it happened to restart.
1794fn reclaim_orphaned_running(queue: &Queue, max_attempts: usize) -> Vec<String> {
1795    let mut reclaimed = Vec::new();
1796    for listed in queue.list() {
1797        if listed.status != TaskStatus::Running {
1798            continue;
1799        }
1800        let Ok(_claim) = queue.claim(&listed.id) else {
1801            continue;
1802        };
1803        // Re-read under the claim: a release or an edit landed by a human
1804        // between the listing above and the claim just taken must not be
1805        // clobbered by a decision based on the stale copy.
1806        let Ok(mut task) = queue.get(&listed.id) else {
1807            continue;
1808        };
1809        if task.status != TaskStatus::Running {
1810            continue;
1811        }
1812        let last_run = task.runs.last().and_then(|id| RunState::load(id).ok());
1813        // `execute` normally abandons a run's own open questions the moment
1814        // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
1815        // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
1816        // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
1817        // with the question still `open`, because the process died before
1818        // reaching that call. `reclaim` itself stays pure on purpose (see its
1819        // own doc), so the same cleanup runs here instead, against the run
1820        // this reclaim is already reading. `settle_run` costs nothing when
1821        // `execute` already got there first.
1822        if let Some(state) = &last_run
1823            && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
1824        {
1825            tracing::warn!("abandon questions for {}: {e:#}", state.id);
1826        }
1827        let language = if last_run.is_none() {
1828            language_of(&task, Path::new("."))
1829        } else {
1830            String::new()
1831        };
1832        reclaim(&mut task, last_run, max_attempts, &language);
1833        if task.status == TaskStatus::Done {
1834            supersede_prior_runs(&task, &crate::run::home());
1835        }
1836        record(queue, &mut task);
1837        reclaimed.push(task.id.clone());
1838    }
1839    reclaimed
1840}
1841
1842/// Find every run whose `run.json` is provably dead — every seat it still
1843/// lists as [`crate::run::RunState::active`] has overrun its own timeout, and
1844/// [`crate::run::RunState::liveness`] reads [`crate::run::Liveness::Dead`],
1845/// not merely "no daemon claims it" — and fail it, clearing the leftover
1846/// active seats so the run stops reading as `implementing` (or whichever
1847/// node) forever.
1848///
1849/// [`reclaim_orphaned_running`] settles the *task* a dead daemon left
1850/// `running`, using whatever `run.json` already says — but nothing in that
1851/// path, nor in [`reclaim`], ever writes back to the run itself (`reclaim`
1852/// stays pure on purpose, see its own doc), so a `run.json` a killed process
1853/// never got back to sits exactly where it was left: `active` full of seats
1854/// nobody will ever answer for, `status` stuck on whatever node was in
1855/// flight. `magi show` already tells an operator this in prose (`no live
1856/// daemon claims this run right now`); this is what makes that fact durable
1857/// on disk, the same way a task's own `TaskStatus::Running` does not get to
1858/// stay stuck once nothing is driving it.
1859///
1860/// Runs on every poll, not only at startup, for the reason
1861/// [`sweep_stale_claims`] and [`reclaim_orphaned_running`] already are: a
1862/// daemon up for days must keep noticing a run some other, now-dead, daemon
1863/// left behind just as readily as one it trips over on the way up.
1864///
1865/// Walks `home.join("runs")` directly and reads each `run.json` on its own,
1866/// rather than the process-global [`RunState::load`] / [`crate::run::list_ids`] —
1867/// the same reason [`crate::clean`]'s housekeeping passes take an explicit
1868/// `runs` directory instead: `home` here is a parameter precisely so a test
1869/// can point it away from the operator's real history (see [`drive`]'s own
1870/// doc), and a scan that fell through to the global home anyway would walk
1871/// whichever directory some *other* process or test pinned into that
1872/// `OnceLock` first — mutating runs this call was never handed.
1873fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
1874    reclaim_abandoned_runs_with(
1875        home,
1876        now,
1877        crate::proc::pid_status,
1878        crate::proc::process_started_at,
1879    )
1880}
1881
1882/// [`reclaim_abandoned_runs`] with its `driver_pid` liveness/identity queries
1883/// supplied by the caller — mirrors [`sweep_stale_claims_with`], which exists
1884/// for the identical reason: this sweep's real damage (wiping a run's active
1885/// seats and failing it) has to be provable against an injected answer in a
1886/// test, not just the real process table.
1887fn reclaim_abandoned_runs_with<F, G>(
1888    home: &Path,
1889    now: Timestamp,
1890    query: F,
1891    identity: G,
1892) -> Vec<String>
1893where
1894    F: Fn(u32) -> Option<bool>,
1895    G: Fn(u32) -> Option<String>,
1896{
1897    let mut abandoned = Vec::new();
1898    for entry in std::fs::read_dir(home.join("runs"))
1899        .into_iter()
1900        .flatten()
1901        .flatten()
1902    {
1903        let id = entry.file_name().to_string_lossy().into_owned();
1904        if !crate::run::is_run_id(&id) {
1905            continue;
1906        }
1907        // Serialize the proof and save with claims and takeover: a new
1908        // execution must not be overwritten after the liveness observation.
1909        let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
1910            continue;
1911        };
1912        // Unreadable is `clean::fold_due`'s problem, not this one's — see
1913        // that module's docs for why a run this cannot parse is left alone
1914        // rather than guessed at. A different schema number is not that: this
1915        // touches only `status` and `active`, never a field whose meaning a
1916        // schema bump changed, so an old record's values serve this exactly
1917        // as well as a current one's (see `clean::read_state`'s own doc for
1918        // the same reasoning applied to folding).
1919        let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
1920            continue;
1921        };
1922        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
1923            continue;
1924        };
1925        if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
1926            continue;
1927        }
1928        // Not `!is_working_on(..)` alone: that is only "no *daemon* claims
1929        // it", which is also the normal, healthy shape of a manual `magi
1930        // run` / `magi review` sharing this same home — this scan walks
1931        // every run on disk, not only ones this daemon itself started. Such
1932        // a run's active seats can legitimately sit past their own timeout
1933        // for a little while (the CLI finishing up, its result still being
1934        // collected) without the process driving it having died. `liveness`
1935        // is what actually tells the two apart, by corroborating
1936        // `driver_pid` against the process it names — see its own doc. Only
1937        // its strongest, provable answer licenses wiping this run's active
1938        // seats and failing it out from under whatever is still running it.
1939        let daemon_claims = is_working_on(home, &id, now);
1940        if state.liveness_under_with(home, daemon_claims, &query, &identity)
1941            != crate::run::Liveness::Dead
1942        {
1943            continue;
1944        }
1945        state.abandon("daemon");
1946        if let Err(e) = state.save_under(home) {
1947            tracing::warn!("could not persist abandoned run {id}: {e:#}");
1948            continue;
1949        }
1950        // This run never passes through `Runner::execute` again, so its end
1951        // is announced here.
1952        if let Some(notice) = notices::run_ended(&state) {
1953            notices::raise_in(home, notice);
1954        }
1955        // The seat that asked is gone for good now, exactly like any other
1956        // door `graph::Runner::settle_questions` closes the moment `status`
1957        // lands somewhere non-resumable - see that method's own doc. Nothing
1958        // else reaches this one before the next `janitor()` startup pass
1959        // (`clean::abandon_settled_questions`), and a daemon that stays up
1960        // for days must not leave an open question badging the operator
1961        // until it happens to restart.
1962        if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
1963            tracing::warn!("abandon questions for {id}: {e:#}");
1964        }
1965        abandoned.push(id);
1966    }
1967    abandoned
1968}
1969
1970/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
1971///
1972/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
1973/// sets, so there is one loop body rather than two that drift apart the first
1974/// time the retry policy changes on only one of them.
1975pub async fn serve(opts: Opts) -> Result<()> {
1976    serve_until(opts, Stop::new()).await
1977}
1978
1979/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
1980///
1981/// Neither a signal nor a `stop` abandons a run in flight. Killing the graph
1982/// mid-node leaves worktrees, branches and agent sessions behind, and every
1983/// agent call already paid for is lost; finishing the run costs the operator a
1984/// wait and saves them a cleanup. A stop therefore only sets a flag: the
1985/// current `execute` runs to its terminal status, the task's outcome is
1986/// recorded, and only then does the loop return. That window is what
1987/// [`Stop::finishing`] is for. An operator who genuinely wants the run dead
1988/// still has a second Ctrl-C, which the runtime turns into a process kill —
1989/// and the task left `Running` then tells the next daemon, and the next human,
1990/// where to look.
1991///
1992/// While the queue is empty the stop is honoured within one wakeup rather than
1993/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
1994/// caller that taps stop does not sit through the remainder of a sleep.
1995pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
1996    let signal = {
1997        let stop = stop.clone();
1998        tokio::spawn(async move {
1999            if tokio::signal::ctrl_c().await.is_ok() {
2000                stop.stop();
2001                tracing::info!("shutdown requested; a run in flight will be finished first");
2002            }
2003        })
2004    };
2005
2006    let worktrees_root = opts
2007        .worktrees_root
2008        .clone()
2009        .unwrap_or_else(crate::run::default_worktree_root);
2010    let outcome = drive(
2011        &opts,
2012        &Queue::open(),
2013        &status_path(),
2014        &crate::run::home(),
2015        &worktrees_root,
2016        &stop,
2017    )
2018    .await;
2019
2020    signal.abort();
2021    outcome
2022}
2023
2024/// The loop proper: setup, poll, teardown, with the queue and the status file
2025/// supplied rather than discovered.
2026///
2027/// All three of `home`, `worktrees_root` and the queue/status paths are
2028/// parameters rather than resolved here, for the same reason:
2029/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
2030/// so a unit test that pinned it would fight every other test in the binary,
2031/// and a loop that resolved its own worktree bay could only be exercised
2032/// against the operator's real `~/wt/<repo>` - publishing over a live
2033/// daemon's status file, claiming tasks out of a live backlog, and, since
2034/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
2035/// whatever the operator actually has on disk.
2036async fn drive(
2037    opts: &Opts,
2038    queue: &Queue,
2039    status_file: &Path,
2040    home: &Path,
2041    worktrees_root: &Path,
2042    stop: &Stop,
2043) -> Result<()> {
2044    // The status file is a *snapshot*, not a stream of events: a reader only
2045    // ever wants the latest values, and every tick rewrites the whole file
2046    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
2047    // while an mpsc channel would force the loop to re-send unchanged fields on
2048    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
2049    // for no gain. The lock is only ever held across a field assignment, never
2050    // across an await.
2051    let recovery_cfg = prepare(&opts.repo, opts).ok();
2052    let daemon_cfg = recovery_cfg
2053        .as_ref()
2054        .map(|c| c.daemon.clone())
2055        .unwrap_or_default();
2056    let reconciled = crate::driver::reconcile(home);
2057    if !reconciled.is_empty() {
2058        tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
2059    }
2060    let mut initial_status = Status::new();
2061    initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
2062        recovery_cfg.as_ref(),
2063        daemon_cfg.max_deputies,
2064    ));
2065    let status = Arc::new(Mutex::new(initial_status));
2066    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
2067    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
2068
2069    // Read once at startup, not per task: how many runs this loop drives at
2070    // once is a property of the machine running it, not of whichever
2071    // repository a given task happens to name - see
2072    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
2073    // fact in the same sense the agent roster is.
2074    let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
2075
2076    // Something has to be waiting on every question for as long as it is open,
2077    // whether or not the agent's own `magi ask` survived. Its own task rather
2078    // than a step of the poll loop: the poll loop is busy for the whole of a
2079    // run, and an owner's reply must not queue behind one.
2080    let waiter = tokio::spawn(crate::waiter::run(
2081        crate::waiter::Waiter::new(
2082            crate::ask::Questions::at(home.join("questions")),
2083            home.to_path_buf(),
2084            recovery_cfg.clone(),
2085        ),
2086        stop.clone(),
2087    ));
2088
2089    // The follow-up seats for the conductor's questions: the conductor files a
2090    // question and moves on, and each open one gets a deputy that reads the
2091    // owner's reply. Its own task for the same reason the waiter's is.
2092    let deputies = tokio::spawn(crate::deputy::run(
2093        crate::deputy::Deputies::new(
2094            crate::ask::Questions::at(home.join("questions")),
2095            home.to_path_buf(),
2096            recovery_cfg.clone(),
2097            opts.repo.clone(),
2098            daemon_cfg.max_deputies,
2099            {
2100                let stop = stop.clone();
2101                Arc::new(move || stop.parking())
2102            },
2103        ),
2104        stop.clone(),
2105    ));
2106
2107    // Keeps every checkout's origin/main fresh; its own task so a slow remote
2108    // never holds up the poll loop.
2109    let fetcher = tokio::spawn(fetch_loop(opts.repo.clone(), opts.clone(), stop.clone()));
2110
2111    // Watches the release-bump pull requests until they land; its own task, not
2112    // tied to any run, because a pending bump outlives the run that opened it.
2113    let release_watch = tokio::spawn(crate::release_watch::run(
2114        crate::release_watch::Watcher::new(
2115            Box::new(crate::release_watch::GhForge),
2116            home.to_path_buf(),
2117        ),
2118        {
2119            let (repo, opts) = (opts.repo.clone(), opts.clone());
2120            move || release_watch_settings(&repo, &opts)
2121        },
2122        stop.clone(),
2123    ));
2124
2125    tracing::info!(
2126        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
2127        queue.root().display(),
2128        opts.poll.as_secs(),
2129        opts.max_attempts,
2130        concurrency,
2131        if daemon_cfg.pause_for_interrupts {
2132            ", interrupts enabled"
2133        } else {
2134            ""
2135        }
2136    );
2137
2138    // `--once` drains an already-idle queue without reaching the idle wait,
2139    // but must still perform the startup cleanup.
2140    janitor(&opts.repo, opts, home, worktrees_root).await;
2141    resweep_superseded_attempts(queue, home);
2142
2143    let outcome = poll(
2144        opts,
2145        queue,
2146        &status,
2147        home,
2148        worktrees_root,
2149        stop,
2150        DispatchLimits {
2151            max_concurrent: concurrency,
2152            pause_for_interrupts: daemon_cfg.pause_for_interrupts,
2153        },
2154    )
2155    .await;
2156
2157    beat.abort();
2158    waiter.abort();
2159    deputies.abort();
2160    fetcher.abort();
2161    release_watch.abort();
2162    clear_status_at(status_file);
2163    outcome
2164}
2165
2166/// The checkouts the release watcher covers and `[daemon] release_stall_minutes`,
2167/// re-read each lap. An unreadable config yields `0` minutes: the watcher idles.
2168fn release_watch_settings(repo: &Path, opts: &Opts) -> (Vec<PathBuf>, u64) {
2169    let Ok(cfg) = prepare(repo, opts) else {
2170        return (Vec::new(), 0);
2171    };
2172    let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
2173        .into_iter()
2174        .map(|r| r.path)
2175        .collect();
2176    // Repositories the daemon has worked in, wherever they live: a task may
2177    // name one outside `[repos] roots`, and its release PR must be watched too.
2178    let mut known: Vec<PathBuf> = Queue::open().list().into_iter().map(|t| t.repo).collect();
2179    let runs = crate::run::home().join("runs");
2180    for id in crate::run::list_ids_in(&runs) {
2181        let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
2182            .ok()
2183            .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
2184            .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
2185        known.extend(repo);
2186    }
2187    for k in known {
2188        let k = k.canonicalize().unwrap_or(k);
2189        if k.join(".git").exists() && !paths.contains(&k) {
2190            paths.push(k);
2191        }
2192    }
2193    let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
2194    if !paths.contains(&own) {
2195        paths.push(own);
2196    }
2197    (paths, cfg.daemon.release_stall_minutes)
2198}
2199
2200/// Per-repo bound on one `git fetch`, so a dead remote cannot stall the pass.
2201const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
2202
2203/// Run [`crate::clean::fetch_origins`] every `[repos] fetch_interval` seconds
2204/// until `stop`. The config is re-read each lap; `0` (or an unreadable config)
2205/// disables the fetch for that lap. Never fails.
2206async fn fetch_loop(repo: PathBuf, opts: Opts, stop: Stop) {
2207    while !stop.stopped() {
2208        let (interval, roots) = match prepare(&repo, &opts) {
2209            Ok(c) => (c.repos.fetch_interval, c.repos.roots),
2210            Err(_) => (0, Vec::new()),
2211        };
2212        if interval > 0 && !roots.is_empty() {
2213            let r = crate::clean::fetch_origins(&roots, FETCH_TIMEOUT, || stop.stopped()).await;
2214            tracing::debug!("fetch origins: {r:?}");
2215        }
2216        // Sleep in slices so a stop or a config change is noticed promptly.
2217        let wait = if interval > 0 { interval } else { 60 };
2218        let mut slept = 0;
2219        while slept < wait && !stop.stopped() {
2220            tokio::time::sleep(Duration::from_secs(1)).await;
2221            slept += 1;
2222        }
2223    }
2224}
2225
2226/// Refresh the status file on a fixed tick.
2227///
2228/// Separate from the loop because a run takes tens of minutes: a status file
2229/// written only between tasks would look stale for the whole of every run, and
2230/// a reader would report the daemon dead exactly while it was busiest.
2231async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
2232    loop {
2233        tokio::time::sleep(HEARTBEAT).await;
2234        let snapshot = {
2235            let mut guard = lock(&status);
2236            guard.updated_at = Timestamp::now();
2237            guard.clone()
2238        };
2239        if let Err(e) = write_status_to(&path, &snapshot) {
2240            // A failed heartbeat must not take the daemon down: the loop is the
2241            // product, the status file is only the window onto it.
2242            tracing::warn!("could not refresh the daemon status file: {e:#}");
2243        }
2244    }
2245}
2246
2247/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
2248/// if so, whether that wait is over.
2249#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2250enum LandResume {
2251    /// The task's last run is not parked on a land approval; schedule it
2252    /// like any other candidate.
2253    NotLanding,
2254    /// Parked in `land`, waiting on a question nobody has answered yet.
2255    /// Left alone: attempting it now would only re-observe the same pull
2256    /// request and park again, spending a `gh` call on a decision that has
2257    /// not changed since the last time this was checked.
2258    StillWaiting,
2259    /// Parked in `land`, and the question is settled - answered or
2260    /// abandoned. Resuming this is the one kind of candidate that must not
2261    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
2262    Ready,
2263}
2264
2265/// Classify a runnable candidate by whether it is parked on a land-merge
2266/// approval. Read-only - no claim taken, nothing written - so it is cheap
2267/// enough to call on every candidate, every poll.
2268fn land_resume_state(task: &Task) -> LandResume {
2269    let Some(run_id) = task.runs.last() else {
2270        return LandResume::NotLanding;
2271    };
2272    let Ok(state) = RunState::load(run_id) else {
2273        return LandResume::NotLanding;
2274    };
2275    if !state.parked {
2276        return LandResume::NotLanding;
2277    }
2278    if state.status == RunStatus::Landing
2279        && state.land_approval.as_ref().is_some_and(|binding| {
2280            ask::Questions::open()
2281                .get(&binding.question)
2282                .is_ok_and(|q| {
2283                    q.run == state.id
2284                        && q.resolution()
2285                            .as_deref()
2286                            .is_some_and(crate::merge_decision::stops)
2287                })
2288        })
2289    {
2290        return LandResume::Ready;
2291    }
2292    if !implementers_match(task, &state) {
2293        return LandResume::NotLanding;
2294    }
2295    // Parked in `land` on the merge approval, or at `merge` on the owner's
2296    // word about a title/body the posting gate withheld. Told apart by the
2297    // run's own record, not by a status both can share.
2298    let node = if state.status == RunStatus::Landing {
2299        land::APPROVAL_NODE
2300    } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
2301        crate::github_text::ASK_NODE
2302    } else {
2303        return LandResume::NotLanding;
2304    };
2305    let store = ask::Questions::open();
2306    let waiting = store
2307        .list()
2308        .into_iter()
2309        .filter(|q| &q.run == run_id && q.node == node)
2310        .max_by(|a, b| a.id.cmp(&b.id));
2311    let Some(mut q) = waiting else {
2312        return LandResume::Ready;
2313    };
2314    if !q.status.open() {
2315        // Repair spends agent resources and must obey concurrency and quota
2316        // waits; only a merge/hold decision may use the decision-only lane.
2317        if q.resolution().as_deref() == Some(land::REPAIR) {
2318            return if state.liveness(false) == Liveness::Live {
2319                LandResume::StillWaiting
2320            } else {
2321                LandResume::NotLanding
2322            };
2323        }
2324        return LandResume::Ready;
2325    }
2326    // `ask::ask_and_wait`'s own deadline is what used to retire a question
2327    // nobody ever answered; land's approval bypasses that wait entirely (see
2328    // `land::approval_gate`), so the same deadline has to be enforced here
2329    // instead, or `graph.answer_timeout` silently stops meaning anything for
2330    // a land approval and a run can sit `StillWaiting` forever with nobody
2331    // told to look at it.
2332    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
2333    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
2334    if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
2335        q.abandon(format!(
2336            "no answer within {}s of asking",
2337            timeout.as_secs().max(1)
2338        ));
2339        // If this can't be persisted, do not treat the wait as settled on a
2340        // guess: fall through and try again next poll.
2341        if store.put(&mut q).is_ok() {
2342            return LandResume::Ready;
2343        }
2344    }
2345    LandResume::StillWaiting
2346}
2347
2348/// How often the loop rechecks for new work while something it already
2349/// started is still running, rather than sleeping out the whole
2350/// [`Opts::poll`] interval.
2351///
2352/// Short on purpose: this is what lets a land-merge approval that comes back
2353/// while another task is mid-competition be noticed and resumed within a
2354/// fraction of a second, not within the next multi-second poll.
2355const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
2356
2357/// How often [`poll`] rechecks the shared build cache against its cap at a
2358/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
2359/// waiting for the queue to run dry.
2360///
2361/// A queue that never empties means the `janitor` call at the bottom of this
2362/// loop's fully-idle branch can go unreached for as long as the backlog
2363/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
2364/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
2365/// 81.8 GiB an idle-only check let it reach before this existed, and it is
2366/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
2367/// backlog of short tasks does not pay for that walk on every poll.
2368const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
2369
2370/// Frees one attempt's concurrency slot - `Stop`'s busy count and its entry
2371/// in `Status::current` - on drop, so both are released even if the attempt
2372/// panics rather than returning.
2373///
2374/// A `Drop` impl rather than statements written after the `.await` it
2375/// guards: a panic unwinds straight past code placed "after" a call, and
2376/// `Runner::execute`'s chain reaches deep enough into agent-output parsing
2377/// that ruling a panic out there is not a bet this loop can make. Without
2378/// this, one panicking run would leave [`Stop::busy_now`] stuck `true`
2379/// forever - the idle branch in [`poll`], and with it the janitor, would
2380/// never run again - and a ghost entry in `Status::current` naming a task
2381/// nothing is still working on.
2382struct InFlightGuard<'a> {
2383    status: &'a Arc<Mutex<Status>>,
2384    stop: &'a Stop,
2385    task_id: &'a str,
2386}
2387
2388impl Drop for InFlightGuard<'_> {
2389    fn drop(&mut self) {
2390        lock(self.status).current.retain(|c| c.task != self.task_id);
2391        self.stop.exit();
2392    }
2393}
2394
2395/// State of [`poll`]'s own interrupt-scheduling sequence - see
2396/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
2397/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
2398/// both kept free of `Task`'s non-identity fields on purpose: every decision
2399/// here turns only on task ids and which ones are in flight, so the "never
2400/// more than one run at once" and "exactly one resume" invariants can be
2401/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
2402/// queue - which is exactly the coverage this feature's first two attempts
2403/// were missing.
2404///
2405/// Deliberately in-memory only, not written to disk anywhere: a daemon
2406/// restart mid-sequence loses track of which run it had asked to park and
2407/// which task was meant to run first, and simply falls back to `Idle` -
2408/// see [`drive`]'s own setup. The parked run itself is not lost - it is
2409/// sitting in the queue exactly like any other resumable, interrupted task,
2410/// `RunStatus::resumable` and [`Task::interrupt`] both intact on disk - it
2411/// just resumes on the ordinary priority order rather than guaranteed to go
2412/// first. Giving that guarantee a crash-proof memory would mean a new queue
2413/// field and a recovery ordering to go with it, which is exactly the
2414/// complexity this feature's constraints rule out for the one property that
2415/// actually matters: at most one run, ever, at once.
2416#[derive(Debug, Clone, PartialEq, Eq)]
2417enum Interrupt {
2418    /// No interrupt sequence in progress. Ordinary dispatch applies.
2419    Idle,
2420    /// `interrupt_task` is runnable and exactly one other run is in flight;
2421    /// `parked` names that one task's id. Dispatch is withheld from
2422    /// everyone, including `interrupt_task` itself, until it has left
2423    /// flight - only then is `interrupt_task` let through.
2424    ///
2425    /// `parked` is a `Vec` rather than a bare id for symmetry with
2426    /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
2427    /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
2428    /// when exactly one run is in flight, so it is guaranteed to hold
2429    /// exactly one entry in practice - see that branch's own doc for why
2430    /// more than one is deliberately never attempted.
2431    Parking {
2432        parked: Vec<String>,
2433        interrupt_task: String,
2434    },
2435    /// `interrupt_task` is dispatched and in flight alone. Dispatch is
2436    /// withheld from everyone until it leaves flight - merged, failed, held,
2437    /// it makes no difference - at which point the sequence moves to
2438    /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
2439    /// going straight to `Idle` would hand `parked` back to ordinary
2440    /// priority-order dispatch, where a higher-priority task filed in the
2441    /// meantime could start ahead of it.
2442    Running {
2443        parked: Vec<String>,
2444        interrupt_task: String,
2445    },
2446    /// `interrupt_task` left flight; `parked` still names the one run this
2447    /// sequence owes a resume. Dispatch is withheld from everyone except
2448    /// that task - see [`interrupt_gate`] - so the resume this feature
2449    /// promises is never raced by, or run alongside, an unrelated candidate.
2450    /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
2451    /// own doc on abandonment - the moment it is no longer runnable at all.
2452    Resuming { parked: Vec<String> },
2453}
2454
2455/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
2456/// and `runnable` are read-only snapshots of this tick's reality, and the
2457/// only side effect the caller still owes the world is asking whichever
2458/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
2459/// site.
2460///
2461/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
2462/// accepted rather than a narrower type because that is what [`poll`] already
2463/// has on hand from [`runnable`], and building a second, smaller list on
2464/// every tick just to satisfy this signature would cost more than it proves.
2465///
2466/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
2467/// back to a task they are waiting on no longer being [`runnable`] - held,
2468/// blocked, deleted, or finished by some other means entirely, all of which
2469/// an operator can do to a task sitting in the queue with no claim on it at
2470/// all, at any moment, interrupt sequence or not. Without this check the
2471/// sequence would wait forever for a dispatch that can never come, and
2472/// `interrupt_gate` would withhold every other task in the queue right along
2473/// with it - a single `magi task hold` on the wrong id turning into a
2474/// daemon that never dispatches anything again.
2475fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
2476    match state {
2477        Interrupt::Idle => {
2478            // Not just "something to interrupt": exactly one thing. More
2479            // than one run in flight only happens above the default
2480            // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
2481            // one resume, never run alongside anything else" only because
2482            // it is only ever seeded with exactly one id - see
2483            // `Interrupt::Resuming`'s own doc on why releasing more than one
2484            // parked id back to ordinary dispatch cannot be made safe
2485            // against that same setting's own extra concurrency slots.
2486            // Waiting here for the herd to settle to one is the
2487            // simplification this feature's own constraints ask for rather
2488            // than a second concurrency model to reconcile with the first.
2489            if in_flight.len() != 1 {
2490                return Interrupt::Idle;
2491            }
2492            match runnable.iter().find(|t| t.interrupt) {
2493                Some(t) => Interrupt::Parking {
2494                    parked: in_flight.to_vec(),
2495                    interrupt_task: t.id.clone(),
2496                },
2497                None => Interrupt::Idle,
2498            }
2499        }
2500        Interrupt::Parking {
2501            parked,
2502            interrupt_task,
2503        } => {
2504            if in_flight.iter().any(|id| parked.contains(id)) {
2505                // Still waiting for what was in flight to actually stop.
2506                Interrupt::Parking {
2507                    parked,
2508                    interrupt_task,
2509                }
2510            } else if in_flight.contains(&interrupt_task) {
2511                Interrupt::Running {
2512                    parked,
2513                    interrupt_task,
2514                }
2515            } else if runnable.iter().any(|t| t.id == interrupt_task) {
2516                // The parked run(s) are gone, but the interrupt task has not
2517                // been dispatched yet on this tick - `interrupt_gate` is
2518                // what lets it through next.
2519                Interrupt::Parking {
2520                    parked,
2521                    interrupt_task,
2522                }
2523            } else {
2524                // The interrupt task itself is no longer runnable - see this
2525                // function's own doc on abandonment. The parked run(s) still
2526                // get their guaranteed resume; there is simply no interrupt
2527                // to run ahead of them any longer.
2528                Interrupt::Resuming { parked }
2529            }
2530        }
2531        Interrupt::Running {
2532            parked,
2533            interrupt_task,
2534        } => {
2535            if in_flight.contains(&interrupt_task) {
2536                Interrupt::Running {
2537                    parked,
2538                    interrupt_task,
2539                }
2540            } else {
2541                // The interrupt task's own run reached a terminal status,
2542                // whichever one - this is the *only* trigger that moves the
2543                // sequence on, driven straight off the same in-flight
2544                // bookkeeping `poll` already reaps every tick, not a second,
2545                // independent poll of anything.
2546                Interrupt::Resuming { parked }
2547            }
2548        }
2549        Interrupt::Resuming { parked } => {
2550            if in_flight.iter().any(|id| parked.contains(id)) {
2551                // One of the parked runs has been dispatched - the resume
2552                // this sequence owed is fulfilled. Whatever else is left in
2553                // `parked` (ordinarily nothing, at the default concurrency
2554                // of one) rejoins ordinary priority-order dispatch, same as
2555                // any other runnable task.
2556                Interrupt::Idle
2557            } else if runnable.iter().any(|t| parked.contains(&t.id)) {
2558                Interrupt::Resuming { parked }
2559            } else {
2560                // Abandonment (see this function's own doc): nothing left in
2561                // `parked` is even runnable any longer.
2562                Interrupt::Idle
2563            }
2564        }
2565    }
2566}
2567
2568/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
2569/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
2570/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
2571/// indistinguishable from any other runnable task - exactly the "off does
2572/// nothing" this feature promises.
2573fn advance_interrupt_tick(
2574    enabled: bool,
2575    state: Interrupt,
2576    in_flight: &[String],
2577    runnable: &[Task],
2578) -> Interrupt {
2579    if !enabled {
2580        return Interrupt::Idle;
2581    }
2582    advance_interrupt(state, in_flight, runnable)
2583}
2584
2585/// Which of this tick's runnable candidates the interrupt sequence actually
2586/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
2587/// each half is assertable on its own: this is the half that keeps a
2588/// competition and an interrupt from ever running at the same moment.
2589fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
2590    match state {
2591        Interrupt::Idle => candidates,
2592        Interrupt::Parking {
2593            parked,
2594            interrupt_task,
2595        } => {
2596            if in_flight.iter().any(|id| parked.contains(id)) {
2597                Vec::new()
2598            } else {
2599                candidates
2600                    .into_iter()
2601                    .filter(|t| &t.id == interrupt_task)
2602                    .collect()
2603            }
2604        }
2605        Interrupt::Running { .. } => Vec::new(),
2606        // At most one: even if `parked` names more than one id (more than
2607        // one run was in flight when the sequence began, only possible
2608        // above the default `max_concurrent_runs = 1`), only the first match
2609        // is offered. Capping this to a single candidate - not merely to
2610        // `parked`'s own ids - is what makes "exactly one resume, never two
2611        // dispatched together" true regardless of how many ordinary slots
2612        // happen to be free this tick.
2613        Interrupt::Resuming { parked } => candidates
2614            .into_iter()
2615            .find(|t| parked.contains(&t.id))
2616            .into_iter()
2617            .collect(),
2618    }
2619}
2620
2621/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
2622/// bundled into one parameter so `poll`'s own signature stays readable -
2623/// see [`drive`]'s call site for where these are actually read.
2624struct DispatchLimits {
2625    /// How many *ordinary* candidates run at once. See
2626    /// [`crate::config::Daemon::max_concurrent_runs`].
2627    max_concurrent: usize,
2628    /// See [`crate::config::Daemon::pause_for_interrupts`].
2629    pause_for_interrupts: bool,
2630}
2631
2632/// Which semaphore, if any, dispatching a candidate should draw its permit
2633/// from.
2634///
2635/// Pure and separate from [`poll`]'s loop body for the same reason
2636/// [`advance_interrupt`] is: the choice between "skip the ordinary pool
2637/// entirely", "spend the one urgent slot" and "spend an ordinary slot" is
2638/// exactly the policy this feature adds, and a policy only exercisable by
2639/// running the whole loop is a policy nobody checks.
2640#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2641enum PermitKind {
2642    /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
2643    /// Checked first - a task can be both a land resume and marked
2644    /// [`Task::urgent`], and the resume's own "must not queue behind
2645    /// anything" guarantee takes precedence.
2646    None,
2647    /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
2648    /// (never in addition to trying) the ordinary pool. This is what lets
2649    /// an urgent task dispatch while every ordinary slot is already checked
2650    /// out, and what stops a second urgent task from opening a third run: it
2651    /// waits on this same one-slot semaphore rather than falling through to
2652    /// the ordinary one.
2653    Urgent,
2654    /// The ordinary `max_concurrent_runs` pool - unaffected by either of the
2655    /// above.
2656    Ordinary,
2657}
2658
2659/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
2660/// own boolean, already computed by the caller from [`land_resume_state`].
2661fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
2662    if priority {
2663        PermitKind::None
2664    } else if urgent {
2665        PermitKind::Urgent
2666    } else {
2667        PermitKind::Ordinary
2668    }
2669}
2670
2671struct DispatchClaim {
2672    task: Task,
2673    claim: crate::queue::Claim,
2674    permit: Option<tokio::sync::OwnedSemaphorePermit>,
2675}
2676
2677/// Claim and re-read before choosing a lane: a queue listing may predate an
2678/// urgent toggle. All unsuccessful paths release the claim without an attempt.
2679fn claim_dispatch(
2680    queue: &Queue,
2681    candidate: &Task,
2682    cooling_down: bool,
2683    ordinary: &Arc<tokio::sync::Semaphore>,
2684    urgent: &Arc<tokio::sync::Semaphore>,
2685) -> Option<DispatchClaim> {
2686    let Ok(claim) = queue.claim(&candidate.id) else {
2687        tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
2688        return None;
2689    };
2690    let task = match queue.get(&candidate.id) {
2691        Ok(t) if t.status.runnable() => t,
2692        Ok(_) => return None,
2693        Err(e) => {
2694            tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
2695            return None;
2696        }
2697    };
2698    let resume = land_resume_state(&task);
2699    if resume == LandResume::StillWaiting {
2700        return None;
2701    }
2702    let priority = resume == LandResume::Ready;
2703    if !priority && cooling_down {
2704        return None;
2705    }
2706    // Never borrow an ordinary slot when the single urgent slot is busy.
2707    // Keep scanning other candidates when either pool has no free slot.
2708    let permit = match permit_kind(priority, task.urgent) {
2709        PermitKind::None => None,
2710        PermitKind::Urgent => Some(Arc::clone(urgent).try_acquire_owned().ok()?),
2711        PermitKind::Ordinary => Some(Arc::clone(ordinary).try_acquire_owned().ok()?),
2712    };
2713    Some(DispatchClaim {
2714        task,
2715        claim,
2716        permit,
2717    })
2718}
2719
2720/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
2721/// teardown and cannot skip the teardown on an early return.
2722///
2723/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
2724/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
2725/// land approval that has since been answered is dispatched outside that
2726/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
2727/// the whole point of parking there is that it must not queue behind
2728/// whatever else the loop happens to be running, even at the default of one.
2729/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
2730/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
2731/// these exemptions is still subject to the interrupt gate below, urgent
2732/// included: a land-resume or urgent candidate is exactly as much "something
2733/// else running" as an ordinary one from the interrupt sequence's point of
2734/// view, and letting either slip through while a run is being parked, or
2735/// while the interrupt task itself has the floor, is precisely the second
2736/// run 75dd's own "at most one run, ever, at once" guarantee must never
2737/// allow - see [`Interrupt`]'s own doc.
2738async fn poll(
2739    opts: &Opts,
2740    queue: &Queue,
2741    status: &Arc<Mutex<Status>>,
2742    home: &Path,
2743    worktrees_root: &Path,
2744    stop: &Stop,
2745    limits: DispatchLimits,
2746) -> Result<()> {
2747    let DispatchLimits {
2748        max_concurrent,
2749        pause_for_interrupts,
2750    } = limits;
2751    // Only consulted by `once`, where a task that just failed is still
2752    // `runnable` and would otherwise be picked up again inside the same drain.
2753    // In the long-running mode a later poll retrying a failed task is the point,
2754    // and the attempt counter is what bounds it.
2755    let mut attempted: Vec<String> = Vec::new();
2756    let sem = Arc::new(tokio::sync::Semaphore::new(max_concurrent));
2757    // One extra, permanent slot for `--urgent` tasks (see `Task::urgent`),
2758    // entirely separate from `sem`: an urgent candidate must dispatch
2759    // alongside whatever `sem` already has checked out, never by waiting for
2760    // one of those ordinary slots to free up and never by growing
2761    // `max_concurrent_runs` itself. Sized at one, not unbounded - see
2762    // `permit_kind`'s own doc - so a second `--urgent` task queues behind the
2763    // first on this same slot rather than opening a third run.
2764    let urgent_sem = Arc::new(tokio::sync::Semaphore::new(1));
2765    // A quota hit is a fact about the machine, not the task that happened to
2766    // surface it, and every other *ordinary* candidate is no less likely to
2767    // hit the same wall - see the warning below. A land-merge resume is
2768    // exempt: it is a human decision finishing, not a fresh competition, and
2769    // must not sit out a quota cooldown it did not cause.
2770    let quota_cooldown_until: Arc<Mutex<Option<Timestamp>>> = Arc::new(Mutex::new(None));
2771    let mut inflight: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
2772    let mut conductor = Conductor::new();
2773    // See `maybe_prune_cache_between_runs`'s own doc: this is the cache check
2774    // a congested queue would otherwise starve of the fully-idle branch below.
2775    let mut cache_last_checked: Option<Timestamp> = None;
2776    // See `Interrupt`'s own doc: in-memory only, advanced once per tick.
2777    let mut interrupt = Interrupt::Idle;
2778    // The `Pause` handed to each dispatched candidate's own `Runner` - see
2779    // `attempt`'s new parameter - kept here so the tick that decides to park
2780    // a run for an interrupt can reach that specific run's handle and no
2781    // other's. Pruned to whatever is still in flight at the top of every
2782    // tick, so a finished attempt's handle does not linger.
2783    let mut interrupt_pauses: std::collections::HashMap<String, crate::graph::Pause> =
2784        std::collections::HashMap::new();
2785
2786    while !stop.stopped() {
2787        lock(status).polls += 1;
2788
2789        // Reap whatever finished since the last tick without blocking on
2790        // anything still running. `InFlightGuard` already released the slot
2791        // even if the spawned attempt panicked; this only surfaces that it
2792        // happened, since a panic swallowed here otherwise leaves no trace.
2793        while let Some(result) = inflight.try_join_next() {
2794            if let Err(e) = result {
2795                tracing::error!("a spawned attempt did not finish cleanly: {e}");
2796                notices::raise(Notice::error(
2797                    "loop:attempt",
2798                    "A queued attempt ended abnormally; check the task it was running.",
2799                ));
2800            }
2801        }
2802
2803        let swept = sweep_stale_claims(queue, STALE_CLAIM);
2804        if !swept.is_empty() {
2805            tracing::warn!(
2806                "swept {} stale claim(s) left behind by an earlier daemon: {}",
2807                swept.len(),
2808                swept.join(", ")
2809            );
2810        }
2811        // Capture stalled work before reclaiming it. A dead daemon's ordinary
2812        // lock is swept and reclaimed in this same poll, but the conductor
2813        // must still see that it was stranded rather than only its mechanical
2814        // terminal state.
2815        let now = Timestamp::now();
2816
2817        // No run this daemon spawned is mid-compile right now, whether or
2818        // not another candidate is about to start - see
2819        // `maybe_prune_cache_between_runs`'s own doc for why this cannot
2820        // wait for the queue to run dry.
2821        if !stop.busy_now() {
2822            maybe_prune_cache_between_runs(
2823                &opts.repo,
2824                opts,
2825                home,
2826                stop,
2827                &mut cache_last_checked,
2828                now,
2829            )
2830            .await;
2831        }
2832
2833        let stalled = stalled_tasks(queue, home, now);
2834        let stalled_ids: std::collections::BTreeSet<_> =
2835            stalled.iter().map(|task| task.id.clone()).collect();
2836        let reclaimed = reclaim_orphaned_running(queue, opts.max_attempts);
2837        if !reclaimed.is_empty() {
2838            tracing::warn!(
2839                "reclaimed {} task(s) left `running` by a daemon that never \
2840                 recorded the outcome: {}",
2841                reclaimed.len(),
2842                reclaimed.join(", ")
2843            );
2844        }
2845        let abandoned_runs = reclaim_abandoned_runs(home, now);
2846        if !abandoned_runs.is_empty() {
2847            tracing::warn!(
2848                "failed {} run(s) left behind by a killed process, past every \
2849                 active seat's own timeout: {}",
2850                abandoned_runs.len(),
2851                abandoned_runs.join(", ")
2852            );
2853        }
2854
2855        // `home`, not `ask::Questions::open()`'s own process-global default:
2856        // `poll` is handed its home explicitly precisely so a test can point
2857        // it elsewhere, the same reason `Queue::at` and the status file path
2858        // are parameters rather than resolved here - see `drive`'s own doc.
2859        let questions = Questions::at(home.join("questions"));
2860
2861        // Deterministic: no model, run before the conductor sees anything so
2862        // its input reflects the queue's current, already-resolved state.
2863        resolve_blockers(queue, &questions);
2864        apply_choice_actions(queue, &questions, home);
2865        triage::apply_answers(queue, &questions);
2866        reconcile_task_questions(queue, &questions);
2867        // Tell the chat a filed task or watched command has ended. Reconciled
2868        // here regardless of how it ended, and started only when no
2869        // upgrade is parking (the draft then waits for a manual resume).
2870        {
2871            let talks = crate::talk::Talks::at(home.join("talks"));
2872            crate::chat_notify::sweep(queue, &talks, home);
2873            crate::chat_watch::sweep(home, &talks);
2874            crate::chat_notify::start_turns(&talks, stop.parking(), &mut inflight);
2875        }
2876
2877        // The conductor gets one look per cycle, right before the loop takes
2878        // its next task, and only when there is something new to look at -
2879        // see `Conductor::worth_a_look`'s own doc for why "stalled is
2880        // non-empty" is the wrong test. Checked before `prepare` so an
2881        // unchanged cycle never pays for a synchronous config load.
2882        let finished: Vec<Task> = finished_tasks(queue)
2883            .into_iter()
2884            .filter(|task| !stalled_ids.contains(&task.id))
2885            // A parked run is waiting for this loop, not for a decision: the
2886            // conductor must not get to hold it or requeue it (a requeue
2887            // sets `fresh_start` and re-competes) before `attempt` resumes.
2888            .filter(|task| !awaiting_resume_with(task, |id| RunState::load_under(id, home)))
2889            .collect();
2890        let queued = queued_tasks(queue);
2891        // An empty queue has nothing to arrange. In particular, do not let
2892        // the conductor's initial snapshot cause synchronous config I/O
2893        // between the caller's stop notification and the idle wait below.
2894        if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
2895            && conductor.worth_a_look(queue, &stalled, &finished)
2896        {
2897            match prepare(&opts.repo, opts) {
2898                Ok(cfg) => {
2899                    conductor
2900                        .maybe_run(
2901                            &cfg,
2902                            &opts.repo,
2903                            queue,
2904                            &questions,
2905                            home,
2906                            &queued,
2907                            &stalled,
2908                            &finished,
2909                            opts.max_attempts,
2910                        )
2911                        .await;
2912                }
2913                Err(e) => {
2914                    tracing::warn!("conductor: no config: {e:#}");
2915                    notices::raise(Notice::warn(
2916                        "loop:no-config",
2917                        "The loop could not read this repository's config, so held tasks are not being triaged.",
2918                    ));
2919                }
2920            }
2921        }
2922
2923        let candidates: Vec<Task> = runnable(queue)
2924            .into_iter()
2925            .filter(|t| !opts.once || !attempted.contains(&t.id))
2926            .collect();
2927
2928        // A task id only stays a key here while its attempt is genuinely in
2929        // flight; `status.current` is the same liveness fact `InFlightGuard`
2930        // maintains for the phone's own status file, so this piggybacks on
2931        // it rather than tracking a second copy of the same thing.
2932        let in_flight: Vec<String> = lock(status)
2933            .current
2934            .iter()
2935            .map(|c| c.task.clone())
2936            .collect();
2937        interrupt_pauses.retain(|id, _| in_flight.contains(id));
2938
2939        interrupt =
2940            advance_interrupt_tick(pause_for_interrupts, interrupt, &in_flight, &candidates);
2941        if let Interrupt::Parking {
2942            parked,
2943            interrupt_task,
2944        } = &interrupt
2945        {
2946            let reason = format!(
2947                "task {} asked to run first",
2948                crate::run::short_of(interrupt_task)
2949            );
2950            for id in parked {
2951                if let Some(pause) = interrupt_pauses.get(id) {
2952                    pause.park_because(reason.clone());
2953                }
2954            }
2955        }
2956        let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
2957
2958        let cooling_down =
2959            lock(&quota_cooldown_until).is_some_and(|until| Timestamp::now() < until);
2960
2961        let mut started_any = false;
2962        for candidate in candidates {
2963            if stop.stopped() {
2964                break;
2965            }
2966
2967            let Some(DispatchClaim {
2968                mut task,
2969                claim,
2970                permit,
2971            }) = claim_dispatch(queue, &candidate, cooling_down, &sem, &urgent_sem)
2972            else {
2973                continue;
2974            };
2975
2976            let task_id = task.id.clone();
2977            attempted.push(task_id.clone());
2978            lock(status).idle = false;
2979            // A stop asked for from here on is "finishing", not "stopped": the
2980            // run gets to reach a terminal status before the loop returns.
2981            stop.enter();
2982            started_any = true;
2983
2984            // A fresh, unshared handle - never `stop.pause()` - so parking
2985            // this run for an interrupt cannot leak into any other run this
2986            // loop ever drives. See `Pause`'s own doc.
2987            let run_pause = crate::graph::Pause::new();
2988            interrupt_pauses.insert(task_id.clone(), run_pause.clone());
2989
2990            let opts = opts.clone();
2991            let queue = queue.clone();
2992            let status = Arc::clone(status);
2993            let stop = stop.clone();
2994            let quota_cooldown_until = Arc::clone(&quota_cooldown_until);
2995            inflight.spawn(async move {
2996                // Held for the whole attempt: dropping either at the end of
2997                // this task is what releases the claim and, for an ordinary
2998                // candidate, frees its concurrency slot back to the loop.
2999                let _claim = claim;
3000                let _permit = permit;
3001                // See `InFlightGuard`: this must survive a panic inside `attempt`.
3002                let _inflight = InFlightGuard {
3003                    status: &status,
3004                    stop: &stop,
3005                    task_id: &task_id,
3006                };
3007                let quota = attempt(&opts, &queue, &status, &stop, run_pause, &mut task).await;
3008                lock(&status).completed += 1;
3009                // A quota loss is a fact about the machine, not this task, and
3010                // the next ordinary candidate the loop offers is no less
3011                // likely to hit the same wall: without a cooldown here a
3012                // whole backlog can be run - and failed - in the seconds it
3013                // takes each attempt to notice the CLI is out of quota.
3014                let now = Timestamp::now();
3015                if let Some(until) = cooldown_until(&quota, now) {
3016                    let wait = until.as_second() - now.as_second();
3017                    *lock(&quota_cooldown_until) = Some(until);
3018                    let hint = quota
3019                        .iter()
3020                        .find(|q| q.reset.is_some())
3021                        .and_then(|q| q.reset.as_deref());
3022                    match hint {
3023                        Some(h) => tracing::warn!(
3024                            "quota hit; waiting {wait}s before taking another ordinary task \
3025                             (CLI reported reset: {h})"
3026                        ),
3027                        None => tracing::warn!(
3028                            "quota hit; waiting {wait}s before taking another ordinary task \
3029                             (no reset hint reported)"
3030                        ),
3031                    }
3032                }
3033            });
3034        }
3035
3036        if started_any {
3037            continue;
3038        }
3039
3040        if stop.busy_now() {
3041            // Something started on an earlier tick is still running. Recheck
3042            // soon rather than sleeping out the whole poll interval - a freed
3043            // slot, or a land approval answered mid-run, must not sit idle
3044            // for it.
3045            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
3046            continue;
3047        }
3048
3049        // Truly idle: nothing new to start and nothing still running.
3050        lock(status).idle = true;
3051        if opts.once {
3052            // A one-shot drain must perform the same post-work cleanup as a
3053            // daemon that reached a normal idle interval. The startup pass
3054            // cannot see runs or cache files produced by this drain.
3055            janitor(&opts.repo, opts, home, worktrees_root).await;
3056            resweep_superseded_attempts(queue, home);
3057            triage_held(queue, home, opts).await;
3058            break;
3059        }
3060        stop.idle(opts.poll).await;
3061        if stop.stopped() {
3062            continue;
3063        }
3064        // Housekeeping only after a full quiet interval. Running it before
3065        // the first idle wait can block the executor while an operator's
3066        // stop request is waiting to be scheduled, defeating Stop's retained
3067        // wake permit. No run can start while this branch is active, so the
3068        // janitor still never races an in-flight compile.
3069        janitor(&opts.repo, opts, home, worktrees_root).await;
3070        resweep_superseded_attempts(queue, home);
3071        triage_held(queue, home, opts).await;
3072    }
3073
3074    // Never return while a run is still in flight, whichever way the loop
3075    // above exited: a stop only sets a flag - see `serve_until` - and
3076    // returning here while `inflight` still holds spawned work would abandon
3077    // it exactly as a mid-node kill would.
3078    while let Some(result) = inflight.join_next().await {
3079        if let Err(e) = result {
3080            tracing::error!("a spawned attempt did not finish cleanly: {e}");
3081            notices::raise(Notice::error(
3082                "loop:attempt",
3083                "A queued attempt ended abnormally; check the task it was running.",
3084            ));
3085        }
3086    }
3087    Ok(())
3088}
3089
3090/// Run one claimed task to a terminal status and record the outcome.
3091///
3092/// Every transition is flushed to the queue as it happens, so the state on disk
3093/// is what actually occurred rather than what this process still intends to
3094/// write.
3095async fn attempt(
3096    opts: &Opts,
3097    queue: &Queue,
3098    status: &Arc<Mutex<Status>>,
3099    stop: &Stop,
3100    interrupt_pause: crate::graph::Pause,
3101    task: &mut Task,
3102) -> Vec<QuotaLoss> {
3103    let repo = repo_for(task, &opts.repo);
3104    tracing::info!(
3105        "task {} — {} (repo {})",
3106        task.short(),
3107        task.title,
3108        repo.display()
3109    );
3110
3111    // A stop spends no agent resources and uses the saved landing owner.
3112    // Current roster edits, missing attachments or a failed config fetch must
3113    // never turn it into a new implementation, or prevent a PR from closing.
3114    if let Some(previous) = task.runs.last().and_then(|id| RunState::load(id).ok())
3115        && previous
3116            .merge_decision
3117            .as_ref()
3118            .is_some_and(|decision| !decision.closed)
3119        && previous.status != RunStatus::Landing
3120        && !crate::merge_decision::resumable_hold(&previous)
3121    {
3122        task.hold_unrequested_retry(Some(format!("The existing owner stop decision remains held. Inspect run {} and its PR; request an explicit fresh review/decision before further work. No replacement or merge was started.", previous.id)));
3123        record(queue, task);
3124        return Vec::new();
3125    }
3126    let stop_owner = task
3127        .runs
3128        .last()
3129        .and_then(|id| RunState::load(id).ok())
3130        .filter(|state| {
3131            crate::merge_decision::resumable_hold(state)
3132                || state.status == RunStatus::Landing
3133                    && state.land_approval.as_ref().is_some_and(|binding| {
3134                        Questions::open().get(&binding.question).is_ok_and(|q| {
3135                            q.run == state.id
3136                                && q.resolution()
3137                                    .as_deref()
3138                                    .is_some_and(crate::merge_decision::stops)
3139                        })
3140                    })
3141        });
3142    if let Some(owner) = stop_owner {
3143        let mut runner = match Runner::resume(&owner.id) {
3144            Ok(runner) => runner,
3145            Err(e) => {
3146                task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
3147                record(queue, task);
3148                return Vec::new();
3149            }
3150        };
3151        runner.on_pause(stop.pause());
3152        runner.watch_interrupt(interrupt_pause);
3153        let quota_before = runner.state.quota.clone();
3154        task.start(owner.id.clone());
3155        record(queue, task);
3156        lock(status).current.push(Current {
3157            task: task.id.clone(),
3158            run: owner.id,
3159        });
3160        runner.state.next_pass_task_entry = true;
3161        let result = runner.execute().await;
3162        return finish_attempt(
3163            opts.max_attempts,
3164            queue,
3165            task,
3166            &runner.state,
3167            &quota_before,
3168            result,
3169        );
3170    }
3171
3172    // The repository's magi.toml comes from `<remote>/<base>`, fetched now. A
3173    // failure here is the network's or the operator's, not the task's: hold
3174    // without spending an attempt, never fall back to a possibly stale copy.
3175    let explicit = match &task.overrides {
3176        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
3177        Some(_) => opts.config.as_deref(),
3178        None => opts.config.as_deref(),
3179    };
3180    if let Err(e) = Config::discover_fetched(&repo, explicit).await {
3181        let reason = format!("[config] {e:#}");
3182        record_config_failure(task, &e);
3183        task.last_error = Some(reason.clone());
3184        task.hold_machine(Some(reason.clone()));
3185        record(queue, task);
3186        tracing::warn!("holding {}: {reason}", task.short());
3187        return Vec::new();
3188    }
3189    let mut config = match prepare_for(&repo, opts, task) {
3190        Ok(c) => c,
3191        Err(e) => {
3192            // A setup failure spends an attempt even though no run was minted.
3193            // Without that, a task naming a repository that does not exist
3194            // would be retried at every poll for as long as the daemon lives.
3195            task.attempts += 1;
3196            task.fail_startup(
3197                "startup-config",
3198                format!("config: {e:#}"),
3199                opts.max_attempts,
3200            );
3201            record(queue, task);
3202            return Vec::new();
3203        }
3204    };
3205    apply_task_implementers(&mut config, task);
3206    if let Some(replacement) = &task.replacement {
3207        let safe = RunState::load(&replacement.run).is_ok_and(|old| {
3208            old.liveness(false) == Liveness::Dead
3209                && old.merge_decision.as_ref().is_some_and(|d| {
3210                    d.closed
3211                        && d.question == replacement.question
3212                        && d.replacement_run.as_ref().is_none_or(|run| {
3213                            task.runs.last() == Some(run)
3214                                && RunState::load(run).is_ok_and(|current| {
3215                                    current.replaces.as_ref().is_some_and(|pin| {
3216                                        pin.question == replacement.question
3217                                            && pin.agent == replacement.agent
3218                                    })
3219                                })
3220                        })
3221                })
3222        });
3223        if !safe {
3224            task.hold_manual(Some("Replacement ownership cannot be confirmed, or a replacement run was already minted before a crash. Inspect the task and its linked runs; no second replacement was started.".into()));
3225            record(queue, task);
3226            return Vec::new();
3227        }
3228        match config.agent(&replacement.agent) {
3229            Ok(agent) if crate::agent::installed(agent) => {}
3230            _ => {
3231                task.hold_manual(Some(format!("Selected implementer `{}` is unavailable or no longer configured. No substitute was dispatched. Restore it and explicitly release the task.", replacement.agent)));
3232                record(queue, task);
3233                return Vec::new();
3234            }
3235        }
3236        config.graph.implementers = 1;
3237        config.graph.land_approval = true;
3238        config.merge.mode = MergeMode::Pr;
3239        config.graph.selected_implementer = Some(replacement.agent.clone());
3240    }
3241    let p = phrases(&config.graph.language);
3242    let start_failed = p.could_not_start;
3243
3244    // The free-space gate, checked *before* anything is minted: a task that
3245    // waits out a full disk costs nothing yet, and must not spend an attempt
3246    // or start a run the machine cannot finish. Held tasks stay in the list
3247    // for the human to see, and `magi task release` re-queues them when space
3248    // comes back - the same recovery as any other hold. A volume whose free
3249    // space cannot be measured closes the gate too: starting a run blind on a
3250    // disk that may be full is how the machine ends up with 6.7 GB free.
3251    if let Some(reason) = disk_gate(&repo, &config) {
3252        task.notice_cause("disk-space", None, None);
3253        task.last_error = Some(reason.clone());
3254        task.hold_machine(Some(reason.clone()));
3255        record(queue, task);
3256        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
3257        // Stable wording - the free-space figures live in the task's hold
3258        // reason, and changing numbers would relight the bell every poll.
3259        notices::raise(
3260            Notice::warn(
3261                &format!("disk:{}", repo.display()),
3262                "A task was held for want of free disk space; free some, then release it from the queue.",
3263            )
3264            .link(Link::Task {
3265                id: task.id.clone(),
3266            }),
3267        );
3268        return Vec::new();
3269    }
3270
3271    // A resumable run of this task is carried on, never re-competed. The
3272    // candidates are built and paid for, and a fresh competition races a
3273    // second implementation against them.
3274    //
3275    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
3276    // started 3cbf on the same task a moment later, duplicating two and a
3277    // half hours of agent work. Then b25f stalled on a judge that timed out
3278    // and one that answered with no JSON - `quota: 0`, so nothing the machine
3279    // was to blame for - and 4043 started **one second** later, buying three
3280    // fresh implementations to reach the same panel. `RunStatus::resumable`
3281    // rather than `!done()` is what catches the second case: a stall is
3282    // terminal, and its cheap recovery re-asks only the absent seats.
3283    //
3284    // A load failure is warned about rather than silently read as "not
3285    // resumable": the alternative is exactly what let a schema mismatch on
3286    // run `eba2` fall through to a full re-competition with nobody told why.
3287    // `crate::conduct` is what actually offers a better answer than
3288    // `Runner::start` here (see `Recovery::Review`), once this task's next
3289    // failure shows it up as `held`/`failed` with the run state unreadable.
3290    let unfinished = (!task.fresh_start)
3291        .then(|| unfinished_run(&task.runs, task.short()))
3292        .flatten()
3293        .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
3294    // `crate::conduct` chose `Review` for this task on an earlier cycle: its
3295    // branch survived, and this reopens exactly that branch as a
3296    // review-only pass rather than resuming or competing again. Consumed
3297    // (cleared) here whichever way this goes, so it never outlives this one
3298    // attempt - see `queue::Task::review_branch`.
3299    let previous = task.runs.last().and_then(|id| RunState::load(id).ok());
3300    let review_branch = take_review_branch(task, previous.as_ref());
3301    let branch_exists = match &review_branch {
3302        Some(branch) => crate::git::branch_exists(&repo, branch)
3303            .await
3304            .unwrap_or(false),
3305        None => false,
3306    };
3307    // An explicit `magi review <branch>` is reviewed whatever happens to the
3308    // branch unless an explicit implementer change requires fresh work. An
3309    // unfinished run of the same task still wins, so a retry resumes.
3310    let proposed = match (&review_branch, &unfinished, &task.review_of) {
3311        (None, None, Some(branch)) => Starter::Review(branch.clone()),
3312        _ => choose_starter(
3313            review_branch.as_deref(),
3314            branch_exists,
3315            unfinished.as_deref(),
3316        ),
3317    };
3318    let retry_selected = task.replacement.is_some()
3319        && task.resumption.is_some()
3320        && !task.fresh_start
3321        && previous.as_ref().is_some_and(|run| {
3322            run.replaces.is_some()
3323                && ((run.status == RunStatus::Failed && run.viable().is_empty())
3324                    || (run.status == RunStatus::Blocked && run.tally.is_none()))
3325        });
3326    let stop_pin = task
3327        .resume_override
3328        .as_ref()
3329        .filter(|pin| {
3330            Questions::open().get(&pin.question_id).is_ok_and(|q| {
3331                q.node == land::APPROVAL_NODE
3332                    && q.resolution()
3333                        .as_deref()
3334                        .is_some_and(crate::merge_decision::stops)
3335            })
3336        })
3337        .and_then(|pin| pin.pinned_run.clone());
3338    let starter = if let Some(run) = stop_pin {
3339        // Stop actions resume their exact owner even after seat-count edits;
3340        // they must never fall through to implementation or a takeover.
3341        Starter::Resume(run)
3342    } else if retry_selected {
3343        Starter::Resume(previous.as_ref().unwrap().id.clone())
3344    } else if let Some(selected) = &task.pr_recovery {
3345        if selected.check_task(&task.id, &task.instruction).is_ok() {
3346            selected_starter(selected, previous.as_ref(), unfinished.as_deref())
3347        } else {
3348            Starter::Review(selected.branch.clone())
3349        }
3350    } else {
3351        starter_with_implementers(task, previous.as_ref(), proposed)
3352    };
3353    // A repair pin must never degrade into a new competition or takeover if
3354    // the owner disappears between the answer and dispatch.
3355    if let Some(pin) = &task.resume_override
3356        && let Some(run) = &pin.pinned_run
3357        && Questions::open().get(&pin.question_id).map_or(true, |q| {
3358            q.node == land::APPROVAL_NODE && q.resolution().as_deref() == Some(land::REPAIR)
3359        })
3360        && starter != Starter::Resume(run.clone())
3361    {
3362        let run = run.clone();
3363        task.notice_cause("repair-owner", Some(&run), None);
3364        task.hold_machine(Some(format!(
3365            "repair owner cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
3366            task.id
3367        )));
3368        record(queue, task);
3369        return Vec::new();
3370    }
3371    if task.replacement.is_some()
3372        && previous.as_ref().is_some_and(|run| run.replaces.is_some())
3373        && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
3374    {
3375        task.hold_manual(Some("The selected replacement already has an attempt. It cannot be resumed safely; inspect its saved pin and restore the existing run. No additional replacement was started.".into()));
3376        record(queue, task);
3377        return Vec::new();
3378    }
3379    // Absolute paths of the files the task was filed with, re-read from the
3380    // task now so a file attached while it was held reaches a resumed run
3381    // too. A stored name whose file has gone is an error before any agent is
3382    // paid for, never a silent omission the implementer cannot notice.
3383    let attachments = match task_attachments(queue, task) {
3384        Ok(a) => a,
3385        Err(e) => {
3386            task.attempts += 1;
3387            task.fail_startup_target(
3388                "startup-attachments",
3389                e.name.clone(),
3390                format!("{start_failed}{e:#}"),
3391                opts.max_attempts,
3392            );
3393            record(queue, task);
3394            return Vec::new();
3395        }
3396    };
3397    let startup_pause = stop.pause();
3398    let startup_interrupt = interrupt_pause.clone();
3399    let wait = crate::repo_lock::WaitPolicy::new(
3400        Duration::from_secs(config.graph.timeout_resource_wait),
3401        move || startup_pause.parked() || startup_interrupt.parked(),
3402    );
3403    let started = wait.scope(async { match &starter {
3404        Starter::Review(_) if task.pr_recovery.is_some() => {
3405            let selected = task.pr_recovery.clone().expect("selected recovery");
3406            match selected.check_task(&task.id, &task.instruction) {
3407                Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
3408                    .await
3409                    .map(|mut r| {
3410                        r.state.attachments = attachments.clone();
3411                        r
3412                    }),
3413                Err(e) => Err(e),
3414            }
3415        }
3416        Starter::Review(branch) => {
3417            tracing::info!(
3418                "task {} reopens `{branch}` as a review-only pass",
3419                task.short()
3420            );
3421            // Every earlier attempt is superseded by the one being minted
3422            // now, so a branch one of them still holds may be taken over.
3423            let takeover = crate::handover::Takeover {
3424                earlier: task.earlier_attempts().to_vec(),
3425                home: crate::run::home(),
3426                choice: take_divergence_answer(branch, &config.merge.remote, task),
3427                task_instruction: Some(instruction_for(task)),
3428            };
3429            Runner::review_taking_over(
3430                &repo,
3431                branch,
3432                config,
3433                Some(takeover),
3434                crate::run::Origin::queue(&task.id),
3435            )
3436            .await
3437        }
3438        Starter::Resume(id) => {
3439            tracing::info!("resuming run {id} rather than competing again");
3440            Runner::resume(id).and_then(|mut r| {
3441                if retry_selected {
3442                    // The explicit queue release retries this same pinned
3443                    // implementation, preserving the attempt and worktrees.
3444                    for candidate in &mut r.state.candidates {
3445                        candidate.failed = None;
3446                        candidate.empty = false;
3447                        candidate.commits = 0;
3448                    }
3449                    r.state.status = RunStatus::Implementing;
3450                    r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
3451                }
3452                if r.state.prep_failure.is_some() {
3453                    let approval = task
3454                        .resumption
3455                        .as_ref()
3456                        .context("preparation retry requires an explicit task release")?;
3457                    r.retry_preparation(approval.at)?;
3458                }
3459                if let Some(instruction) =
3460                    prepare_instruction(&starter, Some(&r.state.instruction), task)
3461                {
3462                    r.state.instruction = instruction;
3463                }
3464                r.state.attachments = attachments.clone();
3465                if task.replacement.is_some() {
3466                    r.state.config.merge.mode = MergeMode::Pr;
3467                    r.state.config.graph.land_approval = true;
3468                }
3469                // A replacement always publishes a new PR and asks for a new
3470                // decision. Other runs retain their original merge override.
3471                if task.replacement.is_none() && let Some(mode) = task
3472                    .overrides
3473                    .as_ref()
3474                    .and_then(|o| o.merge.as_deref())
3475                    .and_then(|m| merge_mode(m).ok())
3476                {
3477                    r.state.config.merge.mode = mode;
3478                }
3479                Ok(r)
3480            })
3481        }
3482        Starter::Start => {
3483            if let Some(branch) = &review_branch {
3484                tracing::warn!(
3485                    "conductor chose review for task {} but branch `{branch}` no longer \
3486                     exists; requeuing as a fresh competition instead",
3487                    task.short()
3488                );
3489            }
3490            let instruction = prepare_instruction(&starter, None, task)
3491                .unwrap_or_else(|| task.instruction.clone());
3492            Runner::start_naming(
3493                &repo,
3494                instruction,
3495                &task.title,
3496                config,
3497                crate::run::Origin::queue(&task.id),
3498            )
3499            .await
3500            .map(|mut r| {
3501                r.state.attachments = attachments.clone();
3502                r
3503            })
3504        }
3505    }}).await;
3506    let mut runner = match started {
3507        Ok(r) => r,
3508        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
3509            task.last_error = Some(e.to_string());
3510            if stop.parking() || interrupt_pause.parked() {
3511                let attempts = task.attempts;
3512                task.park(e.to_string());
3513                // Startup has not spent an attempt to refund.
3514                task.attempts = attempts;
3515            } else {
3516                task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
3517            }
3518            record(queue, task);
3519            return Vec::new();
3520        }
3521        // A branch an earlier attempt still holds and magi will not release
3522        // by itself is the operator's call, not a failed attempt: hold the
3523        // task with the reason, spend nothing, and say so on the bell.
3524        Err(e) if task.pr_recovery.is_some() => {
3525            task.startup_notice_cause("startup-public-head");
3526            task.attempts += 1;
3527            if let Some(partial) = e.downcast_ref::<crate::pr_recovery::StartupFailed>() {
3528                task.link_run(&partial.run);
3529                task.record_pass(&partial.run, 0, task.attempts, None);
3530            }
3531            task.last_error = Some(format!("{start_failed}{e:#}"));
3532            task.hold_unrequested_retry(Some(format!(
3533                "Selected public-head recovery could not start: {e:#}. Correct the cause and use `magi task recover-pr` with the approved public head; automatic recovery is stopped."
3534            )));
3535            record(queue, task);
3536            return Vec::new();
3537        }
3538        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
3539            let detail = match e.downcast_ref::<crate::handover::Refused>() {
3540                Some(r) => (p.handover_refused)(r),
3541                None => format!("{e:#}"),
3542            };
3543            task.startup_notice_cause("startup-handover");
3544            let reason = format!("{start_failed}{detail}");
3545            task.last_error = Some(reason.clone());
3546            // Consumed above by `take`; keep it so the released task retries
3547            // as a review of this same branch.
3548            let branch = match &starter {
3549                Starter::Review(branch) => Some(branch.clone()),
3550                _ => None,
3551            };
3552            // The hold's own `task:<id>` notice (raised by `Queue::put`) is the
3553            // one page; the guidance rides in the reason, fixed per state so a
3554            // re-put never changes the wording and relights it.
3555            task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
3556            record(queue, task);
3557            tracing::warn!(
3558                "holding {} for a branch it cannot take over: {e:#}",
3559                task.short()
3560            );
3561            return Vec::new();
3562        }
3563        // A branch that differs between here and the remote in ways magi
3564        // cannot prove are the same change is a decision for the owner, not a
3565        // failed attempt: ask with both sides laid out, spend no attempt, and
3566        // let the answer requeue the task.
3567        Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
3568            let d = e
3569                .downcast_ref::<crate::reconcile::Diverged>()
3570                .expect("checked by the guard");
3571            let mut q = ask::Question::new(
3572                task.id.clone(),
3573                crate::reconcile::NODE.to_owned(),
3574                crate::reconcile::SEAT.to_owned(),
3575                d.summary(),
3576                d.detail(),
3577                d.choices(),
3578            );
3579            match Questions::open().put(&mut q) {
3580                Ok(()) => {
3581                    task.last_error = Some(format!("{e:#}"));
3582                    // Consumed above by `take`; the answer has to reach a review
3583                    // of this same branch, so keep pointing the task at it.
3584                    task.review_branch = Some(d.branch.clone());
3585                    task.review_instruction = Some(task.instruction.clone());
3586                    task.block(vec![q.id.clone()], Some(d.summary()));
3587                }
3588                Err(put) => {
3589                    tracing::warn!("could not file the divergence question: {put:#}");
3590                    task.attempts += 1;
3591                    task.fail_startup(
3592                        "startup-question-store",
3593                        format!("{start_failed}{e:#}"),
3594                        opts.max_attempts,
3595                    );
3596                }
3597            }
3598            record(queue, task);
3599            return Vec::new();
3600        }
3601        Err(e) => {
3602            // The answer was stale and nothing was applied: keep pointing at
3603            // the branch so the next attempt asks again against its new tips.
3604            // Nothing went wrong with the task, so no attempt is spent: a
3605            // budget one short of its limit must not hold it instead of
3606            // letting the question be asked again.
3607            if e.downcast_ref::<crate::reconcile::Stale>().is_some()
3608                && let Starter::Review(branch) = &starter
3609            {
3610                task.review_branch = Some(branch.clone());
3611                task.review_instruction = Some(task.instruction.clone());
3612                task.last_error = Some(format!("{start_failed}{e:#}"));
3613                task.status = crate::queue::TaskStatus::Failed;
3614                record(queue, task);
3615                return Vec::new();
3616            }
3617            task.attempts += 1;
3618            task.last_error = Some(format!("{start_failed}{e:#}"));
3619            task.startup_notice_cause("startup-source");
3620            task.hold_unrequested_retry(Some(format!(
3621                "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
3622            )));
3623            record(queue, task);
3624            return Vec::new();
3625        }
3626    };
3627    if let Some(replacement) = &task.replacement {
3628        if matches!(starter, Starter::Start) {
3629            runner.state.instruction.push_str(&format!(
3630                "\n\n# Replacement review context\n{}",
3631                replacement.context
3632            ));
3633        }
3634        runner.state.replaces = Some(replacement.clone());
3635        runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
3636        if let Ok(mut old) = RunState::load(&replacement.run)
3637            && let Some(d) = &mut old.merge_decision
3638        {
3639            d.replacement_run = Some(runner.state.id.clone());
3640            old.event(
3641                "replacement",
3642                format!(
3643                    "replacement run {} owns the next attempt; old PR remains closed",
3644                    runner.state.id
3645                ),
3646            );
3647            if let Err(e) = old.save() {
3648                task.hold_manual(Some(format!(
3649                    "Could not link replacement history: {e}; no agents dispatched"
3650                )));
3651                record(queue, task);
3652                return Vec::new();
3653            }
3654        }
3655    }
3656    runner.state.task_instruction = Some(task.instruction.clone());
3657    // The follow-up depth is fixed now, while the task certainly exists:
3658    // deleting it later must not reset the cap (`crate::followup`).
3659    runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
3660    if runner.state.origin_chat.is_none() {
3661        runner.state.origin_chat = task.chat_talk().map(str::to_owned);
3662    }
3663    // A stop that means "park" reaches the graph through this handle.
3664    runner.on_pause(stop.pause());
3665    // `poll`'s interrupt scheduler reaches this one run - and no other -
3666    // through this handle. See `Pause`'s own doc for why these are never
3667    // the same one.
3668    runner.watch_interrupt(interrupt_pause);
3669
3670    // `start` has minted the run, so the task can now point at it. Persisting
3671    // `Running` before `execute` is what makes a crash mid-run legible.
3672    let run = runner.state.id.clone();
3673    task.start(run.clone());
3674    record(queue, task);
3675    lock(status).current.push(Current {
3676        task: task.id.clone(),
3677        run,
3678    });
3679
3680    // `RunState::quota` is the run's whole history across every resume, so
3681    // only what this execution added may arm the cooldown or earn a refund.
3682    let quota_before = runner.state.quota.clone();
3683    runner.state.next_pass_task_entry = true;
3684    let result = runner.execute().await;
3685    finish_attempt(
3686        opts.max_attempts,
3687        queue,
3688        task,
3689        &runner.state,
3690        &quota_before,
3691        result,
3692    )
3693}
3694
3695/// Settle `task` after its run executed: the verdict, the diagnosis, the
3696/// supersession of earlier attempts and the save. Shared by the loop and by
3697/// `magi run --resume`, so an attempt is counted one way wherever it ran.
3698/// Returns the quota losses this execution added to the run.
3699pub fn finish_attempt(
3700    max_attempts: usize,
3701    queue: &Queue,
3702    task: &mut Task,
3703    state: &RunState,
3704    quota_before: &[QuotaLoss],
3705    result: Result<()>,
3706) -> Vec<QuotaLoss> {
3707    let detail = match result {
3708        Ok(()) => describe(state),
3709        Err(e) => format!("{e:#}"),
3710    };
3711    let fresh = losses_this_attempt(quota_before, &state.quota);
3712    let verdict = Verdict {
3713        status: state.status,
3714        // A run that opened a pull request handed its work over, whatever the
3715        // gate then decided about merging it.
3716        left_pr: state.pr.is_some(),
3717        // Only a rate limit earns the task its attempt back - and only one
3718        // suffered now: a refund justified by a previous session's loss is
3719        // the same mistake as re-arming the cooldown from it. A stalled run
3720        // resumed without hitting quota again therefore spends its attempt,
3721        // like any other failure of the task's own.
3722        quota_hit: !fresh.is_empty(),
3723        // A run that parked was asked to stop; that is not a failure and must
3724        // not spend an attempt, or replacing the binary a few times would
3725        // exhaust a task's budget without an agent ever misbehaving.
3726        parked: state.parked,
3727        // A quota loss that left nothing viable is the same machine fact as a
3728        // `Stalled` quota loss; see `settle`'s doc table.
3729        no_viable_candidates: state.viable().is_empty(),
3730    };
3731    if let Some(replacement) = &state.replaces
3732        && let Some(pr) = &state.pr
3733        && let Ok(mut old) = RunState::load(&replacement.run)
3734        && let Some(d) = &mut old.merge_decision
3735    {
3736        d.replacement_pr = Some(pr.url.clone());
3737        let _ = old.save();
3738    }
3739    settle_and_diagnose(task, verdict, &detail, max_attempts, state);
3740    if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
3741        task.hold_unrequested_retry(Some(format!(
3742            "Candidate setup failed: {detail}. Select a complete implementation with `magi task recover-pr`, or correct the referenced source before explicitly releasing the task."
3743        )));
3744    }
3745    if task.status == TaskStatus::Done {
3746        supersede_prior_runs(task, &crate::run::home());
3747    }
3748    record(queue, task);
3749    tracing::info!(
3750        "task {} is {} after run {} ({})",
3751        task.short(),
3752        task.status.as_str(),
3753        state.short(),
3754        label(state.status)
3755    );
3756    fresh
3757}
3758
3759/// A task a hand-started run leaves runnable (failed with attempts to spare,
3760/// or requeued) is **held**: nobody asked for a retry, and a loop starting
3761/// later must not spend agent calls on it. `magi task release` retries.
3762pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
3763    // A run parked on the owner's word about a withheld PR title/body is not a
3764    // failure nobody asked to retry: it resumes (answer, or the neutral text on
3765    // the deadline) the moment a loop serves the queue, via `land_resume_state`.
3766    // Holding it would keep it from ever being a candidate.
3767    let waits_on_owner = withheld_text_wait(task).is_some();
3768    if task.status.runnable()
3769        && !waits_on_owner
3770        && !(task.fresh_start && task.replacement.is_some())
3771    {
3772        let why = task.last_error.clone().map_or_else(
3773            || "the run did not finish".to_owned(),
3774            |e| format!("the run did not finish: {e}"),
3775        );
3776        task.hold_unrequested_retry(Some(format!(
3777            "{why}. It was started by hand, so it is not retried \
3778             automatically; `magi task release` retries it."
3779        )));
3780        record(queue, task);
3781    }
3782}
3783
3784/// Whether an attempt at a task whose newest run is `run` would resume that
3785/// run rather than start a fresh competition. `magi run --resume` hands a run
3786/// to a live loop only when this holds.
3787#[must_use]
3788pub fn loop_would_resume(run: &str) -> bool {
3789    unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
3790}
3791
3792/// A loop in another process that is alive right now: a fresh heartbeat in
3793/// `<home>/daemon.json` published by a pid that is not `own_pid`. `Some(pid)`
3794/// carries the pid it published (`None` inside when it published none - a
3795/// fresh heartbeat is still evidence of a live loop).
3796///
3797/// The one judgement of "is somebody else serving this queue", shared by the
3798/// web UI's refusal to start a second loop and by `magi run` / `magi review`
3799/// deciding whether to hand a task to the loop. A claim file proves nothing
3800/// here: whether a claim succeeds says nothing about whether its owner lives.
3801#[must_use]
3802pub fn foreign_loop(
3803    reading: Option<&Reading>,
3804    now: Timestamp,
3805    own_pid: u32,
3806) -> Option<Option<u32>> {
3807    let reading = reading.filter(|r| r.running(now))?;
3808    match reading.pid {
3809        Some(pid) if pid == own_pid => None,
3810        pid => Some(pid),
3811    }
3812}
3813
3814/// Run one task this process has claimed, in this process, through exactly the
3815/// attempt a daemon would make: the same starter choice (start, resume,
3816/// review), the same `Task::start` / `settle` transitions, attempt counting,
3817/// quota refund and parking. No second dispatcher - `magi run` and `magi
3818/// review` call this when no daemon is alive.
3819///
3820/// The caller holds the [`Queue::claim`] for the whole call, which is what
3821/// keeps a daemon that starts meanwhile from taking the task.
3822///
3823/// The one deliberate difference from the loop: a task the attempt leaves
3824/// runnable (failed with attempts to spare, or requeued) is **held** instead.
3825/// Nobody asked for a retry, and a daemon starting later must not spend agent
3826/// calls re-running a hand-started task behind the operator's back;
3827/// `magi task release` is the explicit retry.
3828pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
3829    let status = Arc::new(Mutex::new(Status::new()));
3830    let stop = Stop::new();
3831    attempt(
3832        opts,
3833        queue,
3834        &status,
3835        &stop,
3836        crate::graph::Pause::new(),
3837        task,
3838    )
3839    .await;
3840    // A run parked on the owner's word about a withheld PR title/body has no
3841    // daemon to finish it. Nobody else will enforce `answer_timeout`, so wait
3842    // here with the claim still held, and resume once the question is settled
3843    // (answered, or abandoned at its deadline -> the neutral text).
3844    // A rejected reply files one more question (the gate asks at most twice),
3845    // so after a resume the run may be waiting again: keep going, with a fresh
3846    // limit for the new question. `resumes` bounds it even if a resume parks
3847    // without asking anything new.
3848    let mut resumes = 0;
3849    while resumes < MAX_WITHHELD_RESUMES {
3850        let Some(timeout) = withheld_text_wait(task) else {
3851            break;
3852        };
3853        eprintln!(
3854            "waiting for the owner's answer on a withheld pull request text \
3855             (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
3856        );
3857        // The deadline abandons the question itself; the extra margin only
3858        // covers an abandon that could not be saved.
3859        let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
3860        let ready = loop {
3861            match land_resume_state(task) {
3862                LandResume::StillWaiting if std::time::Instant::now() < limit => {
3863                    tokio::time::sleep(WITHHELD_POLL).await;
3864                }
3865                LandResume::Ready => break true,
3866                _ => break false,
3867            }
3868        };
3869        if !ready {
3870            break;
3871        }
3872        resumes += 1;
3873        attempt(
3874            opts,
3875            queue,
3876            &status,
3877            &stop,
3878            crate::graph::Pause::new(),
3879            task,
3880        )
3881        .await;
3882    }
3883    hold_if_runnable(queue, task);
3884}
3885
3886/// Resumes an in-process run makes for withheld-text questions: the gate asks
3887/// at most twice, plus one for a resume that asks nothing new.
3888const MAX_WITHHELD_RESUMES: u32 = 3;
3889
3890/// How often an in-process run rechecks its withheld-text question.
3891const WITHHELD_POLL: Duration = Duration::from_secs(15);
3892
3893/// The `answer_timeout` (seconds) of the task's last run when that run is
3894/// parked on an unresolved withheld-text question; `None` otherwise.
3895fn withheld_text_wait(task: &Task) -> Option<u64> {
3896    let id = task.runs.last()?;
3897    let s = RunState::load(id).ok()?;
3898    (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
3899        .then_some(s.config.graph.answer_timeout)
3900}
3901
3902/// The quota losses `after` holds that `before` did not: what one execution
3903/// suffered, as opposed to the run's history.
3904///
3905/// Compared by value rather than by length or position because
3906/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
3907/// the vector can shrink and shift under a resume. A retried seat that hits
3908/// quota again is a `push` with a new `at`, so it shows up as new here.
3909/// `reclaim` deliberately keeps reading the whole history: after a crash there
3910/// is no attempt boundary to diff against.
3911fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
3912    after
3913        .iter()
3914        .filter(|q| !before.contains(q))
3915        .cloned()
3916        .collect()
3917}
3918
3919/// When the loop-wide quota cooldown should end, given this attempt's losses;
3920/// `None` when there were none. Reset-hint parsing and the cap live here.
3921fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
3922    if quota.is_empty() {
3923        return None;
3924    }
3925    let with_hint = quota.iter().find(|q| q.reset.is_some());
3926    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
3927    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
3928    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
3929    Some(
3930        now.checked_add(jiff::SignedDuration::from_secs(secs))
3931            .unwrap_or(Timestamp::MAX),
3932    )
3933}
3934
3935/// An explicit task count must agree with a run before any resume.
3936fn implementers_match(task: &Task, state: &RunState) -> bool {
3937    task.replacement.as_ref().map_or_else(
3938        || {
3939            task.implementers()
3940                .is_none_or(|n| n == state.config.graph.implementers)
3941        },
3942        |replacement| {
3943            state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
3944                && state.config.graph.implementers == 1
3945        },
3946    )
3947}
3948
3949/// Never resume or take over candidate work built for a different seat count.
3950fn starter_with_implementers(
3951    task: &Task,
3952    previous: Option<&RunState>,
3953    proposed: Starter,
3954) -> Starter {
3955    if previous.is_some_and(|s| !implementers_match(task, s)) {
3956        task.review_of
3957            .as_ref()
3958            .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
3959    } else {
3960        proposed
3961    }
3962}
3963
3964/// Apply this task's explicit count to the new attempt, without changing defaults.
3965fn apply_task_implementers(config: &mut Config, task: &Task) {
3966    if let Some(n) = task.implementers() {
3967        config.graph.implementers = n;
3968    }
3969}
3970
3971/// [`prepare`] for one task: its own `--config` and command-line overrides
3972/// (`Task::overrides`, filed by `magi run` / `magi review`) take precedence
3973/// over the loop's, so handing a hand-started task to a daemon changes nothing
3974/// about what it does.
3975fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
3976    let Some(o) = &task.overrides else {
3977        return prepare(repo, opts);
3978    };
3979    // A task filed by `magi run` / `magi review` was configured by that
3980    // command line alone: the loop's own `--config` / `--merge` must not leak
3981    // in, or the same command would behave differently with a loop alive.
3982    let own = Opts {
3983        config: o.config.clone(),
3984        merge: None,
3985        ..opts.clone()
3986    };
3987    let mut config = prepare(repo, if o.inherit_daemon_options { opts } else { &own })?;
3988    o.apply(&mut config);
3989    Ok(config)
3990}
3991
3992/// Load the config for a task's repository, with the merge override applied.
3993fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
3994    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
3995    if let Some(mode) = &opts.merge {
3996        config.merge.mode = merge_mode(mode)?;
3997    }
3998    Ok(config)
3999}
4000
4001/// Prune the shared build cache back under its cap at a safe boundary
4002/// between runs, so a queue that never empties - and so never reaches
4003/// [`poll`]'s fully-idle branch, where the ordinary [`janitor`] pass lives -
4004/// does not leave the cache to grow unchecked for as long as the backlog
4005/// lasts.
4006///
4007/// Called from [`poll`] only when `stop.busy_now()` is already `false`: the
4008/// same liveness fact the idle branch's own janitor call rests on - no run
4009/// this daemon spawned is still mid-compile - so pruning here races nothing.
4010/// The caller must not call this while a run is in flight; there is no
4011/// second `busy_now()` check inside this function, on purpose, because there
4012/// is nothing left to check that `busy_now()` has not already answered.
4013///
4014/// A stop that has already been asked for *is* checked here, for a different
4015/// reason. [`clean::prune_cache_if_over_limit`] walks the whole cache
4016/// synchronously before it decides anything, so the poll loop cannot get back
4017/// to its own `stopped()` test until that walk is over — and a loop already
4018/// on its way out must not make the operator wait out housekeeping it is
4019/// about to stop needing. This is the same call the idle branch makes when it
4020/// rechecks `stop.stopped()` after its wait before reaching [`janitor`], and
4021/// it matters more here: `busy_now()` is false throughout, so
4022/// [`Stop::finishing`] would report a stop as already landed while the walk
4023/// still held the loop. Nothing is lost by skipping — the cap is a standing
4024/// policy, and the next daemon's startup pass measures the same cache.
4025///
4026/// Rate-limited by [`CACHE_CHECK_INTERVAL_SECS`] rather than run on every
4027/// poll: a busy loop reaches this the instant one run's `InFlightGuard` drops
4028/// and the next has not yet claimed a task, which can be every few
4029/// milliseconds, and re-walking a multi-gigabyte cache that often would cost
4030/// more than the growth it is guarding against.
4031async fn maybe_prune_cache_between_runs(
4032    repo: &Path,
4033    opts: &Opts,
4034    home: &Path,
4035    stop: &Stop,
4036    last_checked: &mut Option<Timestamp>,
4037    now: Timestamp,
4038) {
4039    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
4040        return;
4041    }
4042    *last_checked = Some(now);
4043    let cfg = match prepare(repo, opts) {
4044        Ok(cfg) => cfg,
4045        Err(e) => {
4046            tracing::warn!("cache check: no config: {e:#}");
4047            return;
4048        }
4049    };
4050    match clean::prune_cache_if_over_limit(&cfg, home) {
4051        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
4052            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
4053            pruned.files,
4054            pruned.freed
4055        ),
4056        Ok(_) => {}
4057        Err(e) => {
4058            tracing::warn!("housekeep: prune cache: {e:#}");
4059            notices::raise_in(
4060                home,
4061                Notice::warn(
4062                    "housekeep:cache",
4063                    "Pruning the shared build cache failed; disk usage may keep growing.",
4064                ),
4065            );
4066        }
4067    }
4068}
4069
4070/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
4071/// now, given when it last did (if ever). Pure, so the cadence is asserted
4072/// directly rather than by waiting out real minutes in a test.
4073fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
4074    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
4075}
4076
4077/// The disk janitor, with its housekeeping logged rather than fatal.
4078///
4079/// Called only at the loop's idle points, for the reason the caller documents:
4080/// a prune racing a live compile would delete files mid-build. The config is
4081/// re-read on every call because the repository that just ran may not be the
4082/// daemon's own default, and the cache directory is a repository fact.
4083///
4084/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
4085/// and [`crate::run::default_worktree_root`] read here, for the same reason
4086/// [`drive`] takes its queue and status file rather than resolving them: a
4087/// test driving the loop must not reach through to the operator's real home
4088/// or worktree bay just because the janitor runs on every idle tick.
4089/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
4090/// to get wrong silently - a test's `home` was already isolated, but nothing
4091/// exercised the parameter next to it, so a real worktree bay stayed wired in
4092/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
4093/// it for real, every test in this file that drives the loop at all started
4094/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
4095async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
4096    let cfg = match prepare(repo, opts) {
4097        Ok(cfg) => cfg,
4098        Err(e) => {
4099            tracing::warn!("housekeep: no config: {e:#}");
4100            return;
4101        }
4102    };
4103    // A run's own worktree lives under `config.graph.worktree_root` when the
4104    // repository sets one - the same precedence `RunState::worktree_root`
4105    // uses - and `worktrees_root` only stands in for the *default* an
4106    // unconfigured repository resolves to (see this function's own
4107    // parameter, or the test fixture wiring one to a fake path). Housekeeping
4108    // that always swept the default regardless of this override would never
4109    // see, and so never reclaim, a single worktree for a repository that
4110    // relocated them elsewhere.
4111    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
4112    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
4113    // Reported whenever there is anything to say, not only when `folded > 0`:
4114    // the incident this exists to prevent was 90 of 93 runs skipped and 0
4115    // folded, on every single pass, for months - a report gated on `folded`
4116    // would have stayed silent through every one of them.
4117    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
4118        let mut extra = Vec::new();
4119        if out.unreadable > 0 {
4120            extra.push(format!("{} unreadable", out.unreadable));
4121        }
4122        if out.orphaned_worktrees > 0 {
4123            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
4124        }
4125        let detail = if extra.is_empty() {
4126            String::new()
4127        } else {
4128            format!(" ({})", extra.join(", "))
4129        };
4130        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
4131    }
4132    if out.external_merges_recorded > 0 {
4133        tracing::info!(
4134            "housekeep: recorded {} run(s) as merged externally",
4135            out.external_merges_recorded
4136        );
4137    }
4138    if out.stale_pr_states_repaired > 0 {
4139        tracing::info!(
4140            "housekeep: rewrote {} run record(s) whose pull request had already settled",
4141            out.stale_pr_states_repaired
4142        );
4143    }
4144    if out.cache_files > 0 {
4145        tracing::info!(
4146            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
4147            out.cache_files,
4148            out.cache_freed
4149        );
4150    }
4151    if out.questions_abandoned > 0 {
4152        tracing::info!(
4153            "housekeep: abandoned {} question(s) left open by a finished run",
4154            out.questions_abandoned
4155        );
4156    }
4157}
4158
4159/// Run [`triage::run_once`] and log whatever it did, the same "only when
4160/// there is something to say" rule [`janitor`] follows for its own report.
4161///
4162/// Called at the same idle points as [`janitor`] - once per full poll
4163/// interval, never mid-attempt - for the same reason: it is not liveness
4164/// critical, and a task's own `hold_reason` string is the one thing this
4165/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
4166/// tick for no benefit.
4167async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
4168    let questions = Questions::at(home.join("questions"));
4169    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
4170    if report.is_empty() {
4171        return;
4172    }
4173    if !report.quarantined.is_empty() {
4174        tracing::info!(
4175            "triage: held {} blocked task(s) whose blocked-on task or \
4176             question no longer exists: {}",
4177            report.quarantined.len(),
4178            report.quarantined.join(", ")
4179        );
4180    }
4181    if !report.resumed.is_empty() {
4182        tracing::info!(
4183            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
4184            report.resumed.len(),
4185            report.resumed.join(", ")
4186        );
4187    }
4188    if !report.asked.is_empty() {
4189        tracing::info!(
4190            "triage: asked about {} held task(s): {}",
4191            report.asked.len(),
4192            report.asked.join(", ")
4193        );
4194    }
4195    if !report.answered.is_empty() {
4196        tracing::info!(
4197            "triage: applied {} operator answer(s): {}",
4198            report.answered.len(),
4199            report.answered.join(", ")
4200        );
4201    }
4202}
4203
4204/// The free-space gate: what stands between this task and a new run, if
4205/// anything. `Some(reason)` holds the task; `None` lets it start.
4206///
4207/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
4208/// the operator opted out. A measurement failure is a gate, not a pass: both
4209/// sides of "cannot tell" are served by not starting.
4210fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
4211    disk_gate_with(repo, config, crate::disk::free_bytes)
4212}
4213
4214/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
4215/// test can assert the exact wiring `attempt` runs - config's threshold in,
4216/// task-holding reason out - without asking the real machine's disk anything.
4217fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
4218    repo: &Path,
4219    config: &Config,
4220    free_bytes: F,
4221) -> Option<String> {
4222    let min = config.disk.min_free_bytes;
4223    if min == 0 {
4224        return None;
4225    }
4226    match free_bytes(repo) {
4227        Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
4228        Err(e) => Some(crate::disk::unmeasured_in(repo, &e, &config.graph.language)),
4229    }
4230}
4231
4232/// How long to wait before offering another task when a run lost a seat to a
4233/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
4234/// could read, or carried nothing at all. Long enough that a quota outage
4235/// cannot burn through a whole backlog in the few seconds each doomed attempt
4236/// takes to fail; short enough that a quota which clears early is not left
4237/// idle for the fallback's sake.
4238const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
4239
4240/// Longest a parsed reset hint may push the wait out to. The hint comes from
4241/// the CLI's own words, not a contract, so a parsing slip that lands a day
4242/// away must not leave the loop asleep for a day.
4243const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
4244
4245/// How long [`poll`] should wait before offering the next task, after a run
4246/// lost at least one seat to a rate limit.
4247///
4248/// Pure and separate from the loop so the policy can be exercised without a
4249/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
4250/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
4251/// nothing to parse, or the parsed time has already passed; `cap` bounds how
4252/// far a parsed hint is trusted to push the wait out.
4253fn quota_wait(
4254    reset_at: Option<Timestamp>,
4255    now: Timestamp,
4256    fallback: Duration,
4257    cap: Duration,
4258) -> Duration {
4259    match reset_at {
4260        Some(at) if at > now => {
4261            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
4262            Duration::from_secs(secs).min(cap)
4263        }
4264        _ => fallback,
4265    }
4266}
4267
4268/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
4269///
4270/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
4271/// explains why parsing it exactly "would be a bug factory" — so this only
4272/// recognises the shapes actually observed in the wild, and returns `None`
4273/// for anything else rather than guess at a format nobody has seen.
4274///
4275/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
4276/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
4277/// said it, not from whenever this loop happens to read it: anchoring on `now`
4278/// would push the reset later on every read and would read an already-elapsed
4279/// reset as still in the future. (A long hint is still clamped by
4280/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
4281fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
4282    parse_reset_hint_zoned(text, now)
4283        .or_else(|| parse_reset_hint_dated(text))
4284        .or_else(|| parse_reset_hint_relative(text, recorded))
4285}
4286
4287/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
4288/// optional but at least one required, in that order. A bare number or any
4289/// unknown unit is refused.
4290fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
4291    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
4292    let mut rest = rest.trim();
4293    if rest.is_empty() {
4294        return None;
4295    }
4296    let mut total: i64 = 0;
4297    let mut matched = false;
4298    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
4299        if let Some((digits, tail)) = rest.split_once(unit)
4300            && !digits.is_empty()
4301            && digits.bytes().all(|b| b.is_ascii_digit())
4302        {
4303            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
4304            rest = tail;
4305            matched = true;
4306        }
4307    }
4308    if !rest.is_empty() || !matched {
4309        return None;
4310    }
4311    recorded
4312        .checked_add(jiff::SignedDuration::from_secs(total))
4313        .ok()
4314}
4315
4316/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
4317/// case-insensitive) into a 24-hour hour and minute. Shared by every
4318/// reset-hint shape below.
4319fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
4320    let clock = clock.trim().to_lowercase();
4321    let (digits, pm) = clock
4322        .strip_suffix("am")
4323        .map(|d| (d, false))
4324        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
4325    let (h, m) = digits.trim().split_once(':')?;
4326    let mut hour: i8 = h.trim().parse().ok()?;
4327    let minute: i8 = m.trim().parse().ok()?;
4328    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
4329        return None;
4330    }
4331    if pm && hour != 12 {
4332        hour += 12;
4333    } else if !pm && hour == 12 {
4334        hour = 0;
4335    }
4336    Some((hour, minute))
4337}
4338
4339/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
4340/// and a zone, never a date. A clock reading already past today is read as
4341/// tomorrow's: a CLI naming a same-day reset that has already gone by means
4342/// the window rolled over while nothing was watching.
4343fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
4344    let open = text.find('(')?;
4345    let close = text.rfind(')')?;
4346    if close <= open {
4347        return None;
4348    }
4349    let zone = text[open + 1..close].trim();
4350    let (hour, minute) = parse_12h_clock(&text[..open])?;
4351    let tz = jiff::tz::TimeZone::get(zone).ok()?;
4352    let candidate = now
4353        .to_zoned(tz)
4354        .with()
4355        .hour(hour)
4356        .minute(minute)
4357        .second(0)
4358        .millisecond(0)
4359        .microsecond(0)
4360        .nanosecond(0)
4361        .build()
4362        .ok()?;
4363    let mut at = candidate.timestamp();
4364    if at <= now {
4365        at += jiff::SignedDuration::from_hours(24);
4366    }
4367    Some(at)
4368}
4369
4370/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
4371/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
4372/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
4373/// "already past today" correction to make: the year already disambiguates
4374/// it. Scanned as a five-word window so it can be pulled out of the middle
4375/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
4376/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
4377/// any other timestamp with no zone attached.
4378fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
4379    let words: Vec<&str> = text.split_whitespace().collect();
4380    if words.len() < 5 {
4381        return None;
4382    }
4383    (0..=words.len() - 5)
4384        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
4385}
4386
4387/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
4388/// parenthesis right after the window is refused rather than ignored — it
4389/// reads as an explicit zone annotation on a shape that otherwise carries
4390/// none, and guessing UTC anyway would be exactly the silent misread this
4391/// module's parsing otherwise avoids.
4392fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
4393    if trailing.is_some_and(|next| next.starts_with('(')) {
4394        return None;
4395    }
4396    let month = month_number(window[0])?;
4397    let day_token = window[1].strip_suffix(',')?.to_lowercase();
4398    let day_digits = ["st", "nd", "rd", "th"]
4399        .iter()
4400        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
4401    let day: i8 = day_digits.parse().ok()?;
4402    let year_token = window[2];
4403    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
4404        return None;
4405    }
4406    let year: i16 = year_token.parse().ok()?;
4407    // The am/pm word carries the sentence's own trailing punctuation, e.g.
4408    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
4409    // reusing the same 12-hour clock reader the bracketed shape uses.
4410    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
4411    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
4412    let date = jiff::civil::Date::new(year, month, day).ok()?;
4413    let candidate = date
4414        .at(hour, minute, 0, 0)
4415        .to_zoned(jiff::tz::TimeZone::UTC)
4416        .ok()?;
4417    Some(candidate.timestamp())
4418}
4419
4420/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
4421/// case-insensitively, into a 1-based month number.
4422fn month_number(name: &str) -> Option<i8> {
4423    const NAMES: [&str; 12] = [
4424        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
4425    ];
4426    let lower = name.to_lowercase();
4427    NAMES
4428        .iter()
4429        .position(|n| *n == lower.as_str())
4430        .map(|i| i as i8 + 1)
4431}
4432
4433/// Resuming a `Blocked` run that already spent every review round its own
4434/// config allowed cannot make progress: `graph::Runner`'s review loop walks
4435/// `(reviews.len()+1)..=max_rounds`, which is empty once `reviews.len()` has
4436/// reached `max_rounds`, so `execute` would settle straight back to
4437/// `Blocked` without asking anyone anything. Read-only against a state this
4438/// build never mutates — `src/graph.rs` stays untouched — but without this
4439/// check, [`unfinished_run`] would keep reporting such a run as still
4440/// "unfinished", and `crate::conduct::Recovery::Requeue` (whose whole
4441/// promise is a fresh competition when a design needs to change) would
4442/// silently resume the exhausted run instead, spending an attempt on a
4443/// cycle that cannot change anything.
4444fn exhausted_review_budget(state: &RunState) -> bool {
4445    // A run whose task-head publication failed has nothing left to review:
4446    // resuming it only retries the publication, so it is never "exhausted".
4447    state.status == RunStatus::Blocked
4448        && !state.pr_publication_pending
4449        && state.reviews.len() >= state.config.graph.review_rounds
4450}
4451
4452/// This task's *most recent* run, if resuming it would actually make
4453/// progress. `short` is only for the warning's own message.
4454///
4455/// Only ever `runs.last()` — never a search back through older history.
4456/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
4457/// mint, oldest first, and every entry before the last one was already
4458/// superseded at the moment it was minted: the daemon only ever starts a new
4459/// run when the previous one was not worth resuming (unresumable, exhausted,
4460/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
4461/// opens a fresh review-only run alongside an older, already-failed
4462/// competition. Searching further back would let an old run that merely
4463/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
4464/// behind, say — get resumed instead of the fresh competition
4465/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
4466/// nothing asked to revisit.
4467///
4468/// Two runs paid for the "prefer resuming over restarting" half of this
4469/// lesson, which is why this still checks `runs.last()` rather than always
4470/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
4471/// task a moment later, duplicating two and a half hours of agent work. Then
4472/// b25f stalled on a judge that timed out and one that answered with no JSON
4473/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
4474/// **one second** later, buying three fresh implementations to reach the
4475/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
4476/// the second case: a stall is terminal, and its cheap recovery re-asks only
4477/// the absent seats. [`exhausted_review_budget`] is the other half: a run
4478/// that is technically `resumable()` but provably cannot progress must not
4479/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
4480/// no-op instead of the fresh competition it promises.
4481///
4482/// A load failure is warned about rather than silently read as "not
4483/// resumable": the alternative is exactly what let a schema mismatch on run
4484/// `eba2` fall through to a full re-competition with nobody told why.
4485/// `crate::conduct` is what actually offers a better answer than
4486/// `Runner::start` here (see `Recovery::Review`), once this task's next
4487/// failure shows it up as `held`/`failed` with the run state unreadable.
4488fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
4489    unfinished_run_with(runs, short, RunState::load)
4490}
4491
4492/// [`unfinished_run`] with an injected state reader. Tests provide their
4493/// fixtures directly rather than touching the process-global run home.
4494fn unfinished_run_with<F>(runs: &[String], short: &str, load: F) -> Option<String>
4495where
4496    F: FnOnce(&str) -> Result<RunState>,
4497{
4498    let id = runs.last()?;
4499    match load(id) {
4500        // A run some process is driving right now is not "unfinished" in the
4501        // sense of waiting to be picked up: a run started by hand is in
4502        // `runs` while it is still executing, and resuming it here
4503        // would put a second driver on the same worktrees.
4504        Ok(s)
4505            if s.status.resumable()
4506                && !s.released()
4507                && !exhausted_review_budget(&s)
4508                && s.liveness(false) != crate::run::Liveness::Live =>
4509        {
4510            Some(id.clone())
4511        }
4512        Ok(_) => None,
4513        Err(e) => {
4514            tracing::warn!("could not read run {id} for task {short}: {e:#}");
4515            None
4516        }
4517    }
4518}
4519
4520/// Is `task` a parked (or, from an older build, failed) task whose last run was parked at a node boundary, so
4521/// that [`attempt`] will resume it on its own?
4522///
4523/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
4524/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
4525/// injected reader like its sibling. An unreadable run is not awaiting
4526/// anything: it keeps going to the conductor as before.
4527fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
4528where
4529    F: FnOnce(&str) -> Result<RunState>,
4530{
4531    // `Failed` stays: a record an older build wrote for a parked run.
4532    if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
4533        || task.fresh_start
4534        || task.review_branch.is_some()
4535    {
4536        return false;
4537    }
4538    let Some(id) = task.runs.last() else {
4539        return false;
4540    };
4541    load(id).is_ok_and(|s| {
4542        s.parked && s.status.resumable() && !s.released() && !exhausted_review_budget(&s)
4543    })
4544}
4545
4546/// Which of the three ways [`attempt`] can mint or continue a run this task
4547/// should use.
4548#[derive(Debug, Clone, PartialEq, Eq)]
4549enum Starter {
4550    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
4551    /// and that still exists.
4552    Review(String),
4553    /// `crate::graph::Runner::resume` on an unfinished run of this task.
4554    Resume(String),
4555    /// `crate::graph::Runner::start`: a fresh competition.
4556    Start,
4557}
4558
4559/// A selected public implementation overrides every historical candidate and pin.
4560fn selected_starter(
4561    selected: &crate::pr_recovery::Selection,
4562    previous: Option<&RunState>,
4563    unfinished: Option<&str>,
4564) -> Starter {
4565    if let Some(id) = unfinished
4566        && previous.is_some_and(|r| {
4567            r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
4568        })
4569    {
4570        Starter::Resume(id.to_owned())
4571    } else {
4572        Starter::Review(selected.branch.clone())
4573    }
4574}
4575
4576/// The owner's answer to this branch's divergence question, consumed from the
4577/// task so a later, different divergence asks again. The runner applies it
4578/// (see `Runner::review_taking_over`), after the earlier worktree is released.
4579fn take_divergence_answer(
4580    branch: &str,
4581    remote: &str,
4582    task: &mut Task,
4583) -> Option<crate::reconcile::Choice> {
4584    let summary = crate::reconcile::summary_for(branch, remote);
4585    let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
4586        (a.question == summary)
4587            .then(|| crate::reconcile::Choice::from_answer(&a.answer))
4588            .flatten()
4589            .map(|c| (i, c))
4590    })?;
4591    task.answers.remove(idx);
4592    Some(choice)
4593}
4594
4595/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
4596/// this attempt should use. Pure, and separate from [`attempt`], so the
4597/// routing itself is assertable without spawning a real graph or a git
4598/// process: `attempt`'s own `crate::git::branch_exists` call has already
4599/// happened by the time this is called.
4600///
4601/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
4602/// whose branch is gone falls all the way through to [`Starter::Start`], not
4603/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
4604/// old (likely `Blocked`) run in the first place, and a branch that vanished
4605/// out from under that choice is not evidence resuming it would fare better.
4606fn choose_starter(
4607    review_branch: Option<&str>,
4608    branch_exists: bool,
4609    unfinished: Option<&str>,
4610) -> Starter {
4611    match review_branch {
4612        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
4613        Some(_) => Starter::Start,
4614        None => match unfinished {
4615            Some(id) => Starter::Resume(id.to_owned()),
4616            None => Starter::Start,
4617        },
4618    }
4619}
4620
4621/// Consume a retained review only while its authored criteria still match.
4622fn take_review_branch(task: &mut Task, previous: Option<&RunState>) -> Option<String> {
4623    let branch = task.review_branch.take();
4624    let instruction = task.review_instruction.take();
4625    branch.filter(|branch| match &instruction {
4626        Some(authored) => *authored == task.instruction,
4627        // Legacy retained branches must agree with their prior run; only an
4628        // explicitly pinned review can proceed without recoverable provenance.
4629        None => previous.map_or_else(
4630            || task.review_of.as_ref() == Some(branch),
4631            |run| compatible_run_instruction(run, task),
4632        ),
4633    })
4634}
4635
4636/// A current explicit pin can select an otherwise incompatible run. Edits
4637/// and subsequent approvals invalidate pins selected for earlier criteria.
4638fn may_resume_run(run: &RunState, task: &Task) -> bool {
4639    task.resume_override
4640        .as_ref()
4641        .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
4642        || compatible_run_instruction(run, task)
4643}
4644
4645/// Review scaffolding is execution context, not evidence of an operator edit.
4646pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
4647    if let Some(authored) = &run.task_instruction {
4648        return compatible_instruction(authored, task);
4649    }
4650    if compatible_instruction(&run.instruction, task) {
4651        return true;
4652    }
4653    // Recognize only the existing generated review shapes on legacy runs.
4654    // Ordinary authored text with a similar heading is left intact.
4655    if run.reviewed_commits.is_some() {
4656        if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
4657            return strip_answers_block(authored, task).trim() == task.instruction.trim();
4658        }
4659        if let Some(branch) = &task.review_of {
4660            let canonical = format!(
4661                "Review the branch `{branch}` (review-only: no implementation, no judging)."
4662            );
4663            let generated = format!(
4664                "Review the work already on branch `{branch}`. There is no task statement: what the change claims to do is whatever its commits say.\n\n"
4665            );
4666            return task.instruction == canonical && run.instruction.starts_with(&generated);
4667        }
4668    }
4669    false
4670}
4671
4672/// Compare authored instructions, excluding answer blocks appended by the daemon.
4673pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
4674    strip_answers_block(old, task) == task.instruction
4675}
4676
4677/// Which repository a task runs in. A task that names none — the normal case
4678/// for one filed from a phone — runs in the daemon's own default.
4679fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
4680    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
4681        return fallback.to_path_buf();
4682    }
4683    task.repo.clone()
4684}
4685
4686/// The header [`append_answers`] appends operator answers under. Shared with
4687/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
4688/// rather than grown a new block on every resume.
4689const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
4690
4691/// Render the first `count` answers in the block appended to an instruction.
4692fn answers_block(task: &Task, count: usize) -> String {
4693    let mut s = ANSWERS_HEADER.to_owned();
4694    for a in &task.answers[..count] {
4695        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
4696    }
4697    s
4698}
4699
4700/// Render the approval independently of transient task state, so historical
4701/// suffixes remain recognizable after another explicit release.
4702fn resumption_block(r: &crate::queue::Resumption) -> String {
4703    format!(
4704        "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
4705         Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
4706        r.generation, r.at, r.instruction, r.answers_through,
4707    )
4708}
4709
4710/// Append audit answers and the latest explicit approval to the instruction.
4711fn append_answers(base: &str, task: &Task) -> String {
4712    let mut s = base.to_owned();
4713    if !task.answers.is_empty() {
4714        s.push_str(&answers_block(task, task.answers.len()));
4715    }
4716    if let Some(r) = &task.resumption {
4717        s.push_str(&resumption_block(r));
4718    }
4719    s
4720}
4721
4722/// Drop the prior answer block only when it is exactly the suffix this task
4723/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
4724/// the task author is ordinary instruction text, not a block to remove.
4725fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
4726    let mut instruction = instruction;
4727    for approval in task
4728        .resumption
4729        .iter()
4730        .chain(task.resumption_history.iter().rev())
4731    {
4732        if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
4733            instruction = base;
4734            break;
4735        }
4736    }
4737    for count in (1..=task.answers.len()).rev() {
4738        let block = answers_block(task, count);
4739        if let Some(base) = instruction.strip_suffix(&block) {
4740            return base;
4741        }
4742    }
4743    instruction
4744}
4745
4746/// The instruction handed to `Runner::start`: the task's own text, plus any
4747/// operator answers `crate::conduct` collected for it (see
4748/// [`Task::answers`]), so a decision the operator actually made reaches the
4749/// implementers rather than only clearing the block that was waiting on it.
4750///
4751/// Appended rather than merged into [`Task::instruction`] itself, so the
4752/// task's own record stays exactly what its author wrote.
4753fn instruction_for(task: &Task) -> String {
4754    append_answers(&task.instruction, task)
4755}
4756
4757/// The instruction a resumed run should carry on with: whatever it already
4758/// had, refreshed with the task's *current* operator answers.
4759///
4760/// A resumable run's own `RunState::instruction` predates any answer
4761/// `crate::conduct` collects after the run parks, so resuming it unchanged —
4762/// the behaviour before this function existed — silently drops the very
4763/// decision the operator made to unblock it. Re-stripping any block this
4764/// function appended on an earlier resume before re-appending the current
4765/// list (rather than blindly appending again) is what keeps a task resumed
4766/// three times over three answered questions from carrying the same answer
4767/// three times.
4768fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
4769    append_answers(strip_answers_block(old_instruction, task), task)
4770}
4771
4772/// Preserve the producer's verified boundary and target, independent of prose.
4773fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
4774    let failure = error.downcast_ref::<crate::config::ConfigFailure>();
4775    task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
4776    if let Some(cause) = task.hold_notice_cause.as_mut() {
4777        cause.target = failure.map(|f| f.target.clone());
4778    }
4779}
4780
4781#[derive(Debug, thiserror::Error)]
4782#[error("attachment `{name}` is recorded on the task but {path} is missing")]
4783struct MissingAttachment {
4784    name: String,
4785    path: PathBuf,
4786}
4787
4788/// The task's attachments as absolute paths, each checked to still exist.
4789fn task_attachments(
4790    queue: &Queue,
4791    task: &Task,
4792) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
4793    let paths = queue.attachment_paths(task);
4794    for (name, path) in task.attachments.iter().zip(&paths) {
4795        if !path.is_file() {
4796            return Err(MissingAttachment {
4797                name: name.clone(),
4798                path: path.clone(),
4799            });
4800        }
4801    }
4802    Ok(paths)
4803}
4804
4805/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
4806/// answers before handing it to `Runner` — the actual boundary between
4807/// [`choose_starter`]'s routing and the graph, factored out so it is
4808/// assertable without a real repository, git branch, or agent CLI.
4809///
4810/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
4811/// instruction from the reviewed branch's own commit log because there is no
4812/// task statement to speak of for hand-written work, and splicing operator
4813/// answers into that text would contradict the very message it sends
4814/// reviewers ("there is no task statement").
4815fn prepare_instruction(
4816    starter: &Starter,
4817    old_instruction: Option<&str>,
4818    task: &Task,
4819) -> Option<String> {
4820    match starter {
4821        Starter::Start => Some(instruction_for(task)),
4822        Starter::Resume(_) => Some(resumed_instruction(
4823            old_instruction.expect("a resumed run always has a prior instruction"),
4824            task,
4825        )),
4826        Starter::Review(_) => None,
4827    }
4828}
4829
4830/// Persist a transition. A queue write failure is logged rather than fatal: the
4831/// run already happened, and taking the daemon down would only add a lost
4832/// backlog to a full disk.
4833fn record(queue: &Queue, task: &mut Task) {
4834    if let Err(e) = queue.put(task) {
4835        tracing::error!("could not record task {}: {e:#}", task.short());
4836        let notice = Notice::error(
4837            "loop:record",
4838            "The loop could not save a task's state; check the disk.",
4839        )
4840        .link(Link::Task {
4841            id: task.id.clone(),
4842        });
4843        // The queue lives at `<home>/queue`, so its parent is the home.
4844        match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
4845            Some(home) => notices::raise_in(home, notice),
4846            None => notices::raise(notice),
4847        }
4848    }
4849}
4850
4851/// Every runnable task, in the order the loop should try them.
4852///
4853/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
4854/// tail exists so that a claim somebody else holds costs the loop the next
4855/// candidate rather than a whole poll interval of idleness.
4856fn runnable(queue: &Queue) -> Vec<Task> {
4857    let mut tasks: Vec<Task> = queue
4858        .list()
4859        .into_iter()
4860        .filter(|t| t.status.runnable())
4861        .collect();
4862    tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
4863    tasks
4864}
4865
4866/// Why a run ended where it did, in one line, for [`Task::last_error`].
4867///
4868/// A stalled run names the seats the quota took out: "out of quota" is not
4869/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
4870/// agent to replace or which plan to top up.
4871///
4872/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
4873/// purpose: unlike `label`'s other callers (an internal log line, an
4874/// already-a-bug fallback message), this string becomes `Task::last_error`
4875/// verbatim, which the phone renders in the same alarm-styled box an
4876/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
4877/// `.err` styling. A bare `verified_noop` there would read exactly like the
4878/// failure this whole feature exists to tell apart from one.
4879fn describe(state: &RunState) -> String {
4880    let p = phrases(&state.config.graph.language);
4881    let mut detail = if state.status == RunStatus::Stalled {
4882        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
4883        seats.sort_unstable();
4884        seats.dedup();
4885        if seats.is_empty() {
4886            p.quorum_lost.to_owned()
4887        } else {
4888            format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
4889        }
4890    } else {
4891        format!("{}{}", p.run_ended, state.status.display_label())
4892    };
4893    if let Some(last) = state.events.last() {
4894        // The review loop's "never answered" stop is the one event worth
4895        // translating; it is recognised from structured state, not by
4896        // matching the English event text (which stays as recorded).
4897        let unanswered = state
4898            .reviews
4899            .last()
4900            .filter(|r| {
4901                state.status == RunStatus::Blocked
4902                    && last.node == "review"
4903                    && r.incomplete()
4904                    && r.blocking == 0
4905                    && r.round == state.config.graph.review_rounds
4906                    && r.e2e.iter().all(crate::run::CommandOutcome::ok)
4907            })
4908            .map(|r| (r.expected - r.answered, r.round));
4909        match unanswered {
4910            Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
4911                detail.push_str(&format!(
4912                    " ({}: {})",
4913                    last.node,
4914                    (p.reviewers_never_answered)(missing, rounds)
4915                ));
4916            }
4917            _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
4918        }
4919    }
4920    detail.push_str(&format!(" [run {}]", state.id));
4921    detail
4922}
4923
4924/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
4925///
4926/// The task file lives in the backlog indefinitely; a diagnostic is an
4927/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
4928/// stay small regardless of how much a gate command or a candidate printed.
4929const DIAGNOSTIC_MAX: usize = 4_000;
4930
4931/// Tail kept from a single failing command's output inside a diagnostic.
4932/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
4933/// pointer for a human deciding whether to go read the full artifact by hand,
4934/// not a replacement for reading it.
4935const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
4936
4937/// Assemble a bounded diagnostic excerpt from a held task's own run, so
4938/// `magi task show` says more than the one-line reason in [`describe`].
4939///
4940/// The one-liner answers "where did the run stop"; this answers "what would a
4941/// human have found opening `artifacts/` by hand" — the point of the whole
4942/// feature is the case that one-liner actively misleads on: a run held as "no
4943/// candidate produced a change" can mean the implementer actually finished
4944/// the task (opened a PR, merged it, tagged a release) and only left a clean
4945/// local worktree behind, which reads as "nothing happened" unless someone
4946/// goes and reads what the agent actually said. `None` when the run carries
4947/// none of the three shapes this recognises — an ordinary run held for
4948/// something not diagnosable from `RunState` alone still explains itself
4949/// through `Task::last_error`.
4950fn diagnostic(state: &RunState) -> Option<String> {
4951    let mut parts: Vec<String> = Vec::new();
4952
4953    // Gate failure: which check(s), and the tail of what each printed.
4954    for o in state.gate.iter().filter(|o| !o.ok()) {
4955        parts.push(format!(
4956            "gate `{}` failed ({:?}):\n{}",
4957            o.command,
4958            o.code,
4959            crate::run::tail(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
4960        ));
4961    }
4962
4963    // The land loop gave up because the fixer declined while checks were
4964    // still red: the message already names them (see `land::run`).
4965    if let Some(last) = state
4966        .events
4967        .iter()
4968        .rev()
4969        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
4970    {
4971        parts.push(last.message.clone());
4972    }
4973
4974    // No viable candidate: every implementer's own final word, sanitized the
4975    // same way a judge would have read it, so a run that actually finished
4976    // the job does not read as an unexplained failure. A verified no-op is
4977    // called out ahead of its own summary and apart from an ordinary
4978    // failure's `why` — this is the one candidate shape whose diagnostic a
4979    // human is expected to actually judge, not just skim.
4980    if state.viable().is_empty() {
4981        for c in &state.candidates {
4982            if let Some(evidence) = &c.verified_noop {
4983                parts.push(format!(
4984                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
4985                    c.label
4986                ));
4987            } else if !c.summary.trim().is_empty() {
4988                parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
4989            } else if let Some(why) = &c.failed {
4990                parts.push(format!("candidate {}: {why}", c.label));
4991            }
4992        }
4993    }
4994
4995    if parts.is_empty() {
4996        return None;
4997    }
4998    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
4999    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
5000    // back slightly over. Leave it enough room to always land under the
5001    // limit.
5002    Some(crate::run::tail(
5003        &parts.join("\n\n"),
5004        DIAGNOSTIC_MAX.saturating_sub(100),
5005    ))
5006}
5007
5008/// Stable lower-case name for a run status, for an internal log line and the
5009/// "graph stopped without reaching a terminal status" bug message in
5010/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
5011/// doc for why that one reads [`RunStatus::display_label`] instead. One
5012/// definition of a status's name, on the type that owns it: this table used
5013/// to live here as a second copy, and a status renamed in one place would
5014/// have gone on reading correctly in the other.
5015fn label(status: RunStatus) -> &'static str {
5016    status.as_str()
5017}
5018
5019/// Parse a merge mode override.
5020pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
5021    match mode {
5022        "none" => Ok(MergeMode::None),
5023        "local" => Ok(MergeMode::Local),
5024        "pr" => Ok(MergeMode::Pr),
5025        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
5026    }
5027}
5028
5029/// Take the status lock, recovering from a poisoned one.
5030///
5031/// A panic elsewhere must not silently stop the heartbeat: the status is plain
5032/// data, and the worst a poisoned lock can hold is a stale timestamp.
5033fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
5034    mutex
5035        .lock()
5036        .unwrap_or_else(std::sync::PoisonError::into_inner)
5037}
5038
5039#[cfg(test)]
5040mod tests {
5041    use super::*;
5042    use crate::queue::{Source, TaskStatus};
5043    use crate::run::{Candidate, CommandOutcome};
5044    use pretty_assertions::assert_eq;
5045
5046    fn task() -> Task {
5047        Task::new(
5048            "add retries".to_owned(),
5049            "add retries".to_owned(),
5050            PathBuf::from("/repo"),
5051            Source::Human,
5052        )
5053    }
5054
5055    #[test]
5056    fn selected_public_head_overrides_historical_resume_and_pin() {
5057        let mut t = task();
5058        let mut old = run_state(RunStatus::Blocked);
5059        let selection = crate::pr_recovery::Selection {
5060            url: "url".into(),
5061            branch: format!("magi/task-{}", t.id),
5062            head: "a".repeat(40),
5063            instruction: t.instruction.clone(),
5064            approved_at: Timestamp::now(),
5065        };
5066        t.resume_override = Some(crate::queue::OperatorResume {
5067            pinned_run: Some(old.id.clone()),
5068            question_id: "choice".into(),
5069            at: Timestamp::now(),
5070            conductor_rehold: None,
5071            forced: false,
5072        });
5073        assert_eq!(
5074            selected_starter(&selection, Some(&old), Some(&old.id)),
5075            Starter::Review(selection.branch.clone())
5076        );
5077        old.pr_recovery = Some(selection.clone());
5078        assert_eq!(
5079            selected_starter(&selection, Some(&old), Some(&old.id)),
5080            Starter::Review(selection.branch.clone())
5081        );
5082        old.reviewed_commits = Some(vec!["implementation".into()]);
5083        assert_eq!(
5084            selected_starter(&selection, Some(&old), Some(&old.id)),
5085            Starter::Resume(old.id.clone())
5086        );
5087        let mut changed = selection.clone();
5088        changed.head = "b".repeat(40);
5089        assert_eq!(
5090            selected_starter(&changed, Some(&old), Some(&old.id)),
5091            Starter::Review(changed.branch)
5092        );
5093    }
5094
5095    #[test]
5096    fn candidate_transplant_failure_is_one_actionable_hold() {
5097        let dir = tempfile::tempdir().unwrap();
5098        let q = Queue::at(dir.path().join("queue"));
5099        let mut t = task();
5100        let mut state = run_state(RunStatus::Blocked);
5101        state.event("prep", "cannot apply referenced commit: conflict");
5102        state.prep_failure = Some("conflict".into());
5103        t.start(state.id.clone());
5104        finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
5105        assert_eq!(t.attempts, 1);
5106        assert_eq!(t.status, TaskStatus::Held);
5107        assert!(t.operator_held());
5108        assert!(!t.status.runnable());
5109        assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
5110        let first = t.chat_notice_key().unwrap();
5111        t.chat_notices.push(first.clone());
5112        t.release_operator("test", None);
5113        state.id = "another-unprepared-run".into();
5114        t.start(state.id.clone());
5115        finish_attempt(
5116            3,
5117            &q,
5118            &mut t,
5119            &state,
5120            &[],
5121            Err(anyhow::anyhow!("still conflicts")),
5122        );
5123        assert_eq!(
5124            t.chat_notice_key().as_ref(),
5125            Some(&first),
5126            "no work happened"
5127        );
5128        t.release_operator("test", None);
5129        state.prep_failure = None;
5130        state.status = RunStatus::Failed;
5131        state.begin_pass();
5132        t.start(state.id.clone());
5133        finish_attempt(
5134            1,
5135            &q,
5136            &mut t,
5137            &state,
5138            &[],
5139            Err(anyhow::anyhow!("new gate failure")),
5140        );
5141        let failure = t.chat_notice_key().unwrap();
5142        assert_ne!(failure, first, "approved recovery reached a real failure");
5143        t.release_operator("test", None);
5144        state.begin_pass();
5145        t.start(state.id.clone());
5146        finish_attempt(
5147            1,
5148            &q,
5149            &mut t,
5150            &state,
5151            &[],
5152            Err(anyhow::anyhow!("new failure on resume")),
5153        );
5154        assert_ne!(
5155            t.chat_notice_key().as_ref(),
5156            Some(&failure),
5157            "a new settled pass"
5158        );
5159    }
5160
5161    #[test]
5162    fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
5163        for source in ["cli", "web"] {
5164            let mut t = task();
5165            let mut run = run_state(RunStatus::Blocked);
5166            run.instruction = "Run A original criteria".into();
5167            run.task_instruction = Some(run.instruction.clone());
5168            t.start(run.id.clone());
5169            t.release_operator("choice", Some("resume-question"));
5170            t.resume_override = Some(crate::queue::OperatorResume {
5171                question_id: "resume-question".into(),
5172                at: Timestamp::now(),
5173                conductor_rehold: None,
5174                forced: true,
5175                pinned_run: Some(run.id.clone()),
5176            });
5177            t.hold_machine(Some("not enough free space to start a run".into()));
5178            let mut unchanged = t.clone();
5179            unchanged
5180                .edit("title changed".into(), unchanged.instruction.clone())
5181                .unwrap();
5182            unchanged.release_operator(source, None);
5183            assert_eq!(
5184                unchanged
5185                    .resume_override
5186                    .as_ref()
5187                    .unwrap()
5188                    .pinned_run
5189                    .as_deref(),
5190                Some(run.id.as_str())
5191            );
5192            assert!(!compatible_run_instruction(&run, &unchanged));
5193            assert!(may_resume_run(&run, &unchanged));
5194
5195            t.edit(
5196                "approved recovery".into(),
5197                "Reuse measured PR head B; fix Clippy; review".into(),
5198            )
5199            .unwrap();
5200            assert!(t.resume_override.is_none());
5201            t.release_operator(source, None);
5202            let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
5203            assert!(reloaded.resume_override.is_none());
5204            assert!(!may_resume_run(&run, &reloaded));
5205            let unfinished =
5206                unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
5207                    .filter(|_| may_resume_run(&run, &reloaded));
5208            assert_eq!(
5209                choose_starter(None, false, unfinished.as_deref()),
5210                Starter::Start
5211            );
5212            assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
5213            assert_eq!(
5214                reloaded.resumption_history[0].question_id.as_deref(),
5215                Some("resume-question")
5216            );
5217
5218            // A revision already persisted with the old approval/pin is also
5219            // invalidated when the new operator release is recorded.
5220            unchanged.instruction = "Reuse measured PR head B".into();
5221            unchanged.hold_machine(Some("disk hold".into()));
5222            unchanged.release_operator(source, None);
5223            assert!(unchanged.resume_override.is_none());
5224            assert!(!may_resume_run(&run, &unchanged));
5225        }
5226    }
5227
5228    #[test]
5229    fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
5230        let mut t = task();
5231        let mut run = run_state(RunStatus::Blocked);
5232        t.review_of = Some("approved-head".into());
5233        t.instruction =
5234            "Review the branch `approved-head` (review-only: no implementation, no judging)."
5235                .into();
5236        run.instruction = "Review the work already on branch `approved-head`. There is no task statement: what the change claims to do is whatever its commits say.\n\nCommit log".into();
5237        run.reviewed_commits = Some(vec!["Commit log".into()]);
5238        t.start(run.id.clone());
5239        t.hold_machine(Some("interrupted review".into()));
5240        t.release_operator("cli", None);
5241        assert!(
5242            compatible_run_instruction(&run, &t),
5243            "legacy explicit review remains resumable"
5244        );
5245        let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
5246            .filter(|_| compatible_run_instruction(&run, &t));
5247        assert_eq!(
5248            choose_starter(None, false, unfinished.as_deref()),
5249            Starter::Resume(run.id.clone())
5250        );
5251        run.task_instruction = Some(t.instruction.clone());
5252        assert!(compatible_run_instruction(&run, &t));
5253        let reloaded: RunState =
5254            serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
5255        assert!(compatible_run_instruction(&reloaded, &t));
5256        t.edit(
5257            "new approved head".into(),
5258            "Reuse measured PR head B".into(),
5259        )
5260        .unwrap();
5261        assert!(!compatible_run_instruction(&run, &t));
5262
5263        // Legacy recovery reviews retain the task criteria ahead of the log.
5264        t.review_of = None;
5265        t.instruction = "Fix Clippy on approved head".into();
5266        run.task_instruction = None;
5267        run.instruction = format!(
5268            "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
5269            t.instruction
5270        );
5271        assert!(compatible_run_instruction(&run, &t));
5272        t.instruction.push('\n');
5273        assert!(
5274            compatible_run_instruction(&run, &t),
5275            "legacy generated review trimmed the original criteria"
5276        );
5277        t.hold_for_handover(Some("approved-head".into()), "refused".into());
5278        let mut unchanged = t.clone();
5279        assert_eq!(
5280            take_review_branch(&mut unchanged, Some(&run)).as_deref(),
5281            Some("approved-head")
5282        );
5283        t.edit("new plan".into(), "Reuse measured PR head B".into())
5284            .unwrap();
5285        assert!(take_review_branch(&mut t, Some(&run)).is_none());
5286        assert!(!compatible_run_instruction(&run, &t));
5287        t.review_branch = Some("approved-head".into());
5288        t.review_instruction = None;
5289        assert!(
5290            take_review_branch(&mut t, Some(&run)).is_none(),
5291            "legacy retained candidate cannot replace a revised approved head"
5292        );
5293    }
5294
5295    #[test]
5296    fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
5297        crate::run::pin_test_home();
5298        let dir = tempfile::tempdir().unwrap();
5299        let queue = Queue::at(dir.path().join("queue"));
5300        for resume in [true, false] {
5301            let state = run_state(RunStatus::Blocked);
5302            let mut t = task();
5303            t.start(state.id.clone());
5304            let action = if resume {
5305                ask::ChoiceAction::Resume {
5306                    run: state.id.clone(),
5307                }
5308            } else {
5309                ask::ChoiceAction::Requeue
5310            };
5311            let mut q = action_question(&state.id, action);
5312            q.status = ask::QuestionStatus::Open;
5313            q.answer = None;
5314            q.answered_at = None;
5315            t.fail("run stopped with a question", 3);
5316            hold_if_runnable(&queue, &mut t);
5317            assert!(t.operator_decided_at.is_none());
5318            assert!(t.operator_held());
5319            q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
5320            let expected = if resume {
5321                ActionDecision::Resume(state.id.clone())
5322            } else {
5323                ActionDecision::Requeue
5324            };
5325            assert_eq!(
5326                decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
5327                expected
5328            );
5329            t.hold_manual(Some("later explicit hold".into()));
5330            assert_eq!(
5331                decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
5332                ActionDecision::Stale
5333            );
5334        }
5335    }
5336
5337    #[test]
5338    fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
5339        let mut t = task();
5340        t.answers.push(crate::queue::AnsweredQuestion {
5341            question: "Inspect the remote?".into(),
5342            answer: "Inspect then wait".into(),
5343        });
5344        let old = instruction_for(&t);
5345        assert!(compatible_instruction(&old, &t));
5346        t.instruction = "Reuse approved PR head and review".into();
5347        t.release_operator("cli", None);
5348        assert!(!compatible_instruction(&old, &t));
5349        let approved = instruction_for(&t);
5350        assert!(approved.contains("waiting premises are superseded"));
5351        assert!(compatible_instruction(&approved, &t));
5352        assert_eq!(resumed_instruction(&approved, &t), approved);
5353        t.release_operator("web", None);
5354        assert!(compatible_instruction(&approved, &t));
5355        assert_eq!(t.resumption_history.len(), 1);
5356        t.start("run".into());
5357        assert!(instruction_for(&t).contains("Explicit operator resumption"));
5358    }
5359
5360    /// A run that stopped on an infrastructure wait asked no agent anything:
5361    /// the task is held by the machine under a `[resource]` reason (resumable,
5362    /// re-checked by triage), and the attempt it started is given back.
5363    #[test]
5364    fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
5365        let mut state = RunState::new(
5366            PathBuf::from("/repo"),
5367            "main".to_owned(),
5368            "abc1234".to_owned(),
5369            "task".to_owned(),
5370            Config::default(),
5371        );
5372        state.status = RunStatus::Blocked;
5373        state.resource_block = Some(crate::run::ResourceBlock {
5374            node: "graft".to_owned(),
5375            kind: "shared build cache".to_owned(),
5376            detail: "timed out".to_owned(),
5377            at: jiff::Timestamp::now(),
5378        });
5379        let mut t = task();
5380        t.start("20260902-000000-aaaa".to_owned());
5381        assert_eq!(t.attempts, 1);
5382        let verdict = Verdict {
5383            status: RunStatus::Blocked,
5384            left_pr: false,
5385            quota_hit: false,
5386            parked: false,
5387            no_viable_candidates: false,
5388        };
5389        settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
5390        assert_eq!(t.status, TaskStatus::Held);
5391        assert_eq!(t.attempts, 0, "the attempt is refunded");
5392        assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
5393        assert!(
5394            !t.operator_held(),
5395            "a machine hold, released without a human"
5396        );
5397
5398        let mut selected = task();
5399        selected.start("20260902-000000-cccc".into());
5400        selected.replacement = Some(crate::merge_decision::Replacement {
5401            question: "fixture".into(),
5402            run: "earlier".into(),
5403            pr: "https://example.invalid/pr/1".into(),
5404            agent: "selected".into(),
5405            context: "fixture".into(),
5406        });
5407        state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
5408        settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
5409        assert_eq!(selected.attempts, 0);
5410        assert!(
5411            !selected.operator_held(),
5412            "a selected agent also retains a machine resource hold"
5413        );
5414        assert!(
5415            selected
5416                .hold_reason
5417                .as_deref()
5418                .unwrap()
5419                .starts_with("[resource] ")
5420        );
5421
5422        // A park request outranks it: still the operator's doing.
5423        let mut p = task();
5424        p.start("20260902-000000-bbbb".to_owned());
5425        settle_and_diagnose(
5426            &mut p,
5427            Verdict {
5428                parked: true,
5429                ..verdict
5430            },
5431            "parked",
5432            2,
5433            &state,
5434        );
5435        assert_eq!(p.status, TaskStatus::Parked);
5436    }
5437
5438    #[test]
5439    fn record_failure_notice_links_the_task() {
5440        let dir = tempfile::tempdir().unwrap();
5441        // A regular file where the queue directory should be makes every
5442        // `put` fail, on every platform and whoever runs the test.
5443        std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
5444        let queue = Queue::at(dir.path().join("queue"));
5445        let mut t = interrupt_task("rec-fail-1");
5446        record(&queue, &mut t);
5447
5448        let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
5449        assert_eq!(found.len(), 1);
5450        assert_eq!(found[0].key, "loop:record");
5451        assert_eq!(
5452            found[0].link,
5453            Some(Link::Task {
5454                id: "rec-fail-1".to_owned()
5455            })
5456        );
5457    }
5458
5459    /// A runnable task marked to interrupt, with an id fixed for assertions
5460    /// rather than the random one [`Task::new`] mints.
5461    fn interrupt_task(id: &str) -> Task {
5462        let mut t = task();
5463        t.id = id.to_owned();
5464        t.interrupt = true;
5465        t
5466    }
5467
5468    /// An ordinary runnable task with an id fixed for assertions.
5469    fn task_with_id(id: &str) -> Task {
5470        let mut t = task();
5471        t.id = id.to_owned();
5472        t
5473    }
5474
5475    /// A runnable task marked `--urgent`, with an id fixed for assertions.
5476    fn urgent_task(id: &str) -> Task {
5477        let mut t = task();
5478        t.id = id.to_owned();
5479        t.urgent = true;
5480        t
5481    }
5482
5483    #[test]
5484    fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
5485        let dir = tempfile::tempdir().unwrap();
5486        let queue = Queue::at(dir.path().join("queue"));
5487        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
5488        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
5489        let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
5490        let mut first = task();
5491        queue.put(&mut first).unwrap();
5492        let stale_plain = queue.get(&first.id).unwrap();
5493        first.set_urgent(true).unwrap();
5494        queue.put(&mut first).unwrap();
5495        let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
5496        let mut second = urgent_task("second");
5497        queue.put(&mut second).unwrap();
5498        assert!(claim_dispatch(&queue, &second, false, &ordinary, &urgent).is_none());
5499        drop(queue.claim(&second.id).unwrap());
5500        assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
5501        drop(dispatched);
5502        let stale_urgent = queue.get(&first.id).unwrap();
5503        first.set_urgent(false).unwrap();
5504        queue.put(&mut first).unwrap();
5505        assert!(claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent).is_none());
5506        assert_eq!(urgent.available_permits(), 1);
5507        drop(queue.claim(&first.id).unwrap());
5508        drop(occupied);
5509    }
5510
5511    #[test]
5512    fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
5513        let dir = tempfile::tempdir().unwrap();
5514        let queue = Queue::at(dir.path().join("queue"));
5515        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
5516        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
5517        let mut t = task();
5518        queue.put(&mut t).unwrap();
5519        for enabled in [true, false] {
5520            let stale = queue.get(&t.id).unwrap();
5521            t.set_urgent(enabled).unwrap();
5522            queue.put(&mut t).unwrap();
5523            assert_ne!(stale.urgent, enabled);
5524            let DispatchClaim {
5525                task: fresh,
5526                claim,
5527                permit,
5528            } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
5529            assert_eq!(fresh.urgent, enabled);
5530            assert_eq!(ordinary.available_permits(), usize::from(enabled));
5531            assert_eq!(urgent.available_permits(), usize::from(!enabled));
5532            assert!(queue.claim(&t.id).is_err());
5533            assert_eq!(fresh.attempts, stale.attempts);
5534            drop((claim, permit));
5535            assert_eq!(ordinary.available_permits(), 1);
5536            assert_eq!(urgent.available_permits(), 1);
5537        }
5538        t.set_urgent(true).unwrap();
5539        queue.put(&mut t).unwrap();
5540        let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
5541        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
5542        assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
5543        drop(queue.claim(&t.id).unwrap());
5544        assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
5545        drop(occupied);
5546        assert!(claim_dispatch(&queue, &t, true, &ordinary, &urgent).is_none());
5547        drop(queue.claim(&t.id).unwrap());
5548        let held = queue.claim(&t.id).unwrap();
5549        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
5550        drop(held);
5551        t.status = TaskStatus::Held;
5552        queue.put(&mut t).unwrap();
5553        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
5554        drop(queue.claim(&t.id).unwrap());
5555        std::fs::remove_file(queue.path_of(&t.id)).unwrap();
5556        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
5557        drop(queue.claim(&t.id).unwrap());
5558        assert_eq!(urgent.available_permits(), 1);
5559    }
5560
5561    /// The land-resume exemption wins outright, whether or not the candidate
5562    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
5563    /// queue behind anything" guarantee cannot be weaker just because the
5564    /// same task was also filed with `--urgent`.
5565    #[test]
5566    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
5567        assert_eq!(permit_kind(true, false), PermitKind::None);
5568        assert_eq!(permit_kind(true, true), PermitKind::None);
5569    }
5570
5571    /// The one property this whole feature exists for: `--urgent` draws from
5572    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
5573    /// ordinary candidate draws from the ordinary pool exactly as before,
5574    /// untouched by the urgent slot's existence.
5575    #[test]
5576    fn permit_kind_separates_urgent_from_ordinary() {
5577        assert_eq!(permit_kind(false, true), PermitKind::Urgent);
5578        assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
5579    }
5580
5581    /// The exact wiring `attempt` runs before minting anything: a config's
5582    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
5583    /// Free space is injected rather than asked of the real disk - the point
5584    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
5585    /// is deterministic on every machine this test runs on, never dependent
5586    /// on how full the CI runner's own disk happens to be.
5587    #[test]
5588    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
5589        let cfg = Config::default();
5590        let repo = Path::new("/any/repo/path");
5591
5592        let reason =
5593            disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
5594        assert!(reason.contains("1024"), "{reason}");
5595        assert!(
5596            reason.contains(&cfg.disk.min_free_bytes.to_string()),
5597            "{reason}"
5598        );
5599
5600        assert_eq!(
5601            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
5602            None,
5603            "exactly at the floor is open"
5604        );
5605        assert_eq!(
5606            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
5607            None,
5608            "comfortably above the floor is open"
5609        );
5610    }
5611
5612    #[test]
5613    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
5614        let mut cfg = Config::default();
5615        cfg.disk.min_free_bytes = 0;
5616        let repo = Path::new("/any/repo/path");
5617        assert_eq!(
5618            disk_gate_with(repo, &cfg, |_| Ok(0)),
5619            None,
5620            "a zero floor never measures at all"
5621        );
5622    }
5623
5624    #[test]
5625    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
5626        let cfg = Config::default();
5627        let repo = Path::new("/any/repo/path");
5628        let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
5629            .expect("a measurement failure must close the gate, not open it");
5630        assert!(reason.contains("could not measure"), "{reason}");
5631    }
5632
5633    #[test]
5634    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
5635        let ordinary = task();
5636        let next = advance_interrupt(
5637            Interrupt::Idle,
5638            std::slice::from_ref(&ordinary.id),
5639            std::slice::from_ref(&ordinary),
5640        );
5641        assert_eq!(next, Interrupt::Idle);
5642    }
5643
5644    #[test]
5645    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
5646        // Nothing to interrupt - this is just an ordinary candidate, and the
5647        // loop's normal dispatch will pick it up like any other.
5648        let marked = interrupt_task("marked");
5649        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
5650        assert_eq!(next, Interrupt::Idle);
5651    }
5652
5653    #[test]
5654    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
5655        let marked = interrupt_task("marked");
5656        let next = advance_interrupt(
5657            Interrupt::Idle,
5658            &["running".to_owned()],
5659            std::slice::from_ref(&marked),
5660        );
5661        assert_eq!(
5662            next,
5663            Interrupt::Parking {
5664                parked: vec!["running".to_owned()],
5665                interrupt_task: "marked".to_owned(),
5666            }
5667        );
5668    }
5669
5670    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
5671    /// one run can be in flight when a task becomes runnable and marked.
5672    /// Parking all of them would mean `Resuming` later has more than one id
5673    /// to release back to ordinary dispatch, which cannot be made safe
5674    /// against that same setting's own extra concurrency slots letting two
5675    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
5676    /// The simplification the task's own constraints ask for: do not begin
5677    /// a sequence at all until the herd settles back to exactly one.
5678    #[test]
5679    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
5680        let marked = interrupt_task("marked");
5681
5682        let two = advance_interrupt(
5683            Interrupt::Idle,
5684            &["a".to_owned(), "b".to_owned()],
5685            std::slice::from_ref(&marked),
5686        );
5687        assert_eq!(two, Interrupt::Idle);
5688
5689        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
5690        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
5691    }
5692
5693    #[test]
5694    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
5695        let state = Interrupt::Parking {
5696            parked: vec!["running".to_owned()],
5697            interrupt_task: "marked".to_owned(),
5698        };
5699        // Still in flight: no change.
5700        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
5701        assert_eq!(still_going, state);
5702
5703        // Left flight, but the interrupt task has not been dispatched yet on
5704        // this tick - stays `Parking` so `interrupt_gate` can let it through,
5705        // as long as it is still runnable.
5706        let stopped_but_not_yet_dispatched =
5707            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
5708        assert_eq!(stopped_but_not_yet_dispatched, state);
5709
5710        // Left flight, and the interrupt task is now in flight itself.
5711        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
5712        assert_eq!(
5713            dispatched,
5714            Interrupt::Running {
5715                parked: vec!["running".to_owned()],
5716                interrupt_task: "marked".to_owned(),
5717            }
5718        );
5719    }
5720
5721    #[test]
5722    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
5723        let state = Interrupt::Running {
5724            parked: vec!["running".to_owned()],
5725            interrupt_task: "marked".to_owned(),
5726        };
5727        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
5728        assert_eq!(still_running, state);
5729
5730        // Whatever it ended as - merged, failed, held - is not this
5731        // function's concern: leaving flight is the only trigger, driven
5732        // straight off the same in-flight list `poll` already reaps. It does
5733        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
5734        // why that would let an unrelated task start ahead of, or alongside,
5735        // the guaranteed resume.
5736        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
5737        assert_eq!(
5738            ended,
5739            Interrupt::Resuming {
5740                parked: vec!["running".to_owned()]
5741            }
5742        );
5743    }
5744
5745    #[test]
5746    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
5747        let state = Interrupt::Resuming {
5748            parked: vec!["running".to_owned()],
5749        };
5750        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
5751        assert_eq!(still_waiting, state);
5752
5753        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
5754        assert_eq!(dispatched, Interrupt::Idle);
5755    }
5756
5757    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
5758    /// or otherwise moved on by an operator with no claim standing in the
5759    /// way - must not wedge the sequence (and so the whole loop's dispatch,
5760    /// via `interrupt_gate`) waiting forever for a dispatch that can never
5761    /// come. The parked run still gets its resume.
5762    #[test]
5763    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
5764    {
5765        let state = Interrupt::Parking {
5766            parked: vec!["running".to_owned()],
5767            interrupt_task: "marked".to_owned(),
5768        };
5769        // `marked` has been held/blocked/deleted since the sequence began:
5770        // it no longer appears in `runnable` at all.
5771        let next = advance_interrupt(state, &[], &[]);
5772        assert_eq!(
5773            next,
5774            Interrupt::Resuming {
5775                parked: vec!["running".to_owned()]
5776            },
5777            "abandoning the interrupt must not abandon the resume it owes"
5778        );
5779    }
5780
5781    /// The same abandonment, one step later: `Resuming` itself must not wait
5782    /// forever for a parked task that has since become unrunnable.
5783    #[test]
5784    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
5785        let state = Interrupt::Resuming {
5786            parked: vec!["running".to_owned()],
5787        };
5788        let next = advance_interrupt(state, &[], &[]);
5789        assert_eq!(
5790            next,
5791            Interrupt::Idle,
5792            "nothing is left to wait for; the loop must not stay wedged"
5793        );
5794    }
5795
5796    #[test]
5797    fn disabled_by_config_the_sequence_can_never_leave_idle() {
5798        let marked = interrupt_task("marked");
5799        let next = advance_interrupt_tick(
5800            false,
5801            Interrupt::Idle,
5802            &["running".to_owned()],
5803            std::slice::from_ref(&marked),
5804        );
5805        assert_eq!(
5806            next,
5807            Interrupt::Idle,
5808            "an unmarked, unconfigured daemon must behave exactly as before"
5809        );
5810    }
5811
5812    #[test]
5813    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
5814        let state = Interrupt::Parking {
5815            parked: vec!["running".to_owned()],
5816            interrupt_task: "marked".to_owned(),
5817        };
5818        let candidates = vec![interrupt_task("marked"), task()];
5819        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
5820        assert!(
5821            allowed.is_empty(),
5822            "nothing may dispatch - not even the interrupt task itself - \
5823             until the parked run has actually stopped"
5824        );
5825    }
5826
5827    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
5828    /// grow a special case for it: an urgent candidate that is not the
5829    /// interrupt task withholds exactly like an ordinary one for as long as
5830    /// the parked run it is racing has not actually left flight. A version
5831    /// of this feature once bypassed the gate for urgent candidates, on the
5832    /// theory that a genuinely separate concurrency lane could not collide
5833    /// with 75dd's own; it could, and did - the bypassed task dispatched
5834    /// alongside a run 75dd's own state machine had only *asked* to park,
5835    /// not yet confirmed gone, which is exactly the second run
5836    /// `Interrupt::Parking`'s own doc says must never happen. There is no
5837    /// tick during Parking/Running/Resuming where letting an extra
5838    /// candidate through is safe, urgent or not - the parked run may still
5839    /// be genuinely mid-call.
5840    #[test]
5841    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
5842        for state in [
5843            Interrupt::Parking {
5844                parked: vec!["running".to_owned()],
5845                interrupt_task: "marked".to_owned(),
5846            },
5847            Interrupt::Running {
5848                parked: vec!["running".to_owned()],
5849                interrupt_task: "marked".to_owned(),
5850            },
5851            Interrupt::Resuming {
5852                parked: vec!["running".to_owned()],
5853            },
5854        ] {
5855            let candidates = vec![
5856                interrupt_task("marked"),
5857                urgent_task("hot"),
5858                task_with_id("ordinary"),
5859            ];
5860            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
5861            assert!(
5862                !allowed.iter().any(|t| t.id == "hot"),
5863                "an urgent candidate must wait out the same gate as anything \
5864                 else while the run it would run alongside has not actually \
5865                 left flight, for state {state:?}: {allowed:?}"
5866            );
5867        }
5868    }
5869
5870    /// The one case where marking a task `--urgent` and `interrupt` at once
5871    /// is not redundant: once the interrupt sequence's own guaranteed
5872    /// resume/dispatch actually admits the task, it is unaffected by also
5873    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
5874    /// never on the urgent flag.
5875    #[test]
5876    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
5877        let state = Interrupt::Resuming {
5878            parked: vec!["hot".to_owned()],
5879        };
5880        let candidates = vec![urgent_task("hot"), task()];
5881        let allowed = interrupt_gate(&state, &[], candidates);
5882        assert_eq!(
5883            allowed.iter().filter(|t| t.id == "hot").count(),
5884            1,
5885            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
5886        );
5887    }
5888
5889    #[test]
5890    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
5891        let state = Interrupt::Parking {
5892            parked: vec!["running".to_owned()],
5893            interrupt_task: "marked".to_owned(),
5894        };
5895        let other = task();
5896        let candidates = vec![interrupt_task("marked"), other.clone()];
5897        let allowed = interrupt_gate(&state, &[], candidates);
5898        assert_eq!(allowed.len(), 1);
5899        assert_eq!(allowed[0].id, "marked");
5900    }
5901
5902    #[test]
5903    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
5904        let state = Interrupt::Running {
5905            parked: vec!["running".to_owned()],
5906            interrupt_task: "marked".to_owned(),
5907        };
5908        let candidates = vec![task(), task()];
5909        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
5910        assert!(allowed.is_empty());
5911    }
5912
5913    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
5914    /// sequence began (only reachable above the default
5915    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
5916    /// never both in the same tick, which is what "exactly one resume, no
5917    /// simultaneous run" actually requires structurally rather than by
5918    /// coincidence of how many ordinary slots happen to be free.
5919    #[test]
5920    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
5921        let state = Interrupt::Resuming {
5922            parked: vec!["a".to_owned(), "c".to_owned()],
5923        };
5924        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
5925        let allowed = interrupt_gate(&state, &[], candidates);
5926        assert_eq!(
5927            allowed.len(),
5928            1,
5929            "at most one candidate may be offered while resuming: {allowed:?}"
5930        );
5931        assert_eq!(allowed[0].id, "a");
5932    }
5933
5934    #[test]
5935    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
5936        let state = Interrupt::Resuming {
5937            parked: vec!["a".to_owned()],
5938        };
5939        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
5940        assert!(allowed.is_empty());
5941    }
5942
5943    /// The invariant the completion criteria ask for by name: across a whole
5944    /// simulated sequence, there is never a tick where the gate would let
5945    /// through both the parked run's resume and the interrupt task, and
5946    /// exactly one candidate resumes the instant the interrupt task's run
5947    /// ends - never zero, never more than one.
5948    #[test]
5949    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
5950        let running = task(); // id: whatever `Task::new` minted
5951        let marked = interrupt_task("marked");
5952
5953        let mut state = Interrupt::Idle;
5954        // Tick 1: `running` is in flight, `marked` becomes runnable.
5955        let in_flight = vec![running.id.clone()];
5956        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
5957        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
5958        assert!(gated.is_empty(), "still waiting on `running` to park");
5959
5960        // Tick 2: `running` parked and left flight; nothing dispatched yet.
5961        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
5962        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
5963        assert_eq!(
5964            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
5965            vec!["marked"],
5966            "only the interrupt task may be offered to the dispatcher now"
5967        );
5968
5969        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
5970        state = advance_interrupt_tick(
5971            true,
5972            state,
5973            &["marked".to_owned()],
5974            std::slice::from_ref(&running),
5975        );
5976        let gated = interrupt_gate(
5977            &state,
5978            &["marked".to_owned()],
5979            vec![marked.clone(), running.clone()],
5980        );
5981        assert!(
5982            gated.is_empty(),
5983            "the parked run must not be offered back while the interrupt \
5984             task is still running"
5985        );
5986
5987        // Tick 4: `marked`'s run reached a terminal status and left flight.
5988        // A higher-priority ordinary task `other` is also runnable now - it
5989        // must not be let through instead of, or alongside, `running`.
5990        let other = task_with_id("other");
5991        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
5992        assert_eq!(
5993            state,
5994            Interrupt::Resuming {
5995                parked: vec![running.id.clone()]
5996            }
5997        );
5998        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
5999        assert_eq!(
6000            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
6001            vec![running.id.as_str()],
6002            "exactly the parked run resumes - not the unrelated task, even \
6003             though it was offered first"
6004        );
6005
6006        // Tick 5: `running` is now in flight (dispatched from tick 4's
6007        // gate). Only now does the sequence end and ordinary dispatch fully
6008        // resume.
6009        state = advance_interrupt_tick(
6010            true,
6011            state,
6012            std::slice::from_ref(&running.id),
6013            std::slice::from_ref(&other),
6014        );
6015        assert_eq!(state, Interrupt::Idle);
6016        let gated = interrupt_gate(
6017            &state,
6018            std::slice::from_ref(&running.id),
6019            vec![other.clone()],
6020        );
6021        assert_eq!(
6022            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
6023            vec![other.id.as_str()],
6024            "ordinary dispatch is unrestricted again"
6025        );
6026    }
6027
6028    #[test]
6029    fn every_run_status_settles_the_task_it_came_from() {
6030        // run status, resulting task status, attempts still standing after one
6031        let table = [
6032            (RunStatus::Merged, TaskStatus::Done, 1),
6033            (RunStatus::Ready, TaskStatus::Done, 1),
6034            (RunStatus::Stalled, TaskStatus::Failed, 0),
6035            (RunStatus::Blocked, TaskStatus::Failed, 1),
6036            (RunStatus::Failed, TaskStatus::Failed, 1),
6037            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
6038            (RunStatus::Prep, TaskStatus::Failed, 1),
6039            (RunStatus::Implementing, TaskStatus::Failed, 1),
6040            (RunStatus::Judging, TaskStatus::Failed, 1),
6041            (RunStatus::Deliberating, TaskStatus::Failed, 1),
6042            (RunStatus::Voting, TaskStatus::Failed, 1),
6043            (RunStatus::Reviewing, TaskStatus::Failed, 1),
6044            (RunStatus::Gating, TaskStatus::Failed, 1),
6045        ];
6046        for (run, want, attempts) in table {
6047            let mut t = task();
6048            t.start("20260902-000000-aaaa".to_owned());
6049            settle(
6050                &mut t,
6051                Verdict {
6052                    status: run,
6053                    left_pr: false,
6054                    parked: false,
6055                    quota_hit: matches!(run, RunStatus::Stalled),
6056                    no_viable_candidates: false,
6057                },
6058                "why",
6059                2,
6060            );
6061            assert_eq!(t.status, want, "task status after {}", label(run));
6062            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
6063        }
6064    }
6065
6066    #[test]
6067    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
6068        let mut stalled = task();
6069        stalled.start("20260902-000000-aaaa".to_owned());
6070        settle(
6071            &mut stalled,
6072            Verdict {
6073                status: RunStatus::Stalled,
6074                left_pr: false,
6075                parked: false,
6076                quota_hit: true,
6077                no_viable_candidates: false,
6078            },
6079            "quota",
6080            1,
6081        );
6082        assert_eq!(stalled.attempts, 0);
6083        assert!(
6084            stalled.status.runnable(),
6085            "a machine problem must leave the task in line"
6086        );
6087
6088        let mut blocked = task();
6089        blocked.start("20260902-000000-aaaa".to_owned());
6090        settle(
6091            &mut blocked,
6092            Verdict {
6093                status: RunStatus::Blocked,
6094                left_pr: false,
6095                parked: false,
6096                quota_hit: false,
6097                no_viable_candidates: false,
6098            },
6099            "findings open",
6100            1,
6101        );
6102        assert_eq!(blocked.attempts, 1);
6103        assert_eq!(
6104            blocked.status,
6105            TaskStatus::Held,
6106            "the last attempt hands the task to a human"
6107        );
6108    }
6109
6110    #[test]
6111    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
6112        // Attempts to spare: without the pull request this task would go
6113        // straight back in line and run the whole competition again.
6114        let mut delivered = task();
6115        delivered.start("20260903-080619-01c2".to_owned());
6116        settle(
6117            &mut delivered,
6118            Verdict {
6119                status: RunStatus::Blocked,
6120                left_pr: true,
6121                parked: false,
6122                quota_hit: false,
6123                no_viable_candidates: false,
6124            },
6125            "no check status",
6126            4,
6127        );
6128        assert_eq!(
6129            delivered.status,
6130            TaskStatus::Held,
6131            "a pull request waiting on CI or a person is not a retryable failure"
6132        );
6133        assert!(
6134            !delivered.status.runnable(),
6135            "the loop must not pick this task up again"
6136        );
6137        assert_eq!(
6138            delivered.last_error.as_deref(),
6139            Some("no check status"),
6140            "the operator needs to be told what the gate was waiting for"
6141        );
6142
6143        // The same status without a pull request is a plain failure, and with
6144        // attempts left it is retried.
6145        let mut empty_handed = task();
6146        empty_handed.start("20260903-080619-01c2".to_owned());
6147        settle(
6148            &mut empty_handed,
6149            Verdict {
6150                status: RunStatus::Blocked,
6151                left_pr: false,
6152                parked: false,
6153                quota_hit: false,
6154                no_viable_candidates: false,
6155            },
6156            "findings open",
6157            4,
6158        );
6159        assert_eq!(empty_handed.status, TaskStatus::Failed);
6160        assert!(empty_handed.status.runnable());
6161    }
6162
6163    #[test]
6164    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
6165        // Every candidate agreed, with evidence, that nothing belonged in the
6166        // worktree. That is not a confirmed success to close automatically -
6167        // a human still has to check the claim - and it is not an ordinary
6168        // failure either, so this settles exactly like a pull request nobody
6169        // merged yet: `Held`, same as `Blocked` with a PR.
6170        let mut noop = task();
6171        noop.start("20260912-131304-391f".to_owned());
6172        settle(
6173            &mut noop,
6174            Verdict {
6175                status: RunStatus::VerifiedNoop,
6176                left_pr: false,
6177                parked: false,
6178                quota_hit: false,
6179                no_viable_candidates: true,
6180            },
6181            "candidate A: already fixed by b32cfc4, on main",
6182            4,
6183        );
6184        assert_eq!(
6185            noop.status,
6186            TaskStatus::Held,
6187            "an unverified claim is a request for a human, not a failure"
6188        );
6189        assert!(
6190            !noop.status.runnable(),
6191            "the loop must not requeue this on the same unverified claim"
6192        );
6193        // `Task::release` resets attempts to zero the moment a human looks at
6194        // the evidence and lets it run again, so it does not matter here
6195        // whether the one attempt already spent stays spent - what matters is
6196        // that nothing retries this task unattended in the meantime.
6197        assert_eq!(noop.attempts, 1);
6198    }
6199
6200    #[test]
6201    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
6202        // Parking is the operator asking for the process back - to replace the
6203        // binary, most of all. The run's work is intact on disk, so this is
6204        // not a failed attempt, and charging for it would mean a few upgrades
6205        // could exhaust a budget meant for agents that misbehaved.
6206        let mut parked = task();
6207        parked.start("20260903-183634-2d98".to_owned());
6208        settle(
6209            &mut parked,
6210            Verdict {
6211                status: RunStatus::Implementing,
6212                left_pr: false,
6213                quota_hit: false,
6214                parked: true,
6215                no_viable_candidates: false,
6216            },
6217            "parked after `implementing`",
6218            2,
6219        );
6220        assert_eq!(parked.attempts, 0, "a park is refunded");
6221        assert!(
6222            parked.status.runnable(),
6223            "and the task stays in line so the next loop resumes its run"
6224        );
6225        assert_eq!(parked.status, TaskStatus::Parked);
6226        assert_eq!(
6227            parked.park_reason.as_deref(),
6228            Some("parked after `implementing`"),
6229            "the card says where it stopped"
6230        );
6231        assert_eq!(parked.last_error, None, "nothing failed");
6232
6233        // Without the park flag the same non-terminal status is what it always
6234        // was: `execute` returning mid-flight, which is a bug and spends an
6235        // attempt so a task cannot loop on it forever.
6236        let mut broken = task();
6237        broken.start("20260903-183634-2d98".to_owned());
6238        settle(
6239            &mut broken,
6240            Verdict {
6241                status: RunStatus::Implementing,
6242                left_pr: false,
6243                quota_hit: false,
6244                parked: false,
6245                no_viable_candidates: false,
6246            },
6247            "returned mid-flight",
6248            2,
6249        );
6250        assert_eq!(broken.attempts, 1);
6251    }
6252
6253    #[test]
6254    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
6255        // Run e633: quorum lost because two judges answered with the wrong
6256        // JSON shape, `quota: []`. Refunding that takes the bound off the
6257        // retry loop, and each retry pays for a fresh hour-long implement
6258        // wave before it can fail the same way.
6259        let mut flaky = task();
6260        flaky.start("20260903-123023-e633".to_owned());
6261        settle(
6262            &mut flaky,
6263            Verdict {
6264                status: RunStatus::Stalled,
6265                left_pr: false,
6266                parked: false,
6267                quota_hit: false,
6268                no_viable_candidates: false,
6269            },
6270            "verdict rests on 1 of 3 judges",
6271            2,
6272        );
6273        assert_eq!(
6274            flaky.attempts, 1,
6275            "flakiness spends an attempt, so `max_attempts` still bounds it"
6276        );
6277        assert!(flaky.status.runnable(), "and it is still worth retrying");
6278
6279        // The same status, lost to a rate limit, is the machine's fault.
6280        let mut limited = task();
6281        limited.start("20260903-123023-e633".to_owned());
6282        settle(
6283            &mut limited,
6284            Verdict {
6285                status: RunStatus::Stalled,
6286                left_pr: false,
6287                parked: false,
6288                quota_hit: true,
6289                no_viable_candidates: false,
6290            },
6291            "judge-2, judge-3 out of quota",
6292            2,
6293        );
6294        assert_eq!(limited.attempts, 0, "a quota window is refunded");
6295        assert!(limited.status.runnable());
6296
6297        // And the bound really binds: a task that keeps stalling on flakiness
6298        // reaches a human instead of running the roster forever.
6299        let mut worn = task();
6300        for _ in 0..2 {
6301            worn.release();
6302        }
6303        worn.start("20260903-123023-e633".to_owned());
6304        worn.attempts = 2;
6305        settle(
6306            &mut worn,
6307            Verdict {
6308                status: RunStatus::Stalled,
6309                left_pr: false,
6310                parked: false,
6311                quota_hit: false,
6312                no_viable_candidates: false,
6313            },
6314            "no quorum again",
6315            2,
6316        );
6317        assert_eq!(worn.status, TaskStatus::Held);
6318        assert!(!worn.status.runnable());
6319    }
6320
6321    #[test]
6322    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
6323        // The implement wave loses every seat to the same rate limit and
6324        // `after_implement` bails with nothing viable, which surfaces as
6325        // `Failed` rather than `Stalled`. That is the same machine fact the
6326        // `Stalled`-quota row already refunds, and must be refunded the same
6327        // way, or a quota outage quietly holds every task it touches instead
6328        // of leaving them in line for the reset.
6329        let mut wiped_out = task();
6330        wiped_out.start("20260907-025000-a1b2".to_owned());
6331        settle(
6332            &mut wiped_out,
6333            Verdict {
6334                status: RunStatus::Failed,
6335                left_pr: false,
6336                parked: false,
6337                quota_hit: true,
6338                no_viable_candidates: true,
6339            },
6340            "no candidate produced a change; nothing to judge",
6341            2,
6342        );
6343        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
6344        assert!(
6345            wiped_out.status.runnable(),
6346            "a machine problem must leave the task in line"
6347        );
6348
6349        // This is the exemption that must stay narrow: a candidate that did
6350        // produce a change, and then failed for some other reason, still
6351        // spends the attempt even though a seat elsewhere hit its quota.
6352        // Otherwise every ordinary failure that happens to share a run with
6353        // an unrelated rate limit would be refunded for free.
6354        let mut partial_progress = task();
6355        partial_progress.start("20260907-025500-c3d4".to_owned());
6356        settle(
6357            &mut partial_progress,
6358            Verdict {
6359                status: RunStatus::Failed,
6360                left_pr: false,
6361                parked: false,
6362                quota_hit: true,
6363                no_viable_candidates: false,
6364            },
6365            "gate failed on the winning candidate",
6366            2,
6367        );
6368        assert_eq!(
6369            partial_progress.attempts, 1,
6370            "a candidate that actually produced a change spends the attempt \
6371             even though some other seat hit its quota"
6372        );
6373        assert!(partial_progress.status.runnable());
6374    }
6375
6376    #[test]
6377    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
6378        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
6379        // disk, and that construction must reach the same conclusion as the
6380        // one `attempt` builds from a live run, or a crash at exactly the
6381        // wrong moment gives a recovered task a different policy than one a
6382        // daemon finished settling itself.
6383        let mut t = task();
6384        t.start("20260907-025000-a1b2".to_owned());
6385        let mut state = run_state(RunStatus::Failed);
6386        state.quota.push(QuotaLoss {
6387            seat: "cand-a".to_owned(),
6388            node: "implement".to_owned(),
6389            at: Timestamp::now(),
6390            reset: None,
6391        });
6392        assert!(
6393            state.viable().is_empty(),
6394            "no candidate was added, so nothing is viable"
6395        );
6396        reclaim(&mut t, Some(state), 2, "en");
6397        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
6398        assert!(t.status.runnable());
6399    }
6400
6401    #[test]
6402    fn a_held_task_is_never_offered_to_the_loop() {
6403        let dir = tempfile::tempdir().unwrap();
6404        let queue = Queue::at(dir.path().to_path_buf());
6405        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
6406            let mut t = task();
6407            t.id = format!("2026090{n}-000000-000{n}");
6408            t.priority = priority;
6409            queue.put(&mut t).unwrap();
6410        }
6411        let mut held = task();
6412        held.id = "20260909-000000-9999".to_owned();
6413        held.priority = 99;
6414        held.hold_machine(None);
6415        queue.put(&mut held).unwrap();
6416
6417        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
6418        assert_eq!(order.len(), 3);
6419        assert!(!order.contains(&held.id));
6420        assert_eq!(
6421            order.first().cloned(),
6422            queue.next_runnable().map(|t| t.id),
6423            "the loop's first candidate is exactly what the queue offers"
6424        );
6425        assert_eq!(
6426            order,
6427            vec![
6428                "20260902-000000-0002".to_owned(),
6429                "20260903-000000-0003".to_owned(),
6430                "20260901-000000-0001".to_owned(),
6431            ],
6432            "priority first, then oldest, so nothing starves"
6433        );
6434    }
6435
6436    #[test]
6437    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
6438        let dir = tempfile::tempdir().unwrap();
6439        let queue = Queue::at(dir.path().to_path_buf());
6440        let mut old = task();
6441        old.id = "20260101-000000-old0".to_owned();
6442        queue.put(&mut old).unwrap();
6443        let mut fresh = task();
6444        fresh.id = "20260101-000000-new0".to_owned();
6445        queue.put(&mut fresh).unwrap();
6446
6447        // No parseable pid at all, so age is the only signal there is to
6448        // check - unlike a real `Queue::claim`, which always names a real,
6449        // and therefore alive, pid this test cannot fake as dead.
6450        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
6451        std::thread::sleep(Duration::from_millis(60));
6452        let live = queue.claim(&fresh.id).unwrap();
6453
6454        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
6455        assert_eq!(swept, vec![old.id.clone()]);
6456        assert!(
6457            queue.claim(&old.id).is_ok(),
6458            "an unparseable lock older than the threshold is swept"
6459        );
6460        assert!(
6461            queue.claim(&fresh.id).is_err(),
6462            "a live pid protects its lock regardless of age"
6463        );
6464        drop(live);
6465    }
6466
6467    #[test]
6468    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
6469        // The regression this guards: `sweep` now runs concurrently with
6470        // every attempt this daemon itself has spawned (see
6471        // `InFlightGuard`), not only between them the way a single
6472        // sequential loop once did. A run that legitimately outlives
6473        // `older_than` still has this very process's own live pid sitting in
6474        // its own lock file on every later sweep, and deciding by age alone
6475        // would delete that still-valid claim out from under the attempt
6476        // that holds it - which `reclaim_orphaned_running` would then read
6477        // as abandoned and hand to a second, competing attempt.
6478        let dir = tempfile::tempdir().unwrap();
6479        let queue = Queue::at(dir.path().to_path_buf());
6480        let mut t = task();
6481        t.id = "20260101-000000-live".to_owned();
6482        queue.put(&mut t).unwrap();
6483
6484        let claim = queue.claim(&t.id).unwrap();
6485        std::thread::sleep(Duration::from_millis(60));
6486
6487        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
6488        assert!(
6489            swept.is_empty(),
6490            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
6491        );
6492        assert!(
6493            queue.claim(&t.id).is_err(),
6494            "the lock still protects its task"
6495        );
6496        drop(claim);
6497    }
6498
6499    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
6500    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
6501    fn injected_dead_pid() -> u32 {
6502        std::process::id().checked_add(1).unwrap_or(1)
6503    }
6504
6505    #[test]
6506    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
6507        let dir = tempfile::tempdir().unwrap();
6508        let queue = Queue::at(dir.path().to_path_buf());
6509        let mut t = task();
6510        t.id = "20260101-000000-dead".to_owned();
6511        queue.put(&mut t).unwrap();
6512        let dead_pid = injected_dead_pid();
6513
6514        // Written directly rather than through `Queue::claim`, which would
6515        // stamp this test process's own very much alive pid and defeat the
6516        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
6517        // like moments after it died, not six hours later.
6518        std::fs::write(
6519            dir.path().join(format!("{}.lock", t.id)),
6520            dead_pid.to_string(),
6521        )
6522        .unwrap();
6523
6524        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
6525            pid != dead_pid
6526        });
6527        assert_eq!(
6528            swept,
6529            vec![t.id.clone()],
6530            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
6531        );
6532        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
6533    }
6534
6535    #[test]
6536    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
6537        let dir = tempfile::tempdir().unwrap();
6538        let queue = Queue::at(dir.path().to_path_buf());
6539        let mut t = task();
6540        t.id = "20260101-000000-late".to_owned();
6541        queue.put(&mut t).unwrap();
6542        let dead_pid = injected_dead_pid();
6543
6544        // Tick one, standing in for the sweep `poll` already runs at
6545        // startup: nothing to find yet.
6546        assert!(
6547            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
6548            "nothing has claimed the task yet"
6549        );
6550
6551        // A second daemon claims the task and dies before it ever writes
6552        // `running`, well after this loop's own startup sweep already ran.
6553        std::fs::write(
6554            dir.path().join(format!("{}.lock", t.id)),
6555            dead_pid.to_string(),
6556        )
6557        .unwrap();
6558
6559        // Tick two, standing in for a poll long into this daemon's uptime:
6560        // the same function, called again, notices what only just appeared -
6561        // proving the sweep is not a one-shot startup check.
6562        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
6563            pid != dead_pid
6564        });
6565        assert_eq!(swept, vec![t.id.clone()]);
6566    }
6567
6568    #[test]
6569    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
6570        // `reclaim_orphaned_running` looks up the task's last run, which
6571        // touches `run::home()`; the first call anywhere in this binary wins,
6572        // so this is a no-op if another test already pinned one, and either
6573        // way the run id below is never written under it.
6574        crate::run::pin_test_home();
6575        let dir = tempfile::tempdir().unwrap();
6576        let queue = Queue::at(dir.path().to_path_buf());
6577        let mut t = task();
6578        t.id = "20260101-000000-crsh".to_owned();
6579        t.status = TaskStatus::Running;
6580        t.attempts = 1;
6581        // No `run.json` behind this id: standing in for a run this test does
6582        // not need to make readable, since the point is the lock, not the
6583        // recovery table `reclaim` already has its own tests for.
6584        t.runs.push("20260904-000000-4043".to_owned());
6585        queue.put(&mut t).unwrap();
6586        let dead_pid = injected_dead_pid();
6587
6588        // The crashed daemon's own claim, naming a pid nothing on the
6589        // machine holds anymore.
6590        std::fs::write(
6591            dir.path().join(format!("{}.lock", t.id)),
6592            dead_pid.to_string(),
6593        )
6594        .unwrap();
6595
6596        // Before the lock is swept the task looks claimed, and
6597        // `reclaim_orphaned_running` must leave it alone - this is exactly
6598        // the bug: a `running` task stranded behind a dead daemon's lock,
6599        // invisible to the claim-as-proof check because the lock outlived
6600        // the process that wrote it.
6601        assert!(reclaim_orphaned_running(&queue, 2).is_empty());
6602        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
6603
6604        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
6605            pid != dead_pid
6606        });
6607        assert_eq!(swept, vec![t.id.clone()]);
6608
6609        let reclaimed = reclaim_orphaned_running(&queue, 2);
6610        assert_eq!(reclaimed, vec![t.id.clone()]);
6611        let after = queue.get(&t.id).unwrap();
6612        assert_eq!(
6613            after.status,
6614            TaskStatus::Held,
6615            "no run.json to recover from, so a human is asked"
6616        );
6617        assert_eq!(
6618            after.runs,
6619            vec!["20260904-000000-4043".to_owned()],
6620            "the crashed run's id is kept as evidence, not discarded"
6621        );
6622    }
6623
6624    #[test]
6625    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
6626        let dir = tempfile::tempdir().unwrap();
6627        let queue = Queue::at(dir.path().to_path_buf());
6628        let mut t = task();
6629        t.id = "20260101-000000-unknown".to_owned();
6630        queue.put(&mut t).unwrap();
6631        let dead_pid = injected_dead_pid();
6632        std::fs::write(
6633            dir.path().join(format!("{}.lock", t.id)),
6634            dead_pid.to_string(),
6635        )
6636        .unwrap();
6637
6638        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
6639        assert!(swept.is_empty(), "an unknown pid must keep its lock");
6640        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
6641    }
6642
6643    fn run_state_in(status: RunStatus, language: &str) -> RunState {
6644        let mut s = run_state(status);
6645        s.config.graph.language = language.to_owned();
6646        s
6647    }
6648
6649    fn unstarted_verdict(status: RunStatus) -> Verdict {
6650        Verdict {
6651            status,
6652            left_pr: false,
6653            quota_hit: false,
6654            parked: false,
6655            no_viable_candidates: false,
6656        }
6657    }
6658
6659    #[test]
6660    fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
6661        let mut t = task();
6662        t.attempts = 1;
6663        settle_in(
6664            &mut t,
6665            unstarted_verdict(RunStatus::AlreadyInBase),
6666            "already in main",
6667            1,
6668            phrases("en"),
6669        );
6670        assert_eq!(t.status, TaskStatus::Done);
6671        assert_eq!(t.attempts, 0);
6672    }
6673
6674    #[test]
6675    fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
6676        let reason = |language: &str| {
6677            let mut t = task();
6678            settle_in(
6679                &mut t,
6680                unstarted_verdict(RunStatus::Judging),
6681                "boom",
6682                1,
6683                phrases(language),
6684            );
6685            t.last_error.or(t.hold_reason).unwrap_or_default()
6686        };
6687        assert!(
6688            reason("en").starts_with("the graph stopped at `"),
6689            "{}",
6690            reason("en")
6691        );
6692        assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
6693        assert!(reason("日本語").contains("boom"));
6694        assert_eq!(reason("fr"), reason("en"));
6695    }
6696
6697    #[test]
6698    fn describe_follows_the_run_language_and_keeps_the_run_id() {
6699        let en = describe(&run_state_in(RunStatus::Stalled, "en"));
6700        assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
6701        let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
6702        assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
6703        assert!(ja.contains("[run "), "{ja}");
6704        let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
6705        assert!(ended.starts_with("run 終了: "), "{ended}");
6706        let mut de = run_state_in(RunStatus::Failed, "de");
6707        let mut en = run_state_in(RunStatus::Failed, "en");
6708        de.id = "same".to_owned();
6709        en.id = "same".to_owned();
6710        assert_eq!(describe(&de), describe(&en));
6711    }
6712
6713    #[test]
6714    fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
6715        use crate::handover::Refused;
6716        let cases = [
6717            Refused::Foreign {
6718                branch: "b".into(),
6719                path: "/w/x".into(),
6720                why: "made by hand".into(),
6721            },
6722            Refused::Unsafe {
6723                branch: "b".into(),
6724                path: "/w/x".into(),
6725                why: "its worktree has uncommitted changes (a.rs)".into(),
6726            },
6727            Refused::ReleaseFailed {
6728                branch: "b".into(),
6729                path: "/w/x".into(),
6730                run: "ab12".into(),
6731            },
6732        ];
6733        for r in &cases {
6734            let en = (phrases("en").handover_refused)(r);
6735            assert_eq!(en, r.to_string());
6736            let ja = (phrases("ja").handover_refused)(r);
6737            assert!(
6738                !ja.contains("is checked out") && !ja.contains("try again"),
6739                "{ja}"
6740            );
6741            assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
6742            if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
6743                assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
6744            }
6745        }
6746        assert!(phrases("en").handover_hint.contains("release the task"));
6747        assert!(phrases("ja").handover_hint.contains("解放"));
6748    }
6749
6750    #[test]
6751    fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
6752        let build = |lang: &str| {
6753            let mut s = run_state_in(RunStatus::Blocked, lang);
6754            s.id = "same".to_owned();
6755            s.config.graph.review_rounds = 3;
6756            let mut r = review_round(3);
6757            r.expected = 3;
6758            r.answered = 1;
6759            s.reviews.push(r);
6760            s.event(
6761                "review",
6762                "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
6763            );
6764            s
6765        };
6766        let en = describe(&build("en"));
6767        assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
6768        let ja = describe(&build("ja"));
6769        assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
6770        assert!(!ja.contains("never answered"), "{ja}");
6771        assert!(ja.contains("[run "), "{ja}");
6772
6773        // An incomplete panel whose verification failed is a different stop:
6774        // the real event must survive in ja too.
6775        let mut failed = build("ja");
6776        failed.reviews[0].e2e.push(crate::run::CommandOutcome {
6777            command: "cargo test".to_owned(),
6778            code: Some(1),
6779            output_tail: String::new(),
6780            duration_ms: 0,
6781            resource_blocked: false,
6782        });
6783        failed.event("review", "stopped; e2e failed: cargo test");
6784        let ja = describe(&failed);
6785        assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
6786        assert!(!ja.contains("席のレビュアー"), "{ja}");
6787    }
6788
6789    #[test]
6790    fn refusals_and_recovery_prose_follow_the_language() {
6791        let t = held_task_with("r1");
6792        let q = action_question(
6793            "r1",
6794            ask::ChoiceAction::Resume {
6795                run: "r1".to_owned(),
6796            },
6797        );
6798        let refuse = |p: &Phrases| match decide_action(&t, &q, p, |_: &str| bail!("gone")) {
6799            ActionDecision::Refuse(s) => s,
6800            other => panic!("{other:?}"),
6801        };
6802        assert!(refuse(phrases("en")).contains("could not be read: gone"));
6803        assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
6804        assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
6805
6806        let mut held = task();
6807        reclaim(&mut held, None, 2, "ja");
6808        assert!(held.hold_reason.unwrap().contains("保留にしました"));
6809        let mut held = task();
6810        reclaim(&mut held, None, 2, "xx");
6811        assert!(held.hold_reason.unwrap().contains("held for a human"));
6812    }
6813
6814    fn run_state(status: RunStatus) -> RunState {
6815        let mut state = RunState::new(
6816            PathBuf::from("/repo"),
6817            "main".to_owned(),
6818            "abc1234def".to_owned(),
6819            "add retries".to_owned(),
6820            Config::default(),
6821        );
6822        state.status = status;
6823        state
6824    }
6825
6826    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
6827        Candidate {
6828            index: 0,
6829            label,
6830            agent: "claude".to_owned(),
6831            branch: format!("magi/x/{label}"),
6832            worktree: PathBuf::from("/repo"),
6833            summary: summary.to_owned(),
6834            stat: String::new(),
6835            files: 0,
6836            commits: usize::from(!empty),
6837            empty,
6838            failed: failed.map(str::to_owned),
6839            verified_noop: None,
6840            duration_ms: 0,
6841            folded: false,
6842        }
6843    }
6844
6845    #[test]
6846    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
6847        let mut state = run_state(RunStatus::Blocked);
6848        state.gate = vec![
6849            CommandOutcome {
6850                command: "cargo make check".to_owned(),
6851                code: Some(0),
6852                output_tail: "ok".to_owned(),
6853                duration_ms: 0,
6854                resource_blocked: false,
6855            },
6856            CommandOutcome {
6857                command: "cargo test".to_owned(),
6858                code: Some(101),
6859                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
6860                duration_ms: 0,
6861                resource_blocked: false,
6862            },
6863        ];
6864        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
6865        assert!(d.contains("cargo test"), "{d}");
6866        assert!(
6867            !d.contains("cargo make check"),
6868            "a passing check is not a diagnostic: {d}"
6869        );
6870        assert!(d.contains("assertion failed"), "{d}");
6871    }
6872
6873    #[test]
6874    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
6875        let mut state = run_state(RunStatus::Blocked);
6876        state.event(
6877            "land",
6878            "stopped: the fixer produced no commit while 2 check(s) were failing \
6879             (build, lint); stopping instead of looping on an unchanged tree",
6880        );
6881        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
6882        assert!(d.contains("build"), "{d}");
6883        assert!(d.contains("lint"), "{d}");
6884        assert!(d.contains("fixer produced no commit"), "{d}");
6885    }
6886
6887    #[test]
6888    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
6889        // `describe`'s output becomes `Task::last_error` verbatim, and the
6890        // phone renders that in the same alarm-styled box an ordinary
6891        // failure gets. A bare `verified_noop` there would read exactly like
6892        // the failure this status exists to be told apart from.
6893        let state = run_state(RunStatus::VerifiedNoop);
6894        let d = describe(&state);
6895        assert!(
6896            d.contains("agent-verified no-op"),
6897            "expected the display label, not the wire spelling: {d}"
6898        );
6899        assert!(!d.contains("verified_noop"), "{d}");
6900    }
6901
6902    #[test]
6903    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
6904        // The whole point of the feature: a run held as "no candidate produced
6905        // a change" can mean the implementer actually finished the task and
6906        // only left a clean local tree behind - see AGENTS.md on this exact
6907        // failure mode. The diagnostic has to carry what the agent actually
6908        // said, not just the fact that nothing was there to judge.
6909        let mut state = run_state(RunStatus::Failed);
6910        state.candidates = vec![candidate(
6911            'A',
6912            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
6913            true,
6914            None,
6915        )];
6916        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
6917        assert!(d.contains("candidate A"), "{d}");
6918        assert!(d.contains("tagged v1.2.3"), "{d}");
6919    }
6920
6921    #[test]
6922    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
6923        let mut state = run_state(RunStatus::Failed);
6924        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
6925        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
6926        assert!(d.contains("candidate A"), "{d}");
6927        assert!(d.contains("agent timed out"), "{d}");
6928    }
6929
6930    #[test]
6931    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
6932        // A viable candidate existed, the gate never ran, and nothing land
6933        // said matches - `Task::last_error` is left to explain this one alone.
6934        let mut state = run_state(RunStatus::Failed);
6935        state.candidates = vec![candidate('A', "did the work", false, None)];
6936        assert!(diagnostic(&state).is_none());
6937    }
6938
6939    #[test]
6940    fn diagnostic_is_bounded_however_much_a_run_printed() {
6941        let mut state = run_state(RunStatus::Blocked);
6942        state.gate = vec![
6943            CommandOutcome {
6944                command: "cargo test".to_owned(),
6945                code: Some(101),
6946                output_tail: "x".repeat(50_000),
6947                duration_ms: 0,
6948                resource_blocked: false,
6949            },
6950            CommandOutcome {
6951                command: "cargo clippy".to_owned(),
6952                code: Some(1),
6953                output_tail: "y".repeat(50_000),
6954                duration_ms: 0,
6955                resource_blocked: false,
6956            },
6957        ];
6958        state.candidates = vec![
6959            candidate('A', &"z".repeat(50_000), true, None),
6960            candidate('B', &"w".repeat(50_000), true, None),
6961        ];
6962        let d = diagnostic(&state).expect("plenty here to diagnose");
6963        assert!(
6964            d.len() <= DIAGNOSTIC_MAX,
6965            "diagnostic grew to {} bytes, unbounded",
6966            d.len()
6967        );
6968    }
6969
6970    #[test]
6971    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
6972        let mut state = run_state(RunStatus::Blocked);
6973        state.gate = vec![CommandOutcome {
6974            command: "cargo test".to_owned(),
6975            code: Some(101),
6976            output_tail: "assertion failed".to_owned(),
6977            duration_ms: 0,
6978            resource_blocked: false,
6979        }];
6980        let verdict = Verdict {
6981            status: RunStatus::Blocked,
6982            left_pr: false,
6983            quota_hit: false,
6984            parked: false,
6985            no_viable_candidates: false,
6986        };
6987
6988        // Attempt one of two still has a retry coming: no diagnostic yet, the
6989        // task is going to run again and this run's evidence would go stale.
6990        let mut t = task();
6991        t.start("run-1".to_owned());
6992        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
6993        assert_eq!(t.status, TaskStatus::Failed);
6994        assert!(t.diagnostic.is_none());
6995
6996        // Attempt two exhausts the budget: now it is held, and the
6997        // diagnostic is what `magi task show` has to say more than one line.
6998        t.start("run-2".to_owned());
6999        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
7000        assert_eq!(t.status, TaskStatus::Held);
7001        let d = t.diagnostic.expect("a held task must carry its diagnostic");
7002        assert!(d.contains("cargo test"), "{d}");
7003    }
7004
7005    #[test]
7006    fn a_held_task_names_the_open_question_it_is_waiting_on() {
7007        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
7008        // `magi ask` question settled Held with `hold_reason: null`, so the
7009        // notification said nothing actionable. `note_open_question` should
7010        // append the question id to whatever `handed_off` already wrote.
7011        crate::run::pin_test_home();
7012        let home = crate::run::home();
7013        let state = run_state(RunStatus::VerifiedNoop);
7014        let mut q = ask::Question::new(
7015            state.id.clone(),
7016            "implement".to_owned(),
7017            "impl-A".to_owned(),
7018            "is this really a no-op?".to_owned(),
7019            String::new(),
7020            Vec::new(),
7021        );
7022        Questions::at(home.join("questions")).put(&mut q).unwrap();
7023
7024        let verdict = Verdict {
7025            status: RunStatus::VerifiedNoop,
7026            left_pr: false,
7027            quota_hit: false,
7028            parked: false,
7029            no_viable_candidates: false,
7030        };
7031        let mut t = task();
7032        t.start(state.id.clone());
7033        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
7034
7035        assert_eq!(t.status, TaskStatus::Held);
7036        let reason = t.hold_reason.expect("a held task must record why");
7037        assert!(
7038            reason.starts_with("run ended agent-verified no-op"),
7039            "the original settle reason must survive unchanged: {reason}"
7040        );
7041        assert!(
7042            reason.contains(q.short()),
7043            "the open question's id must be named so the notice is actionable: {reason}"
7044        );
7045    }
7046
7047    #[test]
7048    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
7049        crate::run::pin_test_home();
7050        let state = run_state(RunStatus::VerifiedNoop);
7051
7052        let verdict = Verdict {
7053            status: RunStatus::VerifiedNoop,
7054            left_pr: false,
7055            quota_hit: false,
7056            parked: false,
7057            no_viable_candidates: false,
7058        };
7059        let mut t = task();
7060        t.start(state.id.clone());
7061        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
7062
7063        assert_eq!(t.status, TaskStatus::Held);
7064        assert_eq!(
7065            t.hold_reason.as_deref(),
7066            Some("run ended agent-verified no-op"),
7067            "nothing to append when the question was already answered or never asked"
7068        );
7069    }
7070
7071    #[test]
7072    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
7073        crate::run::pin_test_home();
7074        let mut first = run_state(RunStatus::Blocked);
7075        first.id = "20260101-000000-sup1".to_owned();
7076        first.save().unwrap();
7077        let mut second = run_state(RunStatus::Merged);
7078        second.id = "20260101-000000-sup2".to_owned();
7079        second.save().unwrap();
7080
7081        let mut t = task();
7082        t.runs = vec![first.id.clone(), second.id.clone()];
7083        t.status = TaskStatus::Done;
7084
7085        supersede_prior_runs(&t, &crate::run::home());
7086
7087        assert_eq!(
7088            RunState::load(&first.id).unwrap().status,
7089            RunStatus::Superseded,
7090            "the first attempt's Blocked no longer needs anyone's attention"
7091        );
7092        assert_eq!(
7093            RunState::load(&second.id).unwrap().status,
7094            RunStatus::Merged,
7095            "the run that actually succeeded is left exactly as it was"
7096        );
7097    }
7098
7099    #[test]
7100    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
7101        // `is_working_on` alone only proves a *daemon* claim; a `magi run
7102        // --resume` invoked by hand outside the daemon never touches
7103        // `daemon.json` at all, so it would look identical to a genuinely
7104        // idle run without also consulting `RunState::liveness`, which reads
7105        // this run's own recorded `driver_pid` instead.
7106        crate::run::pin_test_home();
7107        let mut first = run_state(RunStatus::Blocked);
7108        first.id = "20260101-000000-sup9".to_owned();
7109        // This test process's own pid: guaranteed alive without needing a
7110        // real second process or daemon.
7111        first.driver_pid = Some(std::process::id());
7112        first.driver_started_at = Some(
7113            crate::proc::process_started_at(std::process::id())
7114                .expect("this test process's own start time must be queryable"),
7115        );
7116        first.save().unwrap();
7117        let mut second = run_state(RunStatus::Merged);
7118        second.id = "20260101-000000-supa".to_owned();
7119        second.save().unwrap();
7120
7121        let mut t = task();
7122        t.runs = vec![first.id.clone(), second.id.clone()];
7123        t.status = TaskStatus::Done;
7124
7125        supersede_prior_runs(&t, &crate::run::home());
7126
7127        assert_eq!(
7128            RunState::load(&first.id).unwrap().status,
7129            RunStatus::Blocked,
7130            "a live driver_pid means something is still actually working this run, \
7131             even though no daemon claims it - rewriting under it would just be \
7132             undone the next time that process saves"
7133        );
7134    }
7135
7136    #[test]
7137    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
7138        // The first resweep must skip a still-live attempt exactly like
7139        // `supersede_prior_runs` itself does; a later resweep, once that
7140        // process is no longer actually driving it, is what closes the gap
7141        // `supersede_prior_runs` alone leaves - a task only ever reaches
7142        // `Done` once, so nothing else would ever look at this run again.
7143        let dir = tempfile::tempdir().unwrap();
7144        let home = dir.path().to_path_buf();
7145        let queue = Queue::at(dir.path().join("queue"));
7146
7147        let mut first = run_state(RunStatus::Blocked);
7148        first.id = "20260101-000000-supd".to_owned();
7149        first.driver_pid = Some(std::process::id());
7150        first.driver_started_at = Some(
7151            crate::proc::process_started_at(std::process::id())
7152                .expect("this test process's own start time must be queryable"),
7153        );
7154        first.save_under(&home).unwrap();
7155        let mut second = run_state(RunStatus::Merged);
7156        second.id = "20260101-000000-supe".to_owned();
7157        second.save_under(&home).unwrap();
7158
7159        let mut t = task();
7160        t.runs = vec![first.id.clone(), second.id.clone()];
7161        t.status = TaskStatus::Done;
7162        queue.put(&mut t).unwrap();
7163
7164        resweep_superseded_attempts(&queue, &home);
7165        assert_eq!(
7166            RunState::load_under(&first.id, &home).unwrap().status,
7167            RunStatus::Blocked,
7168            "still live on the first pass, so still untouched"
7169        );
7170
7171        // Stand in for the manual process no longer being the one driving
7172        // this run: same pid (this test process really is still alive), but
7173        // an identity marker that no longer matches it - see
7174        // `RunState::liveness`'s own doc for why a mismatched
7175        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
7176        let mut stale = RunState::load_under(&first.id, &home).unwrap();
7177        stale.driver_started_at = Some("1".to_owned());
7178        stale.save_under(&home).unwrap();
7179
7180        resweep_superseded_attempts(&queue, &home);
7181        assert_eq!(
7182            RunState::load_under(&first.id, &home).unwrap().status,
7183            RunStatus::Superseded,
7184            "the second pass catches up what the first one correctly skipped"
7185        );
7186    }
7187
7188    #[test]
7189    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
7190        crate::run::pin_test_home();
7191        let mut first = run_state(RunStatus::Blocked);
7192        first.id = "20260101-000000-sup3".to_owned();
7193        first.save().unwrap();
7194        let mut second = run_state(RunStatus::Blocked);
7195        second.id = "20260101-000000-sup4".to_owned();
7196        second.save().unwrap();
7197
7198        let mut t = task();
7199        t.runs = vec![first.id.clone(), second.id.clone()];
7200        // Still retrying: nothing about this task's story is settled yet, so
7201        // neither Blocked run may be relabelled, even though a later attempt
7202        // already exists.
7203        t.status = TaskStatus::Failed;
7204
7205        supersede_prior_runs(&t, &crate::run::home());
7206
7207        assert_eq!(
7208            RunState::load(&first.id).unwrap().status,
7209            RunStatus::Blocked
7210        );
7211        assert_eq!(
7212            RunState::load(&second.id).unwrap().status,
7213            RunStatus::Blocked
7214        );
7215    }
7216
7217    #[test]
7218    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
7219        // `magi task done` (or the API's equivalent) can close a task with no
7220        // run of its own ever having succeeded - there is nothing here that
7221        // counts as "the attempt that finished it", so nothing is rewritten.
7222        crate::run::pin_test_home();
7223        let mut first = run_state(RunStatus::Blocked);
7224        first.id = "20260101-000000-sup5".to_owned();
7225        first.save().unwrap();
7226
7227        let mut t = task();
7228        t.runs = vec![first.id.clone()];
7229        t.status = TaskStatus::Done;
7230
7231        supersede_prior_runs(&t, &crate::run::home());
7232
7233        assert_eq!(
7234            RunState::load(&first.id).unwrap().status,
7235            RunStatus::Blocked,
7236            "a single-attempt task has no earlier run to supersede"
7237        );
7238    }
7239
7240    #[test]
7241    fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
7242        // `magi task done` (or the web/conductor equivalents) can close a
7243        // task in any status, including one whose *last* recorded attempt is
7244        // itself still `Blocked`/`Failed` - a manual merge magi's own loop
7245        // never watched, say. `runs.last()` being `Done`-adjacent is not
7246        // proof it actually succeeded, so nothing earlier may be relabelled
7247        // on its say-so alone.
7248        crate::run::pin_test_home();
7249        let mut first = run_state(RunStatus::Blocked);
7250        first.id = "20260101-000000-supb".to_owned();
7251        first.save().unwrap();
7252        let mut second = run_state(RunStatus::Failed);
7253        second.id = "20260101-000000-supc".to_owned();
7254        second.save().unwrap();
7255
7256        let mut t = task();
7257        t.runs = vec![first.id.clone(), second.id.clone()];
7258        t.status = TaskStatus::Done;
7259
7260        supersede_prior_runs(&t, &crate::run::home());
7261
7262        assert_eq!(
7263            RunState::load(&first.id).unwrap().status,
7264            RunStatus::Blocked,
7265            "the task's last attempt never landed, so there is nothing here \
7266             actually superseding it"
7267        );
7268    }
7269
7270    #[test]
7271    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
7272        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
7273        // to look" - `Failed` and `VerifiedNoop` are already their own
7274        // terminal answers and must not be relabelled into a third one.
7275        crate::run::pin_test_home();
7276        let mut failed = run_state(RunStatus::Failed);
7277        failed.id = "20260101-000000-sup6".to_owned();
7278        failed.save().unwrap();
7279        let mut noop = run_state(RunStatus::VerifiedNoop);
7280        noop.id = "20260101-000000-sup7".to_owned();
7281        noop.save().unwrap();
7282        let mut winner = run_state(RunStatus::Ready);
7283        winner.id = "20260101-000000-sup8".to_owned();
7284        winner.save().unwrap();
7285
7286        let mut t = task();
7287        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
7288        t.status = TaskStatus::Done;
7289
7290        supersede_prior_runs(&t, &crate::run::home());
7291
7292        assert_eq!(
7293            RunState::load(&failed.id).unwrap().status,
7294            RunStatus::Failed
7295        );
7296        assert_eq!(
7297            RunState::load(&noop.id).unwrap().status,
7298            RunStatus::VerifiedNoop
7299        );
7300    }
7301
7302    fn approval_question(run: &str) -> ask::Question {
7303        ask::Question::new(
7304            run.to_owned(),
7305            land::APPROVAL_NODE.to_owned(),
7306            "land".to_owned(),
7307            "merge?".to_owned(),
7308            String::new(),
7309            vec!["merge".to_owned(), "hold".to_owned()],
7310        )
7311    }
7312
7313    #[test]
7314    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
7315        crate::run::pin_test_home();
7316        let mut state = run_state(RunStatus::Landing);
7317        state.id = "20260101-000000-fre1".to_owned();
7318        state.parked = true;
7319        state.save().unwrap();
7320        ask::Questions::open()
7321            .put(&mut approval_question(&state.id))
7322            .unwrap();
7323
7324        let mut t = task();
7325        t.runs.push(state.id.clone());
7326        assert_eq!(
7327            land_resume_state(&t),
7328            LandResume::StillWaiting,
7329            "nobody has answered and the timeout has not passed"
7330        );
7331    }
7332
7333    #[test]
7334    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
7335        crate::run::pin_test_home();
7336        let mut state = run_state(RunStatus::Gating);
7337        state.id = "20260101-000000-gt01".to_owned();
7338        state.parked = true;
7339        state.config.graph.answer_timeout = 60;
7340        state.github_text = Some(crate::run::GithubTextAsk {
7341            rewrite: None,
7342            fingerprint: "f".into(),
7343            title: true,
7344            body: false,
7345            categories: vec!["title-language".into()],
7346            question: None,
7347            asks: 1,
7348            resolved: false,
7349            chosen_title: None,
7350            choice: None,
7351        });
7352        state.save().unwrap();
7353        let store = ask::Questions::open();
7354        let mut q = ask::Question::new(
7355            state.id.clone(),
7356            crate::github_text::ASK_NODE.to_owned(),
7357            crate::github_text::ASK_SEAT.to_owned(),
7358            "s".into(),
7359            String::new(),
7360            vec!["use fallback".into()],
7361        );
7362        store.put(&mut q).unwrap();
7363        let mut t = task();
7364        t.runs.push(state.id.clone());
7365        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
7366        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
7367        store.put(&mut q).unwrap();
7368        assert_eq!(land_resume_state(&t), LandResume::Ready);
7369        assert!(!store.get(&q.id).unwrap().status.open());
7370        // Once decided, a parked run is an ordinary candidate again.
7371        state.github_text.as_mut().unwrap().resolved = true;
7372        state.save().unwrap();
7373        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
7374    }
7375
7376    #[test]
7377    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
7378        // `ask::ask_and_wait`'s own deadline used to retire a question
7379        // nobody answered; land's approval bypasses that wait (see
7380        // `land::approval_gate`), so this is now the only place
7381        // `graph.answer_timeout` is enforced for a land approval at all.
7382        crate::run::pin_test_home();
7383        let mut state = run_state(RunStatus::Landing);
7384        state.id = "20260101-000000-exp1".to_owned();
7385        state.parked = true;
7386        state.config.graph.answer_timeout = 60;
7387        state.save().unwrap();
7388
7389        let store = ask::Questions::open();
7390        let mut q = approval_question(&state.id);
7391        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
7392        store.put(&mut q).unwrap();
7393
7394        let mut t = task();
7395        t.runs.push(state.id.clone());
7396        assert_eq!(
7397            land_resume_state(&t),
7398            LandResume::Ready,
7399            "an expired question must not be waited on forever"
7400        );
7401
7402        let after = store.get(&q.id).unwrap();
7403        assert!(
7404            !after.status.open(),
7405            "the question is abandoned, not silently ignored"
7406        );
7407        assert!(
7408            after.resolution().is_none(),
7409            "an abandoned question is not read as a decision"
7410        );
7411    }
7412
7413    #[test]
7414    fn reclaim_settles_a_running_task_against_its_last_run() {
7415        let mut t = task();
7416        t.start("20260904-000000-4043".to_owned());
7417        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
7418        assert_eq!(
7419            t.status,
7420            TaskStatus::Done,
7421            "a run that actually finished must not stay `running` forever"
7422        );
7423    }
7424
7425    #[test]
7426    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
7427        let mut t = task();
7428        t.start("20260904-000000-4043".to_owned());
7429        t.last_error = Some("earlier trouble".to_owned());
7430        let mut state = run_state(RunStatus::Judging);
7431        state.parked = true;
7432        reclaim(&mut t, Some(state), 1, "en");
7433        assert_eq!(t.status, TaskStatus::Parked);
7434        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
7435        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
7436        assert!(t.park_reason.is_some());
7437        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
7438        assert!(!t.fresh_start);
7439        assert!(t.status.runnable());
7440    }
7441
7442    #[test]
7443    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
7444        let mut t = task();
7445        t.start("20260904-000000-4043".to_owned());
7446        t.last_error = Some("earlier trouble".to_owned());
7447        settle(
7448            &mut t,
7449            Verdict {
7450                status: RunStatus::Judging,
7451                left_pr: false,
7452                quota_hit: false,
7453                parked: true,
7454                no_viable_candidates: false,
7455            },
7456            "parked after `judging`",
7457            1,
7458        );
7459        assert_eq!(t.status, TaskStatus::Parked);
7460        assert_eq!(t.attempts, 0);
7461        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
7462        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
7463        assert_eq!(t.schema, crate::queue::SCHEMA);
7464        assert!(
7465            crate::notices::task_held(&t).is_none(),
7466            "a park is not news"
7467        );
7468        t.start("20260904-000000-4043".to_owned());
7469        assert_eq!(t.park_reason, None);
7470    }
7471
7472    #[test]
7473    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
7474        // A blocked run with attempts left goes back to `Failed`, exactly as
7475        // it would from `attempt` itself - `reclaim` must not invent a second
7476        // policy for a task a daemon merely stopped without reporting.
7477        let mut t = task();
7478        t.start("20260904-000000-4043".to_owned());
7479        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
7480        assert_eq!(t.status, TaskStatus::Failed);
7481        assert!(t.status.runnable());
7482    }
7483
7484    #[test]
7485    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
7486        let mut t = task();
7487        t.start("20260904-000000-4043".to_owned());
7488        assert_eq!(t.attempts, 1);
7489        let mut run = run_state(RunStatus::Implementing);
7490        run.id = "20260904-000000-4043".to_owned();
7491        run.begin_pass();
7492        let cause = crate::run::ParkCause::Upgrade {
7493            from: "0.121.0".to_owned(),
7494            to: Some("0.121.1".to_owned()),
7495        };
7496        run.end_pass_parked(cause.clone());
7497        run.parked = true;
7498        let verdict = Verdict {
7499            status: run.status,
7500            left_pr: false,
7501            quota_hit: false,
7502            parked: true,
7503            no_viable_candidates: false,
7504        };
7505        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
7506        assert_eq!(t.attempts, 0);
7507        assert_eq!(t.passes.len(), 1);
7508        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
7509        assert_eq!(t.passes[0].parked, Some(cause));
7510        assert_eq!(t.passes[0].pass_index, 0);
7511
7512        // A resumed pass that then fails spends its attempt, and the earlier
7513        // pass's entry is untouched.
7514        t.start("20260904-000000-4043".to_owned());
7515        run.begin_pass();
7516        run.status = RunStatus::Failed;
7517        let verdict = Verdict {
7518            status: RunStatus::Failed,
7519            left_pr: false,
7520            quota_hit: false,
7521            parked: false,
7522            no_viable_candidates: false,
7523        };
7524        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
7525        assert_eq!(t.passes.len(), 2);
7526        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
7527        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
7528        assert_eq!(t.passes[1].pass_index, 1);
7529        assert_eq!(t.attempts, 1);
7530    }
7531
7532    #[test]
7533    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
7534        let mut t = task();
7535        t.start("20260904-000000-4043".to_owned());
7536        reclaim(&mut t, None, 2, "en");
7537        assert_eq!(t.status, TaskStatus::Held);
7538        assert!(
7539            t.last_error
7540                .as_deref()
7541                .is_some_and(|e| e.contains("running")),
7542            "the operator needs to know why this task was held"
7543        );
7544    }
7545
7546    #[test]
7547    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
7548        let dir = tempfile::tempdir().unwrap();
7549        let queue = Queue::at(dir.path().to_path_buf());
7550
7551        // No run recorded, so this never has to touch `RunState::load`.
7552        let mut orphaned = task();
7553        orphaned.id = "20260904-000000-orph".to_owned();
7554        orphaned.status = TaskStatus::Running;
7555        orphaned.attempts = 1;
7556        queue.put(&mut orphaned).unwrap();
7557
7558        let mut alive = task();
7559        alive.id = "20260904-000000-live".to_owned();
7560        alive.status = TaskStatus::Running;
7561        alive.attempts = 1;
7562        queue.put(&mut alive).unwrap();
7563        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
7564
7565        let mut queued = task();
7566        queued.id = "20260904-000000-wait".to_owned();
7567        queue.put(&mut queued).unwrap();
7568
7569        let reclaimed = reclaim_orphaned_running(&queue, 2);
7570        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
7571
7572        assert_eq!(
7573            queue.get(&orphaned.id).unwrap().status,
7574            TaskStatus::Held,
7575            "nothing was driving it and there was no run to recover"
7576        );
7577        assert_eq!(
7578            queue.get(&alive.id).unwrap().status,
7579            TaskStatus::Running,
7580            "a live claim must protect the task it belongs to"
7581        );
7582        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
7583    }
7584
7585    /// Read a run.json back from an explicit `home`, the same way
7586    /// `reclaim_abandoned_runs` itself does - never through the
7587    /// process-global `RunState::load`, which this test's own `home` (an
7588    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
7589    /// use at all.
7590    fn read_run_under(home: &Path, id: &str) -> RunState {
7591        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
7592        serde_json::from_str(&body).unwrap()
7593    }
7594
7595    #[test]
7596    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
7597        let dir = tempfile::tempdir().unwrap();
7598        let home = dir.path().to_path_buf();
7599        let now = Timestamp::now();
7600        let overrun_seat = || crate::run::ActiveSeat {
7601            node: "implement".to_owned(),
7602            started_at: now - jiff::SignedDuration::new(21_000, 0),
7603            timeout_secs: 3_600,
7604            attempt: 0,
7605            task: None,
7606            command: None,
7607            index: None,
7608            total: None,
7609        };
7610
7611        let mut dead = run_state(RunStatus::Implementing);
7612        dead.id = "20260101-000000-dead".to_owned();
7613        dead.active.insert("impl-A".to_owned(), overrun_seat());
7614        // A `driver_pid` the injected query below confirms gone outright —
7615        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
7616        dead.driver_pid = Some(4242);
7617        dead.save_under(&home).unwrap();
7618
7619        // Same shape, but a live daemon's heartbeat names it: must be left
7620        // exactly alone, however far past its own timeout the seat sits.
7621        let mut alive = run_state(RunStatus::Implementing);
7622        alive.id = "20260101-000000-aliv".to_owned();
7623        alive.active.insert("impl-A".to_owned(), overrun_seat());
7624        alive.save_under(&home).unwrap();
7625        let mut status = Status::new();
7626        status.current = vec![Current {
7627            task: "20260101-000000-task".to_owned(),
7628            run: alive.id.clone(),
7629        }];
7630        write_status_to(&home.join("daemon.json"), &status).unwrap();
7631
7632        // The abandoned seat left an open question behind: nobody is left to
7633        // read an answer once the run is failed, and this must not wait for
7634        // some later daemon startup's own sweep to notice that.
7635        let questions = Questions::at(home.join("questions"));
7636        let mut q = ask::Question::new(
7637            dead.id.clone(),
7638            "implement".to_owned(),
7639            "impl-A".to_owned(),
7640            "Which storage backend?".to_owned(),
7641            String::new(),
7642            vec!["SQLite".to_owned(), "Redis".to_owned()],
7643        );
7644        questions.put(&mut q).unwrap();
7645
7646        let abandoned = reclaim_abandoned_runs_with(
7647            &home,
7648            now,
7649            |pid| if pid == 4242 { Some(false) } else { None },
7650            |_| panic!("a query answering Dead outright needs no identity corroboration"),
7651        );
7652        assert_eq!(abandoned, vec![dead.id.clone()]);
7653
7654        let reloaded = read_run_under(&home, &dead.id);
7655        assert_eq!(reloaded.status, RunStatus::Failed);
7656        assert!(reloaded.active.is_empty());
7657        assert!(
7658            !questions.get(&q.id).unwrap().status.open(),
7659            "the failed run's own open question must be settled in the same pass"
7660        );
7661
7662        let still_alive = read_run_under(&home, &alive.id);
7663        assert_eq!(
7664            still_alive.status,
7665            RunStatus::Implementing,
7666            "a live daemon's claim protects it"
7667        );
7668        assert!(!still_alive.active.is_empty());
7669    }
7670
7671    /// The exact shape a review round flagged as broken: `magi serve` running
7672    /// in this same `home` scans *every* run on disk, including a manual
7673    /// `magi review` / `magi run` this daemon never started and that
7674    /// therefore claims no heartbeat of its own. Before this scan asked
7675    /// `liveness` rather than just `is_working_on`, a manual run whose active
7676    /// seat merely ran a little past its own timeout — the CLI finishing up,
7677    /// its result still being collected — got wiped and failed by a daemon
7678    /// that had nothing to do with it, out from under a process that was
7679    /// still very much running.
7680    #[test]
7681    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
7682        let dir = tempfile::tempdir().unwrap();
7683        let home = dir.path().to_path_buf();
7684        let now = Timestamp::now();
7685
7686        let mut manual = run_state(RunStatus::Reviewing);
7687        manual.id = "20260101-000000-manl".to_owned();
7688        manual.active.insert(
7689            "review-1".to_owned(),
7690            crate::run::ActiveSeat {
7691                node: "review".to_owned(),
7692                started_at: now - jiff::SignedDuration::new(21_000, 0),
7693                timeout_secs: 3_600,
7694                attempt: 0,
7695                task: None,
7696                command: None,
7697                index: None,
7698                total: None,
7699            },
7700        );
7701        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
7702        // but a real, still-running process: `liveness` must corroborate this
7703        // as `Live`, not read the missing daemon claim as death.
7704        manual.driver_pid = Some(4242);
7705        manual.driver_started_at = Some("1790000000".to_owned());
7706        manual.save_under(&home).unwrap();
7707
7708        let abandoned = reclaim_abandoned_runs_with(
7709            &home,
7710            now,
7711            |pid| if pid == 4242 { Some(true) } else { None },
7712            |pid| {
7713                if pid == 4242 {
7714                    Some("1790000000".to_owned())
7715                } else {
7716                    None
7717                }
7718            },
7719        );
7720        assert!(
7721            abandoned.is_empty(),
7722            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
7723        );
7724
7725        let reloaded = read_run_under(&home, &manual.id);
7726        assert_eq!(reloaded.status, RunStatus::Reviewing);
7727        assert!(!reloaded.active.is_empty());
7728    }
7729
7730    #[test]
7731    fn an_already_claimed_task_is_skipped_rather_than_failed() {
7732        let dir = tempfile::tempdir().unwrap();
7733        let queue = Queue::at(dir.path().to_path_buf());
7734        let mut only = task();
7735        queue.put(&mut only).unwrap();
7736
7737        let _elsewhere = queue.claim(&only.id).unwrap();
7738        let candidates = runnable(&queue);
7739        assert_eq!(candidates.len(), 1, "the task is still runnable");
7740        assert!(
7741            queue.claim(&candidates[0].id).is_err(),
7742            "the loop cannot take a claim somebody else holds"
7743        );
7744
7745        let after = queue.get(&only.id).unwrap();
7746        assert_eq!(after.status, TaskStatus::Queued);
7747        assert_eq!(
7748            after.attempts, 0,
7749            "losing the race is not an attempt at the task"
7750        );
7751        assert_eq!(after.last_error, None);
7752    }
7753
7754    #[test]
7755    fn the_status_file_round_trips_and_its_heartbeat_advances() {
7756        let dir = tempfile::tempdir().unwrap();
7757        let path = dir.path().join("daemon.json");
7758
7759        let mut status = Status::new();
7760        status.idle = false;
7761        status.completed = 7;
7762        status.current = vec![Current {
7763            task: "20260902-000000-t111".to_owned(),
7764            run: "20260902-000001-r111".to_owned(),
7765        }];
7766        write_status_to(&path, &status).unwrap();
7767        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
7768        assert_eq!(first.schema, SCHEMA);
7769        assert_eq!(first.pid, std::process::id());
7770        assert!(!first.idle);
7771        assert_eq!(first.completed, 7);
7772        assert_eq!(first.current, status.current);
7773        assert!(
7774            !path.with_extension("json.tmp").exists(),
7775            "the temp file is renamed, not left behind"
7776        );
7777
7778        std::thread::sleep(Duration::from_millis(5));
7779        status.updated_at = Timestamp::now();
7780        status.polls = 3;
7781        write_status_to(&path, &status).unwrap();
7782        let second: Status =
7783            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
7784        assert!(
7785            second.updated_at > first.updated_at,
7786            "a reader can only detect staleness if the heartbeat moves"
7787        );
7788        assert_eq!(
7789            second.started_at, first.started_at,
7790            "the start time is not a heartbeat"
7791        );
7792        assert_eq!(second.polls, 3);
7793    }
7794
7795    #[test]
7796    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
7797        let dir = tempfile::tempdir().unwrap();
7798
7799        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
7800
7801        let mut status = Status::new();
7802        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
7803        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7804        let stale = read_status(dir.path()).unwrap();
7805        assert!(
7806            !stale.running(Timestamp::now()),
7807            "a minute without a heartbeat is a dead daemon, not a busy one"
7808        );
7809        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
7810
7811        status.updated_at = Timestamp::now();
7812        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7813        let fresh = read_status(dir.path()).unwrap();
7814        assert!(fresh.running(Timestamp::now()));
7815    }
7816
7817    #[test]
7818    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
7819        let dir = tempfile::tempdir().unwrap();
7820        let now = Timestamp::now();
7821        let mine = "20260903-080619-01c2";
7822
7823        assert!(
7824            !is_working_on(dir.path(), mine, now),
7825            "no status file means nobody is working on anything"
7826        );
7827
7828        let mut status = Status::new();
7829        status.current = vec![Current {
7830            task: "20260903-080340-0167".to_owned(),
7831            run: mine.to_owned(),
7832        }];
7833        status.updated_at = now;
7834        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7835        assert!(is_working_on(dir.path(), mine, now));
7836        assert!(
7837            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
7838            "a daemon busy with one run is not working on another"
7839        );
7840
7841        // A killed daemon stops writing heartbeats but leaves the file behind
7842        // naming the run it died in. That run must not be undeletable forever.
7843        status.updated_at = now - jiff::SignedDuration::from_secs(600);
7844        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7845        assert!(
7846            !is_working_on(dir.path(), mine, now),
7847            "a stale heartbeat is a dead daemon, so its run is a leftover"
7848        );
7849    }
7850
7851    #[test]
7852    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
7853        let dir = tempfile::tempdir().unwrap();
7854        let now = Timestamp::now();
7855
7856        assert!(
7857            !is_working_on_short(dir.path(), "01c2", now),
7858            "no status file means nobody is working on anything"
7859        );
7860
7861        let mut status = Status::new();
7862        status.current = vec![Current {
7863            task: "20260903-080340-0167".to_owned(),
7864            run: "20260903-080619-01c2".to_owned(),
7865        }];
7866        status.updated_at = now;
7867        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7868        assert!(
7869            is_working_on_short(dir.path(), "01c2", now),
7870            "the run's short id is the last block of its full id"
7871        );
7872        assert!(
7873            !is_working_on_short(dir.path(), "3cbf", now),
7874            "a daemon busy with one worktree bay is not working on another"
7875        );
7876    }
7877
7878    #[test]
7879    fn a_newer_status_file_still_yields_a_reading() {
7880        let dir = tempfile::tempdir().unwrap();
7881        // A field this build has never heard of must not turn the reading into
7882        // nothing at all; that is the whole reason the reader is permissive.
7883        std::fs::write(
7884            dir.path().join("daemon.json"),
7885            serde_json::json!({
7886                "schema": 2,
7887                "updated_at": Timestamp::now().to_string(),
7888                "idle": true,
7889                "surprise": { "nested": [1, 2, 3] },
7890            })
7891            .to_string(),
7892        )
7893        .unwrap();
7894
7895        let reading = read_status(dir.path()).expect("a forward-compatible read");
7896        assert!(reading.running(Timestamp::now()));
7897        assert!(reading.idle);
7898        assert!(reading.current.is_empty());
7899    }
7900
7901    #[test]
7902    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
7903        // A daemon started before `current` became a list keeps writing this
7904        // shape on every heartbeat until it is restarted. A rolling upgrade
7905        // - a newer `magi web` or `magi doctor` reading an older `magi
7906        // serve`'s heartbeat - must still see the run it is on, not "no
7907        // daemon" from a type mismatch failing the whole struct.
7908        let dir = tempfile::tempdir().unwrap();
7909        std::fs::write(
7910            dir.path().join("daemon.json"),
7911            serde_json::json!({
7912                "schema": 1,
7913                "pid": 4242,
7914                "updated_at": Timestamp::now().to_string(),
7915                "idle": false,
7916                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
7917                "completed": 3,
7918                "polls": 9,
7919            })
7920            .to_string(),
7921        )
7922        .unwrap();
7923
7924        let reading = read_status(dir.path()).expect("an older shape must still parse");
7925        assert!(reading.running(Timestamp::now()));
7926        assert_eq!(
7927            reading.current,
7928            vec![Current {
7929                task: "20260902-140501-aaaa".to_owned(),
7930                run: "20260902-140502-bbbb".to_owned(),
7931            }]
7932        );
7933    }
7934
7935    #[test]
7936    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
7937        let dir = tempfile::tempdir().unwrap();
7938        std::fs::write(
7939            dir.path().join("daemon.json"),
7940            serde_json::json!({
7941                "schema": 1,
7942                "updated_at": Timestamp::now().to_string(),
7943                "idle": true,
7944                "current": null,
7945            })
7946            .to_string(),
7947        )
7948        .unwrap();
7949        let with_null = read_status(dir.path()).expect("null must still parse");
7950        assert!(with_null.current.is_empty());
7951
7952        std::fs::write(
7953            dir.path().join("daemon.json"),
7954            serde_json::json!({
7955                "schema": 1,
7956                "updated_at": Timestamp::now().to_string(),
7957                "idle": true,
7958            })
7959            .to_string(),
7960        )
7961        .unwrap();
7962        let absent = read_status(dir.path()).expect("a missing field must still parse");
7963        assert!(absent.current.is_empty());
7964    }
7965
7966    #[test]
7967    fn a_task_without_a_repository_runs_in_the_daemons_default() {
7968        let fallback = Path::new("/default");
7969        let mut blank = task();
7970        blank.repo = PathBuf::new();
7971        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
7972        let mut dot = task();
7973        dot.repo = PathBuf::from(".");
7974        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
7975        assert_eq!(
7976            repo_for(&task(), fallback),
7977            PathBuf::from("/repo"),
7978            "a task that names a repository keeps it"
7979        );
7980    }
7981
7982    #[test]
7983    fn task_implementers_edit_inherits_daemon_config_and_merge() {
7984        let dir = tempfile::tempdir().unwrap();
7985        let path = dir.path().join("explicit.toml");
7986        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
7987        let opts = Opts {
7988            config: Some(path),
7989            merge: Some("none".into()),
7990            ..Default::default()
7991        };
7992        let mut t = task();
7993        t.set_implementers(
7994            2,
7995            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
7996                .unwrap(),
7997        )
7998        .unwrap();
7999        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
8000        assert_eq!(cfg.graph.implementers, 2);
8001        assert_eq!(cfg.graph.judges, 1);
8002        assert_eq!(cfg.merge.mode, MergeMode::None);
8003        t.set_implementers(1, &cfg).unwrap();
8004        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
8005        apply_task_implementers(&mut cfg, &t);
8006        assert_eq!(cfg.graph.implementers, 1);
8007        assert_eq!(cfg.graph.judges, 1);
8008        assert_eq!(cfg.merge.mode, MergeMode::None);
8009    }
8010
8011    #[test]
8012    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
8013        let dir = tempfile::tempdir().unwrap();
8014        let repo = dir.path().join("repo");
8015        std::fs::create_dir(&repo).unwrap();
8016        std::fs::write(
8017            repo.join("magi.toml"),
8018            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
8019        )
8020        .unwrap();
8021        let daemon_config = dir.path().join("daemon.toml");
8022        std::fs::write(
8023            &daemon_config,
8024            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
8025        )
8026        .unwrap();
8027        let opts = Opts {
8028            config: Some(daemon_config),
8029            merge: Some("pr".into()),
8030            ..Default::default()
8031        };
8032        let q = Queue::at(dir.path().join("queue"));
8033        let validation: Config =
8034            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
8035                .unwrap();
8036        // No provenance field on legacy direct tasks: both shapes stay isolated.
8037        for record in ["{}", r#"{"candidates":2}"#] {
8038            let overrides = serde_json::from_str(record).unwrap();
8039            let filing = crate::direct::Filing {
8040                instruction: "work".into(),
8041                title: "direct".into(),
8042                repo: repo.clone(),
8043                source: crate::queue::Source::Human,
8044                solo: false,
8045                overrides,
8046                review_of: None,
8047            };
8048            let filed =
8049                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
8050            let crate::direct::Filed::Standalone {
8051                mut task,
8052                claim: _claim,
8053            } = filed
8054            else {
8055                panic!("local filing")
8056            };
8057            let before = prepare_for(&repo, &opts, &task).unwrap();
8058            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
8059            assert_eq!(
8060                before.merge.mode,
8061                MergeMode::None,
8062                "daemon --merge must not leak"
8063            );
8064            for n in [2, 1, 2] {
8065                task.set_implementers(n, &validation).unwrap();
8066                q.put(&mut task).unwrap();
8067                task = q.get(&task.id).unwrap();
8068                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
8069                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
8070                apply_task_implementers(&mut cfg, &task);
8071                assert_eq!(cfg.graph.implementers, usize::from(n));
8072                assert_eq!(cfg.graph.judges, 2);
8073                assert_eq!(cfg.merge.mode, MergeMode::None);
8074            }
8075        }
8076    }
8077
8078    #[test]
8079    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
8080        let cfg: Config =
8081            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
8082                .unwrap();
8083        let mut t = task();
8084        t.review_of = Some("review-target".into());
8085        t.hold_manual(Some("retry".into()));
8086        let mut previous = RunState::new(
8087            PathBuf::from("/repo"),
8088            "main".into(),
8089            "abc1234".into(),
8090            "review".into(),
8091            cfg.clone(),
8092        );
8093        previous.config.graph.implementers = 2;
8094        for count in [1, 3] {
8095            t.set_implementers(count, &cfg).unwrap();
8096            t.release();
8097            assert_eq!(t.review_of.as_deref(), Some("review-target"));
8098            for proposed in [
8099                Starter::Resume(previous.id.clone()),
8100                Starter::Review("recovery-target".into()),
8101            ] {
8102                assert_eq!(
8103                    starter_with_implementers(&t, Some(&previous), proposed),
8104                    Starter::Review("review-target".into())
8105                );
8106            }
8107            let mut configured = cfg.clone();
8108            apply_task_implementers(&mut configured, &t);
8109            assert_eq!(configured.graph.implementers, usize::from(count));
8110            assert_eq!(previous.config.graph.implementers, 2);
8111        }
8112    }
8113
8114    #[test]
8115    fn task_implementers_dispatch_and_resume_agree() {
8116        let mut t = task();
8117        let cfg: crate::config::Config =
8118            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
8119                .unwrap();
8120        let mut run = RunState::new(
8121            PathBuf::from("/repo"),
8122            "main".into(),
8123            "abc1234".into(),
8124            "work".into(),
8125            cfg.clone(),
8126        );
8127        run.config.graph.implementers = 2;
8128        for n in [2, 1, 3, 2] {
8129            t.set_implementers(n, &cfg).unwrap();
8130            let mut dispatched = cfg.clone();
8131            apply_task_implementers(&mut dispatched, &t);
8132            assert_eq!(dispatched.graph.implementers, usize::from(n));
8133            assert_eq!(implementers_match(&t, &run), n == 2);
8134            for proposed in [
8135                Starter::Resume(run.id.clone()),
8136                Starter::Review("old-branch".into()),
8137            ] {
8138                let expected = if n == 2 {
8139                    proposed.clone()
8140                } else {
8141                    Starter::Start
8142                };
8143                assert_eq!(
8144                    starter_with_implementers(&t, Some(&run), proposed),
8145                    expected
8146                );
8147            }
8148            assert_eq!(
8149                run.config.graph.implementers, 2,
8150                "history must not be rewritten"
8151            );
8152        }
8153        t.solo = false;
8154        t.overrides = None;
8155        assert!(implementers_match(&t, &run));
8156    }
8157
8158    #[test]
8159    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
8160        // Three seats said out loud. What `solo` promises is one candidate
8161        // *whatever the config asks for*, so the contrast has to be a number
8162        // this test owns - it used to be `Config::default()`'s, which became
8163        // 1 when one implementation became the default and left the two
8164        // halves of this test asserting the same thing.
8165        let mut solo_cfg = Config::default();
8166        solo_cfg.graph.implementers = 3;
8167        let mut solo_task = task();
8168        solo_task.solo = true;
8169        apply_task_implementers(&mut solo_cfg, &solo_task);
8170        assert_eq!(solo_cfg.graph.implementers, 1);
8171
8172        let mut plain_cfg = Config::default();
8173        plain_cfg.graph.implementers = 3;
8174        let plain_task = task();
8175        assert!(!plain_task.solo);
8176        apply_task_implementers(&mut plain_cfg, &plain_task);
8177        assert_eq!(
8178            plain_cfg.graph.implementers, 3,
8179            "a task that did not ask to run alone keeps the config's candidates"
8180        );
8181    }
8182
8183    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
8184        QuotaLoss {
8185            seat: seat.into(),
8186            node: "judge".into(),
8187            at: at.parse().unwrap(),
8188            reset: reset.map(str::to_string),
8189        }
8190    }
8191
8192    #[test]
8193    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
8194        let old: Vec<QuotaLoss> = (1..=4)
8195            .map(|i| {
8196                loss(
8197                    &format!("judge-{i}"),
8198                    "2026-09-23T05:23:00Z",
8199                    Some("2:40pm (Asia/Tokyo)"),
8200                )
8201            })
8202            .collect();
8203        let fresh = losses_this_attempt(&old, &old);
8204        assert!(fresh.is_empty());
8205        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
8206        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
8207    }
8208
8209    #[test]
8210    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
8211        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
8212        let now = Timestamp::now();
8213        let mut after = old.clone();
8214        after.push(loss("judge-2", &now.to_string(), None));
8215        let fresh = losses_this_attempt(&old, &after);
8216        assert_eq!(fresh, vec![after[1].clone()]);
8217        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
8218        assert_eq!(
8219            until,
8220            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
8221        );
8222    }
8223
8224    #[test]
8225    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
8226        // `recover_stall` removes judge-1's loss and the retry then hits quota
8227        // again: the vector is the same length, so an index diff sees nothing.
8228        let before = vec![
8229            loss("judge-1", "2026-09-23T05:23:00Z", None),
8230            loss("judge-2", "2026-09-23T05:24:00Z", None),
8231        ];
8232        let after = vec![
8233            loss("judge-2", "2026-09-23T05:24:00Z", None),
8234            loss("judge-1", "2026-09-24T01:00:00Z", None),
8235        ];
8236        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
8237    }
8238
8239    #[test]
8240    fn merge_overrides_are_parsed_or_refused() {
8241        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
8242        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
8243        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
8244        assert!(merge_mode("squash").is_err());
8245    }
8246
8247    #[test]
8248    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
8249        let now = Timestamp::now();
8250        let fallback = Duration::from_secs(300);
8251        let cap = Duration::from_secs(1800);
8252
8253        // No reset hint at all: the fallback.
8254        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
8255
8256        // A reset ten minutes out, well inside the cap: waited for exactly.
8257        let soon = now + jiff::SignedDuration::from_secs(600);
8258        assert_eq!(
8259            quota_wait(Some(soon), now, fallback, cap),
8260            Duration::from_secs(600)
8261        );
8262
8263        // A reset already in the past is not trusted: the fallback, not a
8264        // zero or negative wait that would spin the loop right back around.
8265        let past = now - jiff::SignedDuration::from_secs(60);
8266        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
8267
8268        // A reset further out than the cap is trusted for direction but not
8269        // for magnitude: a parsing slip must not sleep the loop for a day.
8270        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
8271        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
8272    }
8273
8274    #[test]
8275    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
8276        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
8277
8278        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
8279        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
8280
8281        // Same clock reading, but it has already gone by today: read as
8282        // tomorrow's, since the CLI would not still be reporting a limit past
8283        // its own stated reset.
8284        let already_past =
8285            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
8286        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
8287
8288        assert!(
8289            parse_reset_hint("session limit reached", now, now).is_none(),
8290            "free text with no recognised shape is not guessed at"
8291        );
8292        assert!(
8293            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
8294            "an unresolvable zone name is not guessed at either"
8295        );
8296    }
8297
8298    #[test]
8299    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
8300        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
8301
8302        let at = parse_reset_hint(
8303            "You've hit your usage limit. Visit \
8304             https://chatgpt.com/codex/settings/usage to purchase more \
8305             credits or try again at Sep 19th, 2026 5:10 PM.",
8306            now,
8307            now,
8308        )
8309        .expect("the codex reset wording is a recognised shape");
8310        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
8311
8312        // The month is explicit, so a date already earlier in the same
8313        // sentence-implied year than `now` is trusted as written rather than
8314        // rolled forward a year the way the bracketed shape rolls a
8315        // same-day clock reading to tomorrow.
8316        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
8317            .expect("an explicit year needs no rollover");
8318        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
8319
8320        assert!(
8321            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
8322            "a two-digit year is not the documented shape and is not guessed at"
8323        );
8324        assert!(
8325            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
8326            "a four-letter month name is not the documented three-letter abbreviation"
8327        );
8328        assert!(
8329            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
8330            "an explicit zone on the dated shape is a format nobody has \
8331             documented, and is refused rather than guessed at as UTC"
8332        );
8333    }
8334
8335    #[test]
8336    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
8337        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
8338        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
8339
8340        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
8341        assert_eq!(at.as_second() - recorded.as_second(), 3769);
8342
8343        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
8344        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
8345
8346        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
8347            assert!(
8348                parse_reset_hint(bad, now, recorded).is_none(),
8349                "{bad:?} must not be guessed at"
8350            );
8351        }
8352    }
8353
8354    /// A loop whose queue lives in a temp tree and whose poll interval is far
8355    /// longer than the test's patience, so anything that waits out a poll
8356    /// instead of noticing the stop fails rather than merely being slow.
8357    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
8358        let config = dir.join("magi.toml");
8359        std::fs::write(
8360            &config,
8361            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
8362        )
8363        .unwrap();
8364        let opts = Opts {
8365            poll: Duration::from_secs(30),
8366            config: Some(config),
8367            // The explicit fixture config keeps startup cleanup from reading
8368            // machine configuration. This fictional repository likewise
8369            // keeps any best-effort git cleanup away from this checkout.
8370            repo: dir.join("repo"),
8371            ..Opts::default()
8372        };
8373        // The status file goes in a directory that does not exist yet, so its
8374        // creation is itself evidence the loop published one. `worktrees`
8375        // must be just as fictional: the janitor reclaims worktrees under it
8376        // for real, and a test that let it fall through to
8377        // `crate::run::default_worktree_root()` would have it reclaim
8378        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
8379        // which is exactly what happened before this function took the
8380        // parameter at all.
8381        let home = dir.join("home");
8382        let worktrees = dir.join("wt");
8383        (
8384            opts,
8385            Queue::at(dir.join("queue")),
8386            home.join("daemon.json"),
8387            home,
8388            worktrees,
8389        )
8390    }
8391
8392    #[test]
8393    fn a_stop_is_idempotent_and_once_set_stays_set() {
8394        let stop = Stop::new();
8395        assert!(!stop.stopped());
8396
8397        stop.stop();
8398        assert!(stop.stopped());
8399        stop.stop();
8400        assert!(stop.stopped(), "a second stop is not a toggle");
8401
8402        let shared = stop.clone();
8403        assert!(
8404            shared.stopped(),
8405            "a clone is the same stop; that is how the loop and its caller share one"
8406        );
8407    }
8408
8409    #[test]
8410    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
8411        let stop = Stop::new();
8412        stop.enter();
8413        assert!(
8414            !stop.finishing(),
8415            "a busy loop nobody has asked to stop is just running"
8416        );
8417
8418        stop.stop();
8419        assert!(
8420            stop.finishing(),
8421            "a stop asked for mid-run has not landed until the run is settled"
8422        );
8423
8424        stop.exit();
8425        assert!(
8426            !stop.finishing(),
8427            "once the run is settled the stop has landed and there is nothing to finish"
8428        );
8429    }
8430
8431    #[test]
8432    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
8433        let stop = Stop::new();
8434        stop.enter();
8435        stop.enter();
8436        stop.stop();
8437        assert!(stop.finishing(), "two runs still in flight");
8438
8439        stop.exit();
8440        assert!(
8441            stop.finishing(),
8442            "one run finished, but a sibling is still working"
8443        );
8444
8445        stop.exit();
8446        assert!(
8447            !stop.finishing(),
8448            "the last run out is what actually lands the stop"
8449        );
8450    }
8451
8452    #[tokio::test]
8453    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
8454        let dir = tempfile::tempdir().unwrap();
8455        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
8456        let stop = Stop::new();
8457        stop.stop();
8458
8459        let began = std::time::Instant::now();
8460        tokio::time::timeout(
8461            Duration::from_secs(2),
8462            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
8463        )
8464        .await
8465        .expect("a stopped loop must return, not sit out its poll interval")
8466        .expect("the loop's own setup and teardown must not fail");
8467        assert!(
8468            began.elapsed() < opts.poll,
8469            "returned only after {:?}, which is a poll interval, not a stop",
8470            began.elapsed()
8471        );
8472    }
8473
8474    #[tokio::test]
8475    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
8476        let dir = tempfile::tempdir().unwrap();
8477        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
8478        let stop = Stop::new();
8479
8480        // Asked for after the loop is already parked on its empty queue, which
8481        // is the case an operator tapping stop on a phone actually hits.
8482        let asker = {
8483            let stop = stop.clone();
8484            tokio::spawn(async move {
8485                tokio::time::sleep(Duration::from_millis(20)).await;
8486                stop.stop();
8487            })
8488        };
8489
8490        let began = std::time::Instant::now();
8491        tokio::time::timeout(
8492            Duration::from_secs(2),
8493            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
8494        )
8495        .await
8496        .expect("a stop asked for while idle must wake the wait")
8497        .expect("the loop's own setup and teardown must not fail");
8498        asker.await.unwrap();
8499        assert!(
8500            began.elapsed() < opts.poll,
8501            "returned only after {:?}, so the stop waited on the sleep",
8502            began.elapsed()
8503        );
8504    }
8505
8506    #[tokio::test]
8507    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
8508        let dir = tempfile::tempdir().unwrap();
8509        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
8510        let stop = Stop::new();
8511        stop.stop();
8512
8513        tokio::time::timeout(
8514            Duration::from_secs(2),
8515            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
8516        )
8517        .await
8518        .expect("a stopped loop must return")
8519        .expect("the loop's own setup and teardown must not fail");
8520
8521        assert!(
8522            home.is_dir(),
8523            "the loop did publish a status file, so its removal is the teardown and not an absence"
8524        );
8525        assert!(
8526            !status_file.exists(),
8527            "a stopped loop clears its status file"
8528        );
8529        assert!(
8530            read_status(&home).is_none(),
8531            "a reader must see no daemon at all, not a heartbeat that merely stopped"
8532        );
8533    }
8534
8535    #[tokio::test]
8536    async fn once_runs_startup_housekeeping_before_an_empty_queue_exits() {
8537        let dir = tempfile::tempdir().unwrap();
8538        let (mut opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
8539        opts.once = true;
8540
8541        let mut settled = RunState::new(
8542            dir.path().join("repo"),
8543            "main".to_owned(),
8544            "abc1234".to_owned(),
8545            "fixture".to_owned(),
8546            Config::default(),
8547        );
8548        settled.status = RunStatus::Ready;
8549        let run_dir = home.join("runs").join(&settled.id);
8550        std::fs::create_dir_all(&run_dir).unwrap();
8551        std::fs::write(
8552            run_dir.join("run.json"),
8553            serde_json::to_string_pretty(&settled).unwrap(),
8554        )
8555        .unwrap();
8556        let questions = Questions::at(home.join("questions"));
8557        let mut question = ask::Question::new(
8558            settled.id.clone(),
8559            "review".to_owned(),
8560            "reviewer-1".to_owned(),
8561            "Continue?".to_owned(),
8562            String::new(),
8563            Vec::new(),
8564        );
8565        questions.put(&mut question).unwrap();
8566
8567        drive(&opts, &queue, &status_file, &home, &worktrees, &Stop::new())
8568            .await
8569            .unwrap();
8570
8571        assert_eq!(
8572            questions.get(&question.id).unwrap().status,
8573            ask::QuestionStatus::Abandoned,
8574            "an empty --once drain still performs startup question cleanup"
8575        );
8576    }
8577
8578    #[test]
8579    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
8580        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
8581
8582        assert!(
8583            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
8584            "never checked before: due at once"
8585        );
8586
8587        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
8588        assert!(
8589            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
8590            "well inside the interval: not due yet"
8591        );
8592
8593        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
8594        assert!(
8595            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
8596            "exactly at the edge: not yet due, same convention as `clean::due`"
8597        );
8598
8599        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
8600        assert!(
8601            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
8602            "past the interval: due again"
8603        );
8604    }
8605
8606    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
8607    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
8608    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
8609    /// and the congestion test below both need, and must not drift apart.
8610    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
8611        let config = dir.join("magi.toml");
8612        // A literal (single-quoted) TOML string, not a basic one: the cache
8613        // path is a Windows path full of backslashes, and a basic string
8614        // would have TOML try to interpret `\U` (from `\Users\...`) as a
8615        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
8616        // `{{ vars.cache }}` rendering documents.
8617        std::fs::write(
8618            &config,
8619            format!(
8620                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
8621                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
8622                cache_dir.display()
8623            ),
8624        )
8625        .unwrap();
8626        Opts {
8627            config: Some(config),
8628            repo: dir.join("repo"),
8629            ..Opts::default()
8630        }
8631    }
8632
8633    #[tokio::test]
8634    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
8635        let dir = tempfile::tempdir().unwrap();
8636        let home = dir.path().join("home");
8637        let cache_dir = dir.path().join("cache");
8638        std::fs::create_dir_all(&cache_dir).unwrap();
8639        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
8640        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
8641
8642        // Nobody has asked this daemon to stop, which is the ordinary case;
8643        // the skip that a stop buys is asserted by its own test below.
8644        let running = Stop::new();
8645        let mut last_checked = None;
8646        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
8647        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
8648            .await;
8649        assert_eq!(
8650            crate::disk::dir_size(&cache_dir),
8651            0,
8652            "over the cap on the first check ever: pruned at once, no idle queue required"
8653        );
8654        assert_eq!(last_checked, Some(t0));
8655
8656        // A fresh oversized file lands, but the next check is not due yet.
8657        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
8658        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
8659        maybe_prune_cache_between_runs(
8660            &opts.repo,
8661            &opts,
8662            &home,
8663            &running,
8664            &mut last_checked,
8665            too_soon,
8666        )
8667        .await;
8668        assert_eq!(
8669            crate::disk::dir_size(&cache_dir),
8670            10,
8671            "too soon since the last check: left alone rather than rescanned every call"
8672        );
8673        assert_eq!(
8674            last_checked,
8675            Some(t0),
8676            "an idle check does not reset the clock"
8677        );
8678
8679        // Once the interval elapses, the same oversized cache is caught again.
8680        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
8681        maybe_prune_cache_between_runs(
8682            &opts.repo,
8683            &opts,
8684            &home,
8685            &running,
8686            &mut last_checked,
8687            due_again,
8688        )
8689        .await;
8690        assert_eq!(
8691            crate::disk::dir_size(&cache_dir),
8692            0,
8693            "due again: pruned back under the cap"
8694        );
8695    }
8696
8697    /// A stop must not queue behind housekeeping. The prune below is a
8698    /// synchronous walk of the whole cache with no await point in it, so a
8699    /// loop that entered it could not get back to its own `stopped()` test
8700    /// until the walk finished - and because no run is in flight at this
8701    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
8702    /// the stop had already landed. The idle branch has always made this same
8703    /// check before reaching `janitor`; the between-runs path makes it too.
8704    #[tokio::test]
8705    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
8706        let dir = tempfile::tempdir().unwrap();
8707        let home = dir.path().join("home");
8708        let cache_dir = dir.path().join("cache");
8709        std::fs::create_dir_all(&cache_dir).unwrap();
8710        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
8711        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
8712
8713        let stop = Stop::new();
8714        stop.stop();
8715        assert!(
8716            !stop.finishing(),
8717            "no run is in flight at a between-runs boundary, so nothing else \
8718             would tell the operator this stop had not taken effect yet"
8719        );
8720
8721        let mut last_checked = None;
8722        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
8723        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
8724            .await;
8725        assert_eq!(
8726            crate::disk::dir_size(&cache_dir),
8727            10,
8728            "over its cap, and due for the first check ever, but a stop outranks \
8729             it: the cap is a standing policy the next start measures again"
8730        );
8731        assert_eq!(
8732            last_checked, None,
8733            "a check that never happened must not claim the interval"
8734        );
8735    }
8736
8737    /// The regression this whole change exists for: gate timeouts on runs
8738    /// 52da/2f7f/5991/0915 traced back to the shared cache sitting at 81.8
8739    /// GiB against a 10 GiB cap, because the operator's queue never had a
8740    /// quiet moment for `poll`'s fully-idle branch to reach the ordinary
8741    /// `janitor` pass.
8742    ///
8743    /// Reproduced with a backlog whose repository is never created:
8744    /// `Runner::start` fails at `git::toplevel`, spawning no agent CLI.
8745    /// Each task is held after one startup failure, but the remaining tasks
8746    /// keep the queue busy until an external stop ends the loop.
8747    #[tokio::test]
8748    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
8749        let dir = tempfile::tempdir().unwrap();
8750        let cache_dir = dir.path().join("cache");
8751        std::fs::create_dir_all(&cache_dir).unwrap();
8752        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
8753
8754        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
8755        opts.poll = Duration::from_millis(20);
8756        opts.max_attempts = 1_000;
8757
8758        let queue = Queue::at(dir.path().join("queue"));
8759        for i in 0..128 {
8760            let mut task = Task::new(
8761                format!("queued work {i}"),
8762                format!("queued work {i}"),
8763                opts.repo.clone(),
8764                Source::Human,
8765            );
8766            queue.put(&mut task).unwrap();
8767        }
8768
8769        let home = dir.path().join("home");
8770        let worktrees = dir.path().join("wt");
8771        let status_file = home.join("daemon.json");
8772        let stop = Stop::new();
8773        let stopper = {
8774            let stop = stop.clone();
8775            let queue = Queue::at(dir.path().join("queue"));
8776            tokio::spawn(async move {
8777                // Observe completed work rather than rely on a wall-clock
8778                // delay. Every startup failure holds only its own task; the
8779                // backlog keeps offering work at the next boundary.
8780                for _ in 0..2_000 {
8781                    if queue.list().iter().filter(|t| t.attempts == 1).count() >= 2 {
8782                        break;
8783                    }
8784                    tokio::time::sleep(Duration::from_millis(5)).await;
8785                }
8786                stop.stop();
8787            })
8788        };
8789
8790        tokio::time::timeout(
8791            Duration::from_secs(20),
8792            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
8793        )
8794        .await
8795        .expect("the loop must not hang on a queue that keeps producing failing work")
8796        .expect("the loop's own setup and teardown must not fail");
8797        stopper.await.unwrap();
8798
8799        let after = queue.list();
8800        let completed = after.iter().filter(|t| t.attempts == 1).count();
8801        assert!(
8802            completed >= 2,
8803            "the harness must have processed multiple tasks to exercise a busy queue \
8804             (got {completed} completed task(s))"
8805        );
8806        assert!(
8807            after.iter().any(|t| t.status.runnable()),
8808            "unprocessed tasks must remain: the external stop, rather than an \
8809             exhausted backlog, must end the test"
8810        );
8811        assert!(
8812            after
8813                .iter()
8814                .filter(|t| t.attempts > 0)
8815                .all(|t| { t.attempts == 1 && t.status == TaskStatus::Held }),
8816            "a busy backlog must not retry a task's unchanged startup failure"
8817        );
8818
8819        assert_eq!(
8820            crate::disk::dir_size(&cache_dir),
8821            0,
8822            "an oversized cache must not be left to grow unboundedly just because the \
8823             queue kept the loop busy the whole time"
8824        );
8825    }
8826
8827    #[test]
8828    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
8829        let dir = tempfile::tempdir().unwrap();
8830        let queue = Queue::at(dir.path().join("queue"));
8831        let questions = Questions::at(dir.path().join("questions"));
8832        let mut task = task();
8833        queue.put(&mut task).unwrap();
8834
8835        let mut task_question = ask::Question::new(
8836            task.id.clone(),
8837            crate::conduct::NODE.to_owned(),
8838            "conduct".to_owned(),
8839            "Which backend?".to_owned(),
8840            String::new(),
8841            Vec::new(),
8842        );
8843        questions.put(&mut task_question).unwrap();
8844        task.block(vec![task_question.id.clone()], None);
8845        queue.put(&mut task).unwrap();
8846
8847        let mut run_question = ask::Question::new(
8848            "20260101-000000-run1".to_owned(),
8849            "review".to_owned(),
8850            "reviewer-1".to_owned(),
8851            "Run question".to_owned(),
8852            String::new(),
8853            Vec::new(),
8854        );
8855        questions.put(&mut run_question).unwrap();
8856
8857        // A question from another node whose `run` happens to equal this
8858        // task's id — the same field, filled in for an unrelated reason. Only
8859        // `crate::conduct::NODE` questions use `run` as a task id; this one
8860        // must never be touched by this reconciliation, even after release.
8861        let mut coincidental = ask::Question::new(
8862            task.id.clone(),
8863            "review".to_owned(),
8864            "reviewer-1".to_owned(),
8865            "Unrelated review question".to_owned(),
8866            String::new(),
8867            Vec::new(),
8868        );
8869        questions.put(&mut coincidental).unwrap();
8870
8871        reconcile_task_questions(&queue, &questions);
8872        assert!(questions.get(&task_question.id).unwrap().status.open());
8873        assert!(questions.get(&run_question.id).unwrap().status.open());
8874        assert!(questions.get(&coincidental.id).unwrap().status.open());
8875
8876        task.release();
8877        queue.put(&mut task).unwrap();
8878        reconcile_task_questions(&queue, &questions);
8879        assert_eq!(
8880            questions.get(&task_question.id).unwrap().status,
8881            ask::QuestionStatus::Abandoned
8882        );
8883        assert!(
8884            questions.get(&run_question.id).unwrap().status.open(),
8885            "run questions remain the run janitor's responsibility"
8886        );
8887        assert!(
8888            questions.get(&coincidental.id).unwrap().status.open(),
8889            "a non-conductor question must not be abandoned just because its \
8890             run id coincides with a task id"
8891        );
8892    }
8893
8894    #[test]
8895    fn a_freshly_started_running_task_is_never_stalled() {
8896        let dir = tempfile::tempdir().unwrap();
8897        let mut t = task();
8898        t.start("run-1".to_owned());
8899        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
8900        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
8901        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
8902    }
8903
8904    #[test]
8905    fn a_long_running_task_with_no_live_daemon_is_stalled() {
8906        let dir = tempfile::tempdir().unwrap();
8907        let mut t = task();
8908        t.start("run-1".to_owned());
8909        t.updated_at = Timestamp::now()
8910            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
8911        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
8912        assert_eq!(
8913            stalled_tasks(
8914                &Queue::at(dir.path().join("q")),
8915                dir.path(),
8916                Timestamp::now()
8917            )
8918            .len(),
8919            0,
8920            "the task was never written to this queue"
8921        );
8922    }
8923
8924    #[test]
8925    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
8926        let dir = tempfile::tempdir().unwrap();
8927        let mut t = task();
8928        t.id = "20260903-080340-0167".to_owned();
8929        t.start("20260903-080619-01c2".to_owned());
8930        t.updated_at = Timestamp::now()
8931            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
8932
8933        let mut status = Status::new();
8934        status.current = vec![Current {
8935            task: t.id.clone(),
8936            run: "20260903-080619-01c2".to_owned(),
8937        }];
8938        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8939
8940        assert!(
8941            !is_stalled(&t, dir.path(), Timestamp::now()),
8942            "a live daemon's own heartbeat rules out stalled, however long the task has run"
8943        );
8944    }
8945
8946    /// Rewrite a task's `updated_at` on disk directly, bypassing
8947    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
8948    /// a fixture look like it has genuinely been `running` for a while.
8949    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
8950        let path = queue.path_of(id);
8951        let body = std::fs::read_to_string(&path).unwrap();
8952        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
8953        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
8954        v["updated_at"] = serde_json::Value::String(old.to_string());
8955        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
8956    }
8957
8958    #[test]
8959    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
8960        // The realistic `poll()` ordering, not `is_stalled` in isolation:
8961        // `reclaim_orphaned_running` runs first, on every poll, and settles
8962        // any `running` task whose claim it can actually take. For most
8963        // crashes that is immediate - a dead pid is proof enough for
8964        // `sweep_stale_claims` to drop the lock the same tick, and the very
8965        // next claim attempt succeeds. But a lock whose pid cannot be parsed
8966        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
8967        // `sweep_stale_claims`'s own doc), so the lock - and the claim
8968        // failure behind it - can legitimately outlive many polls. This is
8969        // exactly the gap `stalled_tasks` exists to surface well before that
8970        // six-hour sweep would: reclaim leaves the task `running`, and it
8971        // must still reach the conductor as stalled.
8972        let dir = tempfile::tempdir().unwrap();
8973        let queue = Queue::at(dir.path().join("queue"));
8974        let home = dir.path().join("home");
8975
8976        let mut t = task();
8977        t.id = "20260101-000001-lock".to_owned();
8978        t.start("run-1".to_owned());
8979        queue.put(&mut t).unwrap();
8980        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
8981        std::fs::write(
8982            dir.path().join("queue").join(format!("{}.lock", t.id)),
8983            "not a pid",
8984        )
8985        .unwrap();
8986
8987        let now = Timestamp::now();
8988        assert!(
8989            reclaim_orphaned_running(&queue, 2).is_empty(),
8990            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
8991             and reclaim must leave the task alone"
8992        );
8993        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
8994
8995        let stalled = stalled_tasks(&queue, &home, now);
8996        assert_eq!(
8997            stalled.len(),
8998            1,
8999            "reclaim's inability to claim it yet must not hide it from the conductor"
9000        );
9001        assert_eq!(stalled[0].id, t.id);
9002    }
9003
9004    #[test]
9005    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
9006        let dir = tempfile::tempdir().unwrap();
9007        crate::run::set_home(dir.path().join("run-home"));
9008        let queue = Queue::at(dir.path().join("queue"));
9009        let home = dir.path().join("home");
9010        let questions = Questions::at(dir.path().join("questions"));
9011
9012        let mut t = task();
9013        t.id = "20260101-000003-dead".to_owned();
9014        t.start("missing-run".to_owned());
9015        queue.put(&mut t).unwrap();
9016        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
9017
9018        // This is the real poll ordering: retain the deterministic stalled
9019        // input before a claim proves the owner is gone and reclaims it.
9020        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
9021        assert_eq!(
9022            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
9023            [&t.id]
9024        );
9025        assert_eq!(reclaim_orphaned_running(&queue, 2), [t.id.clone()]);
9026        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
9027
9028        // Reclaim drops its guard before conductor decisions are applied, so
9029        // the decision for the captured stalled input has a real write path.
9030        crate::conduct::apply(
9031            &queue,
9032            &questions,
9033            &crate::conduct::Verdict {
9034                decisions: vec![crate::conduct::Decision {
9035                    id: t.id.clone(),
9036                    recovery: Some(crate::conduct::Recovery::Requeue),
9037                    ..crate::conduct::Decision::default()
9038                }],
9039            },
9040        )
9041        .unwrap();
9042        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
9043    }
9044
9045    #[test]
9046    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
9047        let dir = tempfile::tempdir().unwrap();
9048        let queue = Queue::at(dir.path().join("queue"));
9049        let home = dir.path().join("home");
9050
9051        let mut fresh = task();
9052        fresh.id = "20260101-000001-aaaa".to_owned();
9053        fresh.start("run-1".to_owned());
9054        queue.put(&mut fresh).unwrap();
9055
9056        let mut old = task();
9057        old.id = "20260101-000002-bbbb".to_owned();
9058        old.start("run-2".to_owned());
9059        queue.put(&mut old).unwrap();
9060        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
9061
9062        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
9063        assert_eq!(stalled.len(), 1);
9064        assert_eq!(stalled[0].id, old.id);
9065    }
9066
9067    #[test]
9068    fn queued_and_finished_task_views_partition_by_status() {
9069        let dir = tempfile::tempdir().unwrap();
9070        let queue = Queue::at(dir.path().join("queue"));
9071
9072        let mut queued = task();
9073        queued.id = "20260101-000001-aaaa".to_owned();
9074        queue.put(&mut queued).unwrap();
9075
9076        let mut failed = task();
9077        failed.id = "20260101-000002-bbbb".to_owned();
9078        failed.start("run-1".to_owned());
9079        failed.fail("gate red", 5);
9080        queue.put(&mut failed).unwrap();
9081
9082        let mut held = task();
9083        held.id = "20260101-000003-cccc".to_owned();
9084        held.hold_machine(None);
9085        queue.put(&mut held).unwrap();
9086
9087        let mut running = task();
9088        running.id = "20260101-000004-dddd".to_owned();
9089        running.start("run-2".to_owned());
9090        queue.put(&mut running).unwrap();
9091
9092        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
9093        assert_eq!(queued_ids, [queued.id.clone()]);
9094
9095        let mut finished_ids: Vec<String> =
9096            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
9097        finished_ids.sort_unstable();
9098        let mut want = vec![failed.id.clone(), held.id.clone()];
9099        want.sort_unstable();
9100        assert_eq!(finished_ids, want);
9101    }
9102
9103    #[test]
9104    fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
9105        for short in [false, true] {
9106            let dir = tempfile::tempdir().unwrap();
9107            let queue = Queue::at(dir.path().join("queue"));
9108            let questions = ask::Questions::at(dir.path().join("questions"));
9109            let mut running = task();
9110            running.id = "20261013-192213-feb2".into();
9111            running.start("existing-run".into());
9112            queue.put(&mut running).unwrap();
9113            let mut middle = task();
9114            middle.id = "20261013-193611-ca5b".into();
9115            middle.block(
9116                vec![if short {
9117                    "feb2".into()
9118                } else {
9119                    running.id.clone()
9120                }],
9121                None,
9122            );
9123            queue.put(&mut middle).unwrap();
9124            let mut waiting = task();
9125            waiting.id = "20261013-202849-ee37".into();
9126            waiting.block(
9127                vec![if short {
9128                    "ca5b".into()
9129                } else {
9130                    middle.id.clone()
9131                }],
9132                Some("wait for implementation".into()),
9133            );
9134            queue.put(&mut waiting).unwrap();
9135            assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
9136            let inv = crate::blockers::Inventory::load(&queue, &questions);
9137            assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
9138            assert!(inv.stuck().is_empty());
9139            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
9140            assert!(report.quarantined.is_empty());
9141            assert!(report.asked.is_empty());
9142            resolve_blockers(&queue, &questions);
9143            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9144            assert!(questions.list().is_empty());
9145            // Finishing the transitive prerequisite alone does not satisfy
9146            // the task's direct dependency.
9147            running.succeed();
9148            queue.put(&mut running).unwrap();
9149            resolve_blockers(&queue, &questions);
9150            assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
9151            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9152            middle = queue.get(&middle.id).unwrap();
9153            middle.succeed();
9154            queue.put(&mut middle).unwrap();
9155            resolve_blockers(&queue, &questions);
9156            let after = queue.get(&waiting.id).unwrap();
9157            assert_eq!(after.status, TaskStatus::Queued);
9158            assert!(after.blocked_by.is_empty());
9159            assert_eq!(after.instruction, waiting.instruction);
9160        }
9161    }
9162
9163    #[test]
9164    fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
9165        for future_schema in [false, true] {
9166            let name = "20261013-193611-ca5b";
9167            let mut future = task();
9168            future.id = name.into();
9169            future.schema = crate::queue::SCHEMA + 1;
9170            let contents = if future_schema {
9171                serde_json::to_string(&future).unwrap()
9172            } else {
9173                "corrupt".into()
9174            };
9175            let dir = tempfile::tempdir().unwrap();
9176            let queue = Queue::at(dir.path().join("queue"));
9177            let questions = ask::Questions::at(dir.path().join("questions"));
9178            let mut waiting = task();
9179            waiting.id = "20261013-202849-ee37".into();
9180            waiting.block(vec!["ca5b".into()], None);
9181            queue.put(&mut waiting).unwrap();
9182            std::fs::write(queue.path_of(name), contents).unwrap();
9183            assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
9184            assert!(
9185                crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
9186            );
9187            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
9188            assert!(report.asked.is_empty());
9189            resolve_blockers(&queue, &questions);
9190            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9191            assert!(questions.list().is_empty());
9192        }
9193        let dir = tempfile::tempdir().unwrap();
9194        let queue = Queue::at(dir.path().join("queue"));
9195        let questions = ask::Questions::at(dir.path().join("questions"));
9196        let mut waiting = task();
9197        waiting.id = "20261013-202849-ee37".into();
9198        waiting.block(vec!["ca5b".into()], None);
9199        queue.put(&mut waiting).unwrap();
9200        let mut done = task();
9201        done.id = "20261013-193611-ca5b".into();
9202        done.succeed();
9203        queue.put(&mut done).unwrap();
9204        // An unreadable second match must not disappear from uniqueness
9205        // checks just because Queue::list skips it.
9206        std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
9207        assert!(queue.get("ca5b").is_err());
9208        assert_eq!(
9209            crate::queue::dependency(&queue, &questions, "ca5b"),
9210            crate::queue::Dependency::Ambiguous
9211        );
9212        resolve_blockers(&queue, &questions);
9213        let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
9214        assert!(report.asked.is_empty());
9215        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9216        assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
9217    }
9218
9219    #[test]
9220    fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
9221        for held in [false, true] {
9222            for question in [false, true] {
9223                for reference in ["ca5b", "20261013-193611-ca5b"] {
9224                    let dir = tempfile::tempdir().unwrap();
9225                    let queue = Queue::at(dir.path().join("queue"));
9226                    let questions = ask::Questions::at(dir.path().join("questions"));
9227                    let mut prerequisite = task();
9228                    prerequisite.id = "20261013-193611-ca5b".into();
9229                    prerequisite.start("existing-run".into());
9230                    queue.put(&mut prerequisite).unwrap();
9231                    let mut waiting = task();
9232                    waiting.id = "20261013-202849-ee37".into();
9233                    if held {
9234                        waiting.hold_machine(Some("waiting for separate consent".into()));
9235                    }
9236                    queue.put(&mut waiting).unwrap();
9237                    let reason = "Deleting saved data requires separate owner consent";
9238                    crate::conduct::apply(
9239                        &queue,
9240                        &questions,
9241                        &crate::conduct::Verdict {
9242                            decisions: vec![crate::conduct::Decision {
9243                                id: waiting.id.clone(),
9244                                blocked_by: vec![reference.into()],
9245                                question: question.then(|| "May the saved data be deleted?".into()),
9246                                recovery: (!question).then_some(crate::conduct::Recovery::Hold),
9247                                reason: Some(reason.into()),
9248                                ..crate::conduct::Decision::default()
9249                            }],
9250                        },
9251                    )
9252                    .unwrap();
9253                    let before = queue.get(&waiting.id).unwrap();
9254                    if question {
9255                        assert_eq!(before.status, TaskStatus::Blocked);
9256                        let q = questions.get(&before.blocked_by[0]).unwrap();
9257                        assert_eq!(q.summary, "May the saved data be deleted?");
9258                        assert!(q.status.open());
9259                    } else {
9260                        assert_eq!(before.status, TaskStatus::Held);
9261                        let recorded_reason = before.hold_reason.as_deref().unwrap();
9262                        assert!(recorded_reason.starts_with(reason));
9263                        if held {
9264                            assert!(recorded_reason.contains("waiting for separate consent"));
9265                        }
9266                    }
9267                    prerequisite.succeed();
9268                    queue.put(&mut prerequisite).unwrap();
9269                    resolve_blockers(&queue, &questions);
9270                    let after = queue.get(&waiting.id).unwrap();
9271                    assert_eq!(after.status, before.status);
9272                    assert_eq!(after.blocked_by, before.blocked_by);
9273                    assert_eq!(after.hold_reason, before.hold_reason);
9274                    assert_eq!(after.instruction, waiting.instruction);
9275                    if question {
9276                        assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
9277                    }
9278                    assert!(
9279                        queue.next_runnable().is_none(),
9280                        "dependency completion is not consent"
9281                    );
9282                }
9283            }
9284        }
9285    }
9286
9287    #[test]
9288    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
9289        let dir = tempfile::tempdir().unwrap();
9290        let queue = Queue::at(dir.path().join("queue"));
9291        let questions = ask::Questions::at(dir.path().join("questions"));
9292
9293        let mut dep = task();
9294        dep.id = "20260101-000001-dep0".to_owned();
9295        dep.succeed();
9296        queue.put(&mut dep).unwrap();
9297
9298        let mut still_going = task();
9299        still_going.id = "20260101-000002-dep1".to_owned();
9300        queue.put(&mut still_going).unwrap();
9301
9302        let mut blocked = task();
9303        blocked.id = "20260101-000003-main".to_owned();
9304        blocked.block(
9305            vec![dep.id.clone(), still_going.id.clone()],
9306            Some("waits on both".to_owned()),
9307        );
9308        queue.put(&mut blocked).unwrap();
9309
9310        resolve_blockers(&queue, &questions);
9311
9312        let after = queue.get(&blocked.id).unwrap();
9313        assert_eq!(
9314            after.status,
9315            TaskStatus::Blocked,
9316            "one dependency is still outstanding"
9317        );
9318        assert_eq!(after.blocked_by, [still_going.id.clone()]);
9319    }
9320
9321    #[test]
9322    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
9323        let dir = tempfile::tempdir().unwrap();
9324        let queue = Queue::at(dir.path().join("queue"));
9325        let questions = ask::Questions::at(dir.path().join("questions"));
9326
9327        let mut q = crate::ask::Question::new(
9328            "20260101-000001-main".to_owned(),
9329            crate::conduct::NODE.to_owned(),
9330            "conduct".to_owned(),
9331            "Which backend?".to_owned(),
9332            String::new(),
9333            Vec::new(),
9334        );
9335        questions.put(&mut q).unwrap();
9336        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
9337            .unwrap();
9338        questions.put(&mut q).unwrap();
9339
9340        let mut blocked = task();
9341        blocked.id = "20260101-000001-main".to_owned();
9342        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
9343        queue.put(&mut blocked).unwrap();
9344
9345        resolve_blockers(&queue, &questions);
9346
9347        let after = queue.get(&blocked.id).unwrap();
9348        assert_eq!(
9349            after.status,
9350            TaskStatus::Queued,
9351            "the only blocker resolved"
9352        );
9353        assert_eq!(after.answers.len(), 1);
9354        assert_eq!(after.answers[0].question, "Which backend?");
9355        assert_eq!(after.answers[0].answer, "SQLite");
9356
9357        // And the run this task starts next is told about it.
9358        let instruction = instruction_for(&after);
9359        assert!(instruction.contains("Which backend?"));
9360        assert!(instruction.contains("SQLite"));
9361    }
9362
9363    #[test]
9364    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
9365        let dir = tempfile::tempdir().unwrap();
9366        let queue = Queue::at(dir.path().join("queue"));
9367        let questions = ask::Questions::at(dir.path().join("questions"));
9368
9369        let mut q = crate::ask::Question::new(
9370            "20260101-000001-main".to_owned(),
9371            crate::conduct::NODE.to_owned(),
9372            "conduct".to_owned(),
9373            "Is the setup done?".to_owned(),
9374            String::new(),
9375            Vec::new(),
9376        );
9377        q.abandon("no answer within 60s of asking");
9378        questions.put(&mut q).unwrap();
9379
9380        let mut blocked = task();
9381        blocked.id = "20260101-000001-main".to_owned();
9382        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
9383        queue.put(&mut blocked).unwrap();
9384
9385        resolve_blockers(&queue, &questions);
9386
9387        let after = queue.get(&blocked.id).unwrap();
9388        assert_eq!(
9389            after.status,
9390            TaskStatus::Held,
9391            "never left blocked on nothing"
9392        );
9393        assert!(!after.operator_held(), "a machine hold, for triage");
9394        assert!(
9395            after
9396                .hold_reason
9397                .as_deref()
9398                .unwrap_or_default()
9399                .contains("went unanswered")
9400        );
9401    }
9402
9403    #[test]
9404    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
9405        // Reproduces the reported bug (task 3958): a task held out of
9406        // attempts, blocked on a `crate::conduct` follow-up question, must
9407        // come back `held` once that question is answered - never `queued`,
9408        // whatever the answer said - or it silently re-enters the
9409        // competition queue with its attempts already exhausted.
9410        let dir = tempfile::tempdir().unwrap();
9411        let queue = Queue::at(dir.path().join("queue"));
9412        let questions = ask::Questions::at(dir.path().join("questions"));
9413
9414        let mut q = crate::ask::Question::new(
9415            "20260101-000001-main".to_owned(),
9416            crate::conduct::NODE.to_owned(),
9417            "conduct".to_owned(),
9418            "How should this be handled?".to_owned(),
9419            String::new(),
9420            Vec::new(),
9421        );
9422        questions.put(&mut q).unwrap();
9423        q.answer(crate::ask::Answer::Text(
9424            "leave it held, a human will look at it later".to_owned(),
9425        ))
9426        .unwrap();
9427        questions.put(&mut q).unwrap();
9428
9429        let mut held = task();
9430        held.id = "20260101-000001-main".to_owned();
9431        held.hold_machine(Some("out of attempts".to_owned()));
9432        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
9433        queue.put(&mut held).unwrap();
9434
9435        resolve_blockers(&queue, &questions);
9436
9437        let after = queue.get(&held.id).unwrap();
9438        assert_eq!(after.status, TaskStatus::Held);
9439        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
9440        assert_eq!(
9441            after.answers[0].answer,
9442            "leave it held, a human will look at it later"
9443        );
9444    }
9445
9446    #[test]
9447    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
9448        let dir = tempfile::tempdir().unwrap();
9449        let queue = Queue::at(dir.path().join("queue"));
9450        let questions = ask::Questions::at(dir.path().join("questions"));
9451        let mut dep = task();
9452        dep.id = "20260101-000001-gone".to_owned();
9453        queue.put(&mut dep).unwrap();
9454        let mut blocked = task();
9455        blocked.id = "20260101-000003-main".to_owned();
9456        blocked.block(vec![dep.id.clone()], None);
9457        queue.put(&mut blocked).unwrap();
9458
9459        // Claimed, so `remove` cannot rewrite it and the resolver must.
9460        let claim = queue.claim(&blocked.id).unwrap();
9461        queue.remove(&dep.id, false, &questions).unwrap();
9462        drop(claim);
9463        resolve_blockers(&queue, &questions);
9464
9465        let after = queue.get(&blocked.id).unwrap();
9466        assert_eq!(after.status, TaskStatus::Queued);
9467        assert!(after.blocked_by.is_empty());
9468    }
9469
9470    #[test]
9471    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
9472        // Reproduces the reported bug: a task blocked on a task id that was
9473        // removed (`magi task rm`, or deleted by hand) can never see that id
9474        // reach `Done`, so the ordinary per-id loop has nothing to notice and
9475        // would otherwise leave the task `blocked` forever with no way for an
9476        // operator to find out why.
9477        let dir = tempfile::tempdir().unwrap();
9478        let queue = Queue::at(dir.path().join("queue"));
9479        let questions = ask::Questions::at(dir.path().join("questions"));
9480
9481        let mut still_going = task();
9482        still_going.id = "20260101-000002-dep1".to_owned();
9483        queue.put(&mut still_going).unwrap();
9484
9485        let mut blocked = task();
9486        blocked.id = "20260101-000003-main".to_owned();
9487        blocked.block(
9488            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
9489            Some("waits on both".to_owned()),
9490        );
9491        queue.put(&mut blocked).unwrap();
9492
9493        resolve_blockers(&queue, &questions);
9494
9495        let after = queue.get(&blocked.id).unwrap();
9496        assert_eq!(
9497            after.status,
9498            TaskStatus::Held,
9499            "a missing dependency must not leave the task blocked forever"
9500        );
9501        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
9502        assert!(after.blocked_by.is_empty());
9503        let reason = after.hold_reason.as_deref().unwrap_or_default();
9504        assert!(
9505            reason.contains("20260101-000001-gone"),
9506            "the missing id must be named so an operator can tell what happened: {reason}"
9507        );
9508        assert!(
9509            reason.contains(&still_going.id),
9510            "the still-valid dependency must not silently vanish from the record: {reason}"
9511        );
9512    }
9513
9514    #[test]
9515    fn instruction_for_is_unchanged_without_any_answers() {
9516        let t = task();
9517        assert_eq!(instruction_for(&t), t.instruction);
9518    }
9519
9520    #[test]
9521    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
9522        let dir = tempfile::tempdir().unwrap();
9523        let q = Queue::at(dir.path().join("queue"));
9524        let src = dir.path().join("shot.png");
9525        std::fs::write(&src, "x").unwrap();
9526        let mut t = task();
9527        q.attach(&mut t, &[src]).unwrap();
9528        let paths = task_attachments(&q, &t).unwrap();
9529        assert_eq!(paths.len(), 1);
9530        assert!(paths[0].is_absolute() && paths[0].is_file());
9531        std::fs::remove_file(&paths[0]).unwrap();
9532        let err = task_attachments(&q, &t).unwrap_err().to_string();
9533        assert!(err.contains("shot.png"), "{err}");
9534    }
9535
9536    #[tokio::test]
9537    async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
9538        let dir = tempfile::tempdir().unwrap();
9539        let queue_path = dir.path().join("queue");
9540        let queue = Queue::at(queue_path.clone());
9541        let mut t = task();
9542        t.source = Source::Agent {
9543            run: "originating-chat".into(),
9544            node: crate::queue::CHAT_NODE.into(),
9545        };
9546        let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
9547            stage: "config-fetch",
9548            target: "origin/main".into(),
9549        });
9550        record_config_failure(&mut t, &fetch);
9551        t.hold_machine(Some(format!("{fetch:#}")));
9552        let fetch_key = t.chat_notice_due().unwrap();
9553        t.chat_notices.push(fetch_key.clone());
9554        queue.put(&mut t).unwrap();
9555
9556        let queue = Queue::at(queue_path);
9557        let mut t = queue.get(&t.id).unwrap();
9558        let a = dir.path().join("a.toml");
9559        let b = dir.path().join("b.toml");
9560        for (path, text, new_cause) in [
9561            (&a, "[graph", true),
9562            (&a, "[verify", false),
9563            (&a, "[graph]\nimplementers = 'invalid-type'", true),
9564            (&b, "[graph]\nimplementers = 'invalid-type'", true),
9565        ] {
9566            t.release_operator("test", None);
9567            std::fs::write(path, text).unwrap();
9568            let error = Config::discover_fetched(dir.path(), Some(path))
9569                .await
9570                .unwrap_err();
9571            record_config_failure(&mut t, &error);
9572            t.hold_machine(Some(format!("{error:#}")));
9573            let due = t.chat_notice_due();
9574            assert_eq!(due.is_some(), new_cause, "{error:#}");
9575            if let Some(key) = due {
9576                assert_ne!(key, fetch_key);
9577                t.chat_notices.push(key);
9578            }
9579        }
9580        t.succeed();
9581        assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
9582    }
9583
9584    #[test]
9585    fn different_missing_attachments_have_distinct_persisted_notice_causes() {
9586        let dir = tempfile::tempdir().unwrap();
9587        let queue_path = dir.path().join("queue");
9588        let queue = Queue::at(queue_path.clone());
9589        let mut t = task();
9590        t.source = crate::queue::Source::Agent {
9591            run: "originating-chat".into(),
9592            node: crate::queue::CHAT_NODE.into(),
9593        };
9594        let a = dir.path().join("a.png");
9595        let b = dir.path().join("b.png");
9596        std::fs::write(&a, "a").unwrap();
9597        std::fs::write(&b, "b").unwrap();
9598        queue.attach(&mut t, &[a, b]).unwrap();
9599        let paths = task_attachments(&queue, &t).unwrap();
9600        for path in &paths {
9601            std::fs::remove_file(path).unwrap();
9602        }
9603        let missing = task_attachments(&queue, &t).unwrap_err();
9604        t.attempts += 1;
9605        let reason = missing.to_string();
9606        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
9607        let first = t.chat_notice_due().expect("first attachment notice");
9608        t.chat_notices.push(first.clone());
9609        queue.put(&mut t).unwrap();
9610
9611        let queue = Queue::at(queue_path.clone());
9612        let mut t = queue.get(&t.id).unwrap();
9613        assert!(t.chat_notice_due().is_none(), "restart does not replay");
9614        t.release_operator("test", None);
9615        t.attempts += 1;
9616        let missing = task_attachments(&queue, &t).unwrap_err();
9617        t.fail_startup_target(
9618            "startup-attachments",
9619            missing.name,
9620            "same missing attachment with regenerated wording",
9621            1,
9622        );
9623        assert!(t.chat_notice_due().is_none(), "same object stays quiet");
9624
9625        std::fs::write(&paths[0], "restored").unwrap();
9626        t.release_operator("test", None);
9627        t.attempts += 1;
9628        let missing = task_attachments(&queue, &t).unwrap_err();
9629        let reason = missing.to_string();
9630        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
9631        let second = t
9632            .chat_notice_due()
9633            .expect("different attachment must notify");
9634        assert_ne!(first, second);
9635        assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
9636    }
9637
9638    #[test]
9639    fn resumed_instruction_is_unchanged_without_any_answers() {
9640        let t = task();
9641        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
9642    }
9643
9644    #[test]
9645    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
9646        let mut t = task();
9647        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
9648        // The run's own instruction on disk predates the answer: it is the
9649        // plain original text `Runner::start` saved before the operator was
9650        // ever asked anything.
9651        let old = t.instruction.clone();
9652
9653        let refreshed = resumed_instruction(&old, &t);
9654        assert!(refreshed.starts_with(&old), "the original text is kept");
9655        assert!(refreshed.contains("Which backend?"));
9656        assert!(refreshed.contains("SQLite"));
9657    }
9658
9659    #[test]
9660    fn resumed_instruction_keeps_an_original_answers_heading() {
9661        let mut t = task();
9662        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
9663        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
9664
9665        let refreshed = resumed_instruction(&t.instruction, &t);
9666
9667        assert!(
9668            refreshed.starts_with(&t.instruction),
9669            "an answers heading in the original instruction is not the appended block"
9670        );
9671        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
9672        assert!(refreshed.contains("Which backend?"));
9673        assert!(refreshed.contains("SQLite"));
9674
9675        let repeated = resumed_instruction(&refreshed, &t);
9676        assert_eq!(
9677            repeated, refreshed,
9678            "only the final appended block is refreshed"
9679        );
9680    }
9681
9682    #[test]
9683    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
9684        let mut t = task();
9685        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
9686
9687        // A first resume appends the block; a second resume of the same run,
9688        // with no new answer in between, must reproduce exactly the same
9689        // text rather than appending the block a second time.
9690        let once = resumed_instruction(&t.instruction, &t);
9691        let twice = resumed_instruction(&once, &t);
9692        assert_eq!(once, twice);
9693        assert_eq!(once.matches("Which backend?").count(), 1);
9694
9695        // A later answer replaces the block wholesale rather than growing it.
9696        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
9697        let refreshed = resumed_instruction(&once, &t);
9698        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
9699        assert!(refreshed.contains("Which backend?"));
9700        assert!(refreshed.contains("Which cache?"));
9701    }
9702
9703    #[test]
9704    fn prepare_instruction_covers_all_three_starters() {
9705        let mut t = task();
9706        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
9707
9708        // Start: a fresh run gets the task text plus every answer so far —
9709        // exactly `instruction_for`.
9710        assert_eq!(
9711            prepare_instruction(&Starter::Start, None, &t),
9712            Some(instruction_for(&t))
9713        );
9714
9715        // Resume: the run's prior instruction is refreshed with the answer,
9716        // not discarded and not left stale.
9717        let old = t.instruction.clone();
9718        assert_eq!(
9719            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
9720            Some(resumed_instruction(&old, &t))
9721        );
9722
9723        // Review: a review-only pass builds its own instruction from the
9724        // branch's history in `crate::graph`, with no task statement at all -
9725        // this boundary must leave it alone.
9726        assert_eq!(
9727            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
9728            None
9729        );
9730    }
9731
9732    #[test]
9733    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
9734        assert_eq!(
9735            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
9736            Starter::Review("magi/eba2/A".to_owned())
9737        );
9738    }
9739
9740    #[test]
9741    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
9742        assert_eq!(
9743            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
9744            Starter::Start,
9745            "a vanished review branch must not fall back to resuming the old run either"
9746        );
9747    }
9748
9749    #[test]
9750    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
9751        let mut t = task();
9752        t.start("old-run".to_owned());
9753        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
9754        t.release();
9755        let branch = t.review_branch.take();
9756        assert_eq!(
9757            choose_starter(branch.as_deref(), true, Some("old-run")),
9758            Starter::Review("magi/eba2/A".to_owned()),
9759            "a review wins over resuming the old run"
9760        );
9761    }
9762
9763    #[test]
9764    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
9765        assert_eq!(
9766            choose_starter(None, false, Some("some-run")),
9767            Starter::Resume("some-run".to_owned())
9768        );
9769        assert_eq!(choose_starter(None, false, None), Starter::Start);
9770    }
9771
9772    #[test]
9773    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
9774        let mut released = task();
9775        released.start("stalled-run".to_owned());
9776        released.requeue();
9777        let unfinished = (!released.fresh_start)
9778            .then(|| Some("stalled-run".to_owned()))
9779            .flatten();
9780        assert_eq!(
9781            choose_starter(None, false, unfinished.as_deref()),
9782            Starter::Start,
9783            "release keeps run history but must not resume it"
9784        );
9785        assert_eq!(released.runs, ["stalled-run"]);
9786    }
9787
9788    #[test]
9789    fn an_ordinary_release_keeps_a_resumable_run_available() {
9790        let mut released = task();
9791        released.start("stalled-run".to_owned());
9792        released.release();
9793        let unfinished = (!released.fresh_start)
9794            .then(|| Some("stalled-run".to_owned()))
9795            .flatten();
9796        assert_eq!(
9797            choose_starter(None, false, unfinished.as_deref()),
9798            Starter::Resume("stalled-run".to_owned()),
9799            "manual release must preserve the normal resume path"
9800        );
9801    }
9802
9803    #[test]
9804    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
9805        let mut state = run_state(RunStatus::Blocked);
9806        state.config.graph.review_rounds = 3;
9807        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
9808        assert!(exhausted_review_budget(&state));
9809
9810        // One round still unused: resuming can still ask a reviewer something.
9811        state.reviews.pop();
9812        assert!(!exhausted_review_budget(&state));
9813
9814        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
9815        // count: only a `Blocked` run re-enters the review loop on resume.
9816        let mut stalled = run_state(RunStatus::Stalled);
9817        stalled.config.graph.review_rounds = 1;
9818        stalled.reviews = vec![review_round(1)];
9819        assert!(!exhausted_review_budget(&stalled));
9820    }
9821
9822    fn review_round(round: usize) -> crate::run::ReviewRound {
9823        crate::run::ReviewRound {
9824            round,
9825            head: "deadbeef".to_owned(),
9826            verified_head: None,
9827            verified_at: None,
9828            reviews: Vec::new(),
9829            e2e: Vec::new(),
9830            verify_retried: false,
9831            e2e_deferred: false,
9832            e2e_defer_reason: None,
9833            fix: None,
9834            blocking: 0,
9835            answered: 1,
9836            expected: 1,
9837            clean: false,
9838            progressed: true,
9839            vote_split: false,
9840            reconsideration: Vec::new(),
9841            verdict: None,
9842        }
9843    }
9844
9845    #[test]
9846    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
9847        let mut run = RunState::new(
9848            PathBuf::from("/repo"),
9849            "main".to_owned(),
9850            "abc1234def".to_owned(),
9851            "add retries".to_owned(),
9852            Config::default(),
9853        );
9854        run.status = RunStatus::Judging;
9855        run.parked = true;
9856        let mut task = Task::new(
9857            "add retries".to_owned(),
9858            "add retries".to_owned(),
9859            PathBuf::from("/repo"),
9860            crate::queue::Source::Human,
9861        );
9862        task.status = TaskStatus::Failed;
9863        task.runs = vec![run.id.clone()];
9864        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
9865        assert!(with(&task, &run), "parked after judging is the case");
9866        let mut parked_task = task.clone();
9867        parked_task.status = TaskStatus::Parked;
9868        assert!(with(&parked_task, &run), "the Parked status is the case");
9869
9870        let mut not_parked = run.clone();
9871        not_parked.parked = false;
9872        not_parked.status = RunStatus::Stalled;
9873        assert!(!with(&task, &not_parked), "a stall is the conductor's");
9874
9875        let mut fresh = task.clone();
9876        fresh.fresh_start = true;
9877        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
9878
9879        let mut review = task.clone();
9880        review.review_branch = Some("magi/x/A".to_owned());
9881        assert!(!with(&review, &run), "review is ranked before resume");
9882
9883        let mut held = task.clone();
9884        held.status = TaskStatus::Held;
9885        assert!(!with(&held, &run), "a hold stays visible to the conductor");
9886
9887        let mut released = run.clone();
9888        released.released_to = Some("20260901-000000-new1".to_owned());
9889        assert!(!with(&task, &released), "nothing left to resume into");
9890
9891        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
9892            "unreadable"
9893        )));
9894    }
9895
9896    #[test]
9897    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
9898        let mut released = RunState::new(
9899            PathBuf::from("/repo"),
9900            "main".to_owned(),
9901            "abc1234def".to_owned(),
9902            "add retries".to_owned(),
9903            Config::default(),
9904        );
9905        released.status = RunStatus::Blocked;
9906        assert_eq!(
9907            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
9908            Some(released.id.clone())
9909        );
9910        released.released_to = Some("20260901-000000-new1".to_owned());
9911        assert_eq!(
9912            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
9913            None,
9914            "there is nothing left to resume it into"
9915        );
9916    }
9917
9918    #[test]
9919    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
9920        // Mirrors the failure this exists to close: a task's last run ended
9921        // `Blocked` with the review budget spent, `crate::conduct` chose
9922        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
9923        // evidence), and without this check `attempt` would go on treating
9924        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
9925        // review loop iterates zero times over an already-spent budget, so
9926        // the resumed run settles right back to `Blocked` having asked nobody
9927        // anything, and `Requeue`'s promised fresh competition never happens.
9928        let mut exhausted = RunState::new(
9929            PathBuf::from("/repo"),
9930            "main".to_owned(),
9931            "abc1234def".to_owned(),
9932            "add retries".to_owned(),
9933            Config::default(),
9934        );
9935        exhausted.status = RunStatus::Blocked;
9936        exhausted.config.graph.review_rounds = 1;
9937        exhausted.reviews = vec![review_round(1)];
9938
9939        assert_eq!(
9940            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
9941            None,
9942            "an exhausted `Blocked` run must not be offered as resumable"
9943        );
9944
9945        // A `Blocked` run with rounds still unused is genuinely worth
9946        // resuming, and must still be found.
9947        let mut has_budget_left = RunState::new(
9948            PathBuf::from("/repo"),
9949            "main".to_owned(),
9950            "abc1234def".to_owned(),
9951            "add retries".to_owned(),
9952            Config::default(),
9953        );
9954        has_budget_left.status = RunStatus::Blocked;
9955        has_budget_left.config.graph.review_rounds = 3;
9956        has_budget_left.reviews = vec![review_round(1)];
9957
9958        assert_eq!(
9959            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
9960                Ok(has_budget_left.clone())
9961            }),
9962            Some(has_budget_left.id.clone())
9963        );
9964    }
9965
9966    #[test]
9967    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
9968        let mut run = RunState::new(
9969            PathBuf::from("/repo"),
9970            "main".to_owned(),
9971            "abc1234def".to_owned(),
9972            "add retries".to_owned(),
9973            Config::default(),
9974        );
9975        run.status = RunStatus::Blocked;
9976        run.config.graph.review_rounds = 1;
9977        run.reviews = vec![review_round(1)];
9978        run.pr_publication_pending = true;
9979        assert_eq!(
9980            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
9981            Some(run.id.clone()),
9982            "a spent review budget must not turn a failed publication into a re-competition"
9983        );
9984    }
9985
9986    #[test]
9987    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
9988        // A task whose history holds an *older* run that still looks
9989        // resumable (say, a competition `Runner::review` was started
9990        // alongside after that older run went `Stalled`) and a *newest* run
9991        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
9992        // on this task must mean a fresh competition — falling back to the
9993        // stale, superseded `Stalled` run instead would resurrect history
9994        // nothing asked to revisit and silently defeat the requeue.
9995        let mut older_stalled = RunState::new(
9996            PathBuf::from("/repo"),
9997            "main".to_owned(),
9998            "abc1234def".to_owned(),
9999            "add retries".to_owned(),
10000            Config::default(),
10001        );
10002        older_stalled.status = RunStatus::Stalled;
10003
10004        let mut newest_exhausted = RunState::new(
10005            PathBuf::from("/repo"),
10006            "main".to_owned(),
10007            "abc1234def".to_owned(),
10008            "add retries".to_owned(),
10009            Config::default(),
10010        );
10011        newest_exhausted.status = RunStatus::Blocked;
10012        newest_exhausted.config.graph.review_rounds = 1;
10013        newest_exhausted.reviews = vec![review_round(1)];
10014
10015        assert_eq!(
10016            unfinished_run_with(
10017                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
10018                "t",
10019                |_| Ok(newest_exhausted.clone())
10020            ),
10021            None,
10022            "the newest run is exhausted, so nothing here is worth resuming - \
10023             least of all the older, already-superseded run"
10024        );
10025    }
10026
10027    #[test]
10028    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
10029        assert_eq!(
10030            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
10031                Err(anyhow::anyhow!("fixture is absent"))
10032            }),
10033            None
10034        );
10035    }
10036
10037    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
10038        let mut q = ask::Question::new(
10039            run.to_owned(),
10040            "implement".to_owned(),
10041            "impl-A".to_owned(),
10042            "continue?".to_owned(),
10043            String::new(),
10044            vec!["resume で続行する".to_owned(), "other".to_owned()],
10045        );
10046        q.actions.insert("resume で続行する".to_owned(), action);
10047        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
10048            .unwrap();
10049        q
10050    }
10051
10052    fn held_task_with(run: &str) -> Task {
10053        let mut t = task();
10054        t.runs = vec![run.to_owned()];
10055        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
10056        t
10057    }
10058
10059    fn resume_action(run: &str) -> ask::ChoiceAction {
10060        ask::ChoiceAction::Resume { run: run.into() }
10061    }
10062
10063    #[test]
10064    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
10065        for parked in [false, true] {
10066            let mut t = task();
10067            t.start("A".into());
10068            t.start("B".into());
10069            assert_eq!(t.runs, vec!["A", "B"]);
10070            t.start("A".into());
10071            let mut resumed = run_state(RunStatus::Blocked);
10072            resumed.id = "A".into();
10073            resumed.parked = parked;
10074            resumed.driver_exited = true;
10075            t.hold_machine(Some("resumed run stopped".into()));
10076            let q = action_question("A", resume_action("A"));
10077            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
10078            assert_eq!(
10079                decide_action(&t, &q, &PHRASES_EN, |id| {
10080                    assert_eq!(id, "A");
10081                    Ok(resumed.clone())
10082                }),
10083                ActionDecision::Resume("A".into())
10084            );
10085            assert_eq!(
10086                action_standing(&t, &action_question("B", resume_action("B"))),
10087                ActionStanding::Stale
10088            );
10089            t.release_operator("cli", None);
10090            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
10091                assert_eq!(id, "A");
10092                Ok(resumed.clone())
10093            });
10094            assert_eq!(
10095                choose_starter(None, false, unfinished.as_deref()),
10096                Starter::Resume("A".into())
10097            );
10098            assert_eq!(t.runs, vec!["B", "A"]);
10099        }
10100    }
10101
10102    #[test]
10103    fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
10104        let mut state = crate::land::tests::repair_state(true, true);
10105        state.status = RunStatus::Landing;
10106        state.parked = true;
10107        state.driver_exited = true;
10108        let mut q = ask::Question::new(
10109            state.id.clone(),
10110            land::APPROVAL_NODE.into(),
10111            "land".into(),
10112            "Merge?".into(),
10113            String::new(),
10114            vec![land::APPROVE.into(), land::HOLD.into()],
10115        );
10116        q.id = state.id.clone();
10117        state.land_approval = Some(crate::run::LandApproval {
10118            question: q.id.clone(),
10119            head: "current-head".into(),
10120        });
10121        assert!(land::upgrade_repair_choice(&mut q, &state));
10122        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
10123        let mut task = held_task_with(&state.id);
10124        task.status = TaskStatus::Parked;
10125        assert_eq!(
10126            decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
10127            ActionDecision::Resume(state.id.clone())
10128        );
10129        q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
10130        q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
10131        task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
10132        assert_eq!(
10133            decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
10134            ActionDecision::Resume(state.id.clone()),
10135            "a repair answer newer than the manual hold resumes the existing owner"
10136        );
10137        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
10138        for answered_at in [q.answered_at, None] {
10139            let mut older = q.clone();
10140            older.answered_at = answered_at;
10141            let refused = decide_action(&task, &older, &PHRASES_EN, |_| {
10142                panic!("a later manual hold must prevent dispatch")
10143            });
10144            let ActionDecision::Refuse(reason) = refused else {
10145                panic!("expected an actionable refusal, got {refused:?}");
10146            };
10147            assert!(reason.contains("later operator decision"));
10148            assert!(reason.contains(&format!("magi task release {}", task.id)));
10149        }
10150        task.operator_decided_at = None;
10151        let mut superseded = state.clone();
10152        superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
10153        assert_eq!(
10154            decide_action(&task, &q, &PHRASES_EN, |_| Ok(superseded)),
10155            ActionDecision::Stale
10156        );
10157        for case in 1..4 {
10158            let mut changed = state.clone();
10159            match case {
10160                1 => changed.status = RunStatus::Blocked,
10161                2 => changed.released_to = Some("new-owner".into()),
10162                _ => changed.land_approval.as_mut().unwrap().head.clear(),
10163            }
10164            assert!(matches!(
10165                decide_action(&task, &q, &PHRASES_EN, |_| Ok(changed)),
10166                ActionDecision::Refuse(_)
10167            ));
10168        }
10169        assert!(matches!(
10170            decide_action(&task, &q, &PHRASES_EN, |_| anyhow::bail!("missing owner")),
10171            ActionDecision::Refuse(_)
10172        ));
10173        task.runs.push("replacement".into());
10174        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
10175        assert_eq!(
10176            decide_action(&task, &q, &PHRASES_EN, |_| panic!(
10177                "old owner must not load"
10178            )),
10179            ActionDecision::Stale
10180        );
10181    }
10182
10183    #[test]
10184    fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
10185        let mut state = crate::land::tests::repair_state(true, true);
10186        state.status = RunStatus::Landing;
10187        state.parked = true;
10188        state.driver_exited = true;
10189        let mut q = ask::Question::new(
10190            state.id.clone(),
10191            land::APPROVAL_NODE.into(),
10192            "land".into(),
10193            "Merge?".into(),
10194            String::new(),
10195            vec![land::APPROVE.into(), land::HOLD.into()],
10196        );
10197        q.id = state.id.clone();
10198        state.land_approval = Some(crate::run::LandApproval {
10199            question: q.id.clone(),
10200            head: "current-head".into(),
10201        });
10202        state.save().unwrap();
10203        land::upgrade_repair_choice(&mut q, &state);
10204        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
10205        Questions::open().put(&mut q).unwrap();
10206        let tmp = tempfile::tempdir().unwrap();
10207        let queue = Queue::at(tmp.path().join("queue"));
10208        let mut task = held_task_with(&state.id);
10209        task.status = TaskStatus::Parked;
10210        queue.put(&mut task).unwrap();
10211        let empty = Arc::new(tokio::sync::Semaphore::new(0));
10212        let free = Arc::new(tokio::sync::Semaphore::new(1));
10213        assert!(claim_dispatch(&queue, &task, false, &empty, &free).is_none());
10214        assert!(claim_dispatch(&queue, &task, true, &free, &free).is_none());
10215        let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
10216        assert!(claim.permit.is_some());
10217        assert!(claim_dispatch(&queue, &task, false, &free, &free).is_none());
10218        drop(claim);
10219        Questions::open()
10220            .update(&q.id, |q| {
10221                q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
10222                Ok(())
10223            })
10224            .unwrap();
10225        let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
10226        assert!(claim.permit.is_none());
10227        assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
10228    }
10229
10230    #[test]
10231    fn decide_action_resumes_only_the_latest_resumable_run() {
10232        let t = held_task_with("r1");
10233        let q = action_question("r1", resume_action("r1"));
10234        let load = |s: RunState| move |_: &str| Ok(s);
10235        assert_eq!(
10236            decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Blocked))),
10237            ActionDecision::Resume("r1".into())
10238        );
10239        // Not the latest run of the task.
10240        let q_other = action_question("r1", resume_action("r0"));
10241        assert!(matches!(
10242            decide_action(
10243                &t,
10244                &q_other,
10245                &PHRASES_EN,
10246                load(run_state(RunStatus::Blocked))
10247            ),
10248            ActionDecision::Refuse(_)
10249        ));
10250        // A finished run cannot make progress.
10251        assert!(matches!(
10252            decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Ready))),
10253            ActionDecision::Refuse(_)
10254        ));
10255        // A released one either.
10256        let mut released = run_state(RunStatus::Blocked);
10257        released.released_to = Some("elsewhere".into());
10258        assert!(matches!(
10259            decide_action(&t, &q, &PHRASES_EN, load(released)),
10260            ActionDecision::Refuse(_)
10261        ));
10262        // Unreadable state is a refusal, never a fresh competition.
10263        assert!(matches!(
10264            decide_action(&t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
10265            ActionDecision::Refuse(_)
10266        ));
10267    }
10268
10269    #[test]
10270    fn decide_action_ignores_a_question_about_an_earlier_run() {
10271        let mut t = held_task_with("r1");
10272        t.runs.push("r2".to_owned());
10273        let never = |_: &str| -> Result<RunState> { bail!("not read") };
10274        assert_eq!(
10275            decide_action(
10276                &t,
10277                &action_question("r1", ask::ChoiceAction::Done),
10278                &PHRASES_EN,
10279                never
10280            ),
10281            ActionDecision::Stale
10282        );
10283    }
10284
10285    #[test]
10286    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
10287        let mut t = held_task_with("r1");
10288        let never = |_: &str| -> Result<RunState> { bail!("not read") };
10289        assert_eq!(
10290            decide_action(
10291                &t,
10292                &action_question("r1", ask::ChoiceAction::Requeue),
10293                &PHRASES_EN,
10294                never
10295            ),
10296            ActionDecision::Requeue
10297        );
10298        let done_q = action_question("r1", ask::ChoiceAction::Done);
10299        assert_eq!(
10300            decide_action(&t, &done_q, &PHRASES_EN, never),
10301            ActionDecision::Done
10302        );
10303        t.mark_action_applied(&done_q.id);
10304        assert_eq!(
10305            decide_action(&t, &done_q, &PHRASES_EN, never),
10306            ActionDecision::Skip
10307        );
10308
10309        // A plain answer (no action for that label) does nothing.
10310        let mut plain = action_question("r1", ask::ChoiceAction::Done);
10311        plain.actions.clear();
10312        assert_eq!(
10313            decide_action(&held_task_with("r1"), &plain, &PHRASES_EN, never),
10314            ActionDecision::Skip
10315        );
10316        // A running task is left alone.
10317        let mut running = held_task_with("r1");
10318        running.status = TaskStatus::Running;
10319        assert_eq!(
10320            decide_action(
10321                &running,
10322                &action_question("r1", ask::ChoiceAction::Done),
10323                &PHRASES_EN,
10324                never
10325            ),
10326            ActionDecision::Skip
10327        );
10328    }
10329
10330    #[test]
10331    fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
10332        crate::run::pin_test_home();
10333        for legacy in [false, true] {
10334            let dir = tempfile::tempdir().unwrap();
10335            let queue = Queue::at(dir.path().join("queue"));
10336            let questions = Questions::at(dir.path().join("questions"));
10337            let run = "20260101-000000-hold";
10338            let mut task = held_task_with(run);
10339            task.status = TaskStatus::Parked;
10340            let mut q = ask::Question::new(
10341                run.into(),
10342                land::APPROVAL_NODE.into(),
10343                "land".into(),
10344                "Repair?".into(),
10345                String::new(),
10346                vec![land::REPAIR.into()],
10347            );
10348            q.actions.insert(land::REPAIR.into(), resume_action(run));
10349            q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
10350            // Deterministically order the answer before the actual manual hold.
10351            q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
10352            q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
10353            questions.put(&mut q).unwrap();
10354            task.hold_manual(Some("Keep this PR paused".into()));
10355            if legacy {
10356                task.hold_source = None;
10357            }
10358            queue.put(&mut task).unwrap();
10359
10360            apply_choice_actions(&queue, &questions, dir.path());
10361            let after = queue.get(&task.id).unwrap();
10362            assert!(after.operator_held());
10363            assert_eq!(after.hold_source, task.hold_source);
10364            assert_eq!(after.operator_decided_at, task.operator_decided_at);
10365            assert_eq!(after.runs, task.runs);
10366            assert_eq!(after.instruction, task.instruction);
10367            assert!(after.resume_override.is_none());
10368            assert!(after.action_applied(&q.id));
10369            let reason = after.hold_reason.as_deref().unwrap();
10370            assert!(reason.starts_with("Keep this PR paused"));
10371            assert!(reason.contains("later operator decision"));
10372            assert!(reason.contains(&format!("magi task release {}", task.id)));
10373
10374            for recovery in [
10375                crate::conduct::Recovery::Review,
10376                crate::conduct::Recovery::Requeue,
10377            ] {
10378                crate::conduct::apply(
10379                    &queue,
10380                    &questions,
10381                    &crate::conduct::Verdict {
10382                        decisions: vec![crate::conduct::Decision {
10383                            id: task.id.clone(),
10384                            recovery: Some(recovery),
10385                            ..Default::default()
10386                        }],
10387                    },
10388                )
10389                .unwrap();
10390            }
10391            // Reconciliation is idempotent, and automatic recovery cannot
10392            // reopen this owner after it observes the rejected repair answer.
10393            apply_choice_actions(&queue, &questions, dir.path());
10394            let still_held = queue.get(&task.id).unwrap();
10395            assert!(still_held.operator_held());
10396            assert_eq!(still_held.hold_reason, after.hold_reason);
10397            assert_eq!(still_held.runs, task.runs);
10398            assert!(still_held.review_branch.is_none());
10399            assert!(!still_held.fresh_start);
10400            assert!(queue.next_runnable().is_none());
10401        }
10402    }
10403
10404    #[test]
10405    fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
10406        for held in [false, true] {
10407            for retry in [false, true] {
10408                let dir = tempfile::tempdir().unwrap();
10409                let queue = Queue::at(dir.path().join("queue"));
10410                let questions = Questions::at(dir.path().join("questions"));
10411                let home = dir.path().join("home");
10412                let mut t = task();
10413                if held {
10414                    t.hold_machine(Some("driver state unknown".into()));
10415                }
10416                queue.put(&mut t).unwrap();
10417                let verdict = serde_json::from_value(serde_json::json!({
10418                    "decisions": [{
10419                        "id": t.id,
10420                        "question": "Driver state unknown; retry the checks or hold?",
10421                        "choices": ["daemon: recheck and retry", "daemon: hold the task"],
10422                        "actions": {
10423                            "daemon: recheck and retry": {"do": "requeue"},
10424                            "daemon: hold the task": {"do": "hold"}
10425                        }
10426                    }]
10427                }))
10428                .unwrap();
10429                crate::conduct::apply(&queue, &questions, &verdict).unwrap();
10430                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
10431                let mut q = questions.list().pop().unwrap();
10432                let choice = if retry {
10433                    "daemon: recheck and retry"
10434                } else {
10435                    "daemon: hold the task"
10436                };
10437                assert_eq!(q.actions.len(), 2);
10438                q.answer(ask::Answer::Choice(choice.into())).unwrap();
10439                questions.put(&mut q).unwrap();
10440
10441                // A Web answer does not remove the deputy's fresh lease.
10442                questions.beat(&q.id, ask::WaiterKind::Deputy);
10443                for _ in 0..2 {
10444                    resolve_blockers(&queue, &questions);
10445                    apply_choice_actions(&queue, &questions, &home);
10446                    let waiting = queue.get(&t.id).unwrap();
10447                    assert_eq!(waiting.status, TaskStatus::Blocked);
10448                    assert_eq!(waiting.blocked_by, [q.id.clone()]);
10449                    assert!(waiting.answers.is_empty());
10450                    assert!(!waiting.action_applied(&q.id));
10451                    assert!(runnable(&queue).is_empty());
10452                    let free = Arc::new(tokio::sync::Semaphore::new(1));
10453                    assert!(claim_dispatch(&queue, &t, false, &free, &free).is_none());
10454                }
10455                std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
10456
10457                // Releasing the blocker and applying the operation share one save.
10458                resolve_blockers(&queue, &questions);
10459                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
10460                apply_choice_actions(&queue, &questions, &home);
10461                let after = queue.get(&t.id).unwrap();
10462                assert_eq!(
10463                    after.status,
10464                    if retry {
10465                        TaskStatus::Queued
10466                    } else {
10467                        TaskStatus::Held
10468                    }
10469                );
10470                assert!(after.action_applied(&q.id));
10471                assert_eq!(after.operator_held(), !retry);
10472                assert_eq!(after.answers.len(), 1);
10473
10474                // A later operator decision must not replay this answer.
10475                let mut changed = after;
10476                if retry {
10477                    changed.hold_manual(Some("later hold".into()));
10478                } else {
10479                    changed.release_operator("test", None);
10480                }
10481                let expected = changed.status;
10482                queue.put(&mut changed).unwrap();
10483                apply_choice_actions(&queue, &questions, &home);
10484                assert_eq!(queue.get(&t.id).unwrap().status, expected);
10485            }
10486        }
10487    }
10488
10489    #[test]
10490    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
10491        let dir = tempfile::tempdir().unwrap();
10492        let queue = Queue::at(dir.path().join("queue"));
10493        let questions = Questions::at(dir.path().join("questions"));
10494        let home = dir.path().join("home");
10495        let mut state = run_state(RunStatus::Blocked);
10496        state.id = "20260101-000000-act1".to_owned();
10497        state.save_under(&home).unwrap();
10498
10499        let mut t = held_task_with(&state.id);
10500        queue.put(&mut t).unwrap();
10501        let mut q = action_question(&state.id, resume_action(&state.id));
10502        questions.put(&mut q).unwrap();
10503
10504        apply_choice_actions(&queue, &questions, &home);
10505        let after = queue.get(&t.id).unwrap();
10506        assert_eq!(after.status, TaskStatus::Queued);
10507        assert!(!after.fresh_start);
10508        assert!(after.action_applied(&q.id));
10509        let pin = after.resume_override.clone().unwrap();
10510        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
10511        assert!(pin.forced);
10512
10513        // Held again later: the same answer does not release it a second time.
10514        let mut again = queue.get(&t.id).unwrap();
10515        again.hold_machine(Some("later".into()));
10516        queue.put(&mut again).unwrap();
10517        apply_choice_actions(&queue, &questions, &home);
10518        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10519    }
10520
10521    #[test]
10522    fn a_delivered_answer_is_still_acted_on_exactly_once() {
10523        let dir = tempfile::tempdir().unwrap();
10524        let queue = Queue::at(dir.path().join("queue"));
10525        let questions = Questions::at(dir.path().join("questions"));
10526        let home = dir.path().join("home");
10527        let mut state = run_state(RunStatus::Blocked);
10528        state.id = "20260101-000000-act2".to_owned();
10529        state.save_under(&home).unwrap();
10530
10531        let mut t = held_task_with(&state.id);
10532        queue.put(&mut t).unwrap();
10533        let mut q = action_question(&state.id, resume_action(&state.id));
10534        q.answer_delivered = true;
10535        questions.put(&mut q).unwrap();
10536
10537        // Delivered, and the agent then died: the task is still held, so the
10538        // chosen action applies.
10539        apply_choice_actions(&queue, &questions, &home);
10540        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
10541        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
10542
10543        // Held again: the same answer does nothing a second time.
10544        let mut again = queue.get(&t.id).unwrap();
10545        again.hold_machine(Some("later".into()));
10546        queue.put(&mut again).unwrap();
10547        apply_choice_actions(&queue, &questions, &home);
10548        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10549    }
10550
10551    #[test]
10552    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
10553        let dir = tempfile::tempdir().unwrap();
10554        let queue = Queue::at(dir.path().join("queue"));
10555        let questions = Questions::at(dir.path().join("questions"));
10556        let home = dir.path().join("home");
10557        let mut state = run_state(RunStatus::Blocked);
10558        state.id = "20260101-000000-act3".to_owned();
10559        state.save_under(&home).unwrap();
10560        let mut t = held_task_with(&state.id);
10561        queue.put(&mut t).unwrap();
10562        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
10563        questions.put(&mut q).unwrap();
10564
10565        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
10566        apply_choice_actions(&queue, &questions, &home);
10567        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10568
10569        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
10570        apply_choice_actions(&queue, &questions, &home);
10571        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
10572    }
10573
10574    #[test]
10575    fn action_standing_tells_the_reasons_apart() {
10576        let mut t = held_task_with("r1");
10577        let q = action_question("r1", ask::ChoiceAction::Requeue);
10578        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
10579        let mut plain = q.clone();
10580        plain.actions.clear();
10581        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
10582
10583        // Applied wins over everything, even a running task.
10584        t.mark_action_applied(&q.id);
10585        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
10586
10587        // A newer attempt running: the old question is Stale, not Busy.
10588        let mut t = held_task_with("r1");
10589        t.start("r2".to_owned());
10590        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
10591        // The same question about the latest run just waits.
10592        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
10593        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
10594        t.status = TaskStatus::Blocked;
10595        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
10596
10597        // A conductor question is keyed by the task, never stale.
10598        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
10599        c.node = crate::conduct::NODE.to_owned();
10600        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
10601        assert!(!ActionStanding::Busy.daemon_owns());
10602    }
10603
10604    #[test]
10605    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
10606        let dir = tempfile::tempdir().unwrap();
10607        let queue = Queue::at(dir.path().join("queue"));
10608        let questions = Questions::at(dir.path().join("questions"));
10609        let home = dir.path().join("home");
10610        let mut state = run_state(RunStatus::Blocked);
10611        state.id = "20260101-000000-act4".to_owned();
10612        state.save_under(&home).unwrap();
10613        let mut t = held_task_with(&state.id);
10614        t.status = TaskStatus::Running;
10615        queue.put(&mut t).unwrap();
10616        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
10617        q.cwd = Some(dir.path().display().to_string());
10618        questions.put(&mut q).unwrap();
10619
10620        // While the task runs the daemon will not act, so the waiter still
10621        // delivers the word to the dead asker's seat ...
10622        let running = queue.get(&t.id).unwrap();
10623        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
10624        assert!(matches!(
10625            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
10626            crate::waiter::Action::Deliver(_)
10627        ));
10628        // ... and the daemon waits while the task runs, then applies once.
10629        apply_choice_actions(&queue, &questions, &home);
10630        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
10631        let mut back = queue.get(&t.id).unwrap();
10632        back.hold_machine(Some("later".into()));
10633        queue.put(&mut back).unwrap();
10634        apply_choice_actions(&queue, &questions, &home);
10635        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
10636        let mut again = queue.get(&t.id).unwrap();
10637        again.hold_machine(Some("again".into()));
10638        queue.put(&mut again).unwrap();
10639        apply_choice_actions(&queue, &questions, &home);
10640        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10641    }
10642}