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        a if a.maintenance() => ActionDecision::Skip,
921        ask::ChoiceAction::ResumeRun { .. }
922        | ask::ChoiceAction::ReleaseTask { .. }
923        | ask::ChoiceAction::RerunChecks { .. }
924        | ask::ChoiceAction::AbandonRun { .. } => unreachable!(),
925        ask::ChoiceAction::Requeue => ActionDecision::Requeue,
926        ask::ChoiceAction::Hold => ActionDecision::Hold,
927        ask::ChoiceAction::Done => ActionDecision::Done,
928        ask::ChoiceAction::Resume { run } => {
929            if task.runs.last() != Some(run) {
930                return ActionDecision::Refuse((p.resume_not_latest)(
931                    q.short(),
932                    ask::short_id(run),
933                ));
934            }
935            match load(run) {
936                Ok(s) if stopping => {
937                    if s.merge_decision.as_ref().is_some_and(|d| d.closed)
938                        || !s
939                            .land_approval
940                            .as_ref()
941                            .is_some_and(|binding| binding.question == q.id)
942                    {
943                        ActionDecision::Stale
944                    } else if s.liveness(false) == Liveness::Live {
945                        ActionDecision::Skip
946                    } else if s.status == RunStatus::Landing
947                        && !s.released()
948                        && s.retired_to.is_none()
949                    {
950                        ActionDecision::Resume(run.clone())
951                    } else {
952                        ActionDecision::Refuse("Owner stop decision cannot resume its original landing execution; inspect the existing run. No replacement or merge was started.".into())
953                    }
954                }
955                Ok(s)
956                    if q.node == land::APPROVAL_NODE
957                        && q.resolution().as_deref() == Some(land::REPAIR) =>
958                {
959                    if s.merge_repairs.iter().any(|r| r.question == q.id)
960                        || s.land_approval.as_ref().is_some_and(|a| a.question != q.id)
961                    {
962                        // A live/manual driver already consumed or superseded
963                        // this answer. Do not hold its fresh approval wait.
964                        ActionDecision::Stale
965                    } else if s.liveness(false) == Liveness::Live {
966                        ActionDecision::Skip
967                    } else if s.status != RunStatus::Landing
968                        || s.released()
969                        || s.reviews.is_empty()
970                        || !implementers_match(task, &s)
971                        || !s
972                            .land_approval
973                            .as_ref()
974                            .is_some_and(|a| a.question == q.id && !a.head.is_empty())
975                    {
976                        ActionDecision::Refuse(format!(
977                            "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",
978                            q.id, run, run
979                        ))
980                    } else {
981                        ActionDecision::Resume(run.clone())
982                    }
983                }
984                Ok(s) if s.liveness(false) == Liveness::Live => {
985                    ActionDecision::Refuse("run already has a live driver".into())
986                }
987                Ok(s)
988                    if s.status.resumable()
989                        && !s.released()
990                        && s.retired_to.is_none()
991                        && !exhausted_review_budget(&s) =>
992                {
993                    ActionDecision::Resume(run.clone())
994                }
995                Ok(_) => ActionDecision::Refuse((p.resume_cannot_progress)(
996                    q.short(),
997                    ask::short_id(run),
998                )),
999                Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
1000                    q.short(),
1001                    ask::short_id(run),
1002                    &format!("{e:#}"),
1003                )),
1004            }
1005        }
1006    }
1007}
1008
1009/// The fixed prose the daemon writes into [`Task::last_error`] and
1010/// [`Task::hold_reason`], in the language of `[graph] language`. Same shape as
1011/// `triage::Wording` and `land::Words`: only English and Japanese are
1012/// translated, anything else falls back to English.
1013///
1014/// Rendered when the reason is *generated*, so a reason keeps the language it
1015/// was written in if the setting changes later. The notification frame
1016/// (`Task <id> is held:`) is not here and stays English.
1017///
1018/// Deliberately **not** translated, because other code reads them back by
1019/// string: the disk gate prefixes (`triage::is_disk_hold`), `out of attempts`
1020/// and `gate red`. IDs, node names, paths and external error text are embedded
1021/// as they are.
1022struct Phrases {
1023    /// `{}` = status label, then the detail.
1024    graph_stopped: fn(&str, &str) -> String,
1025    quorum_lost: &'static str,
1026    /// Followed by the seats' names.
1027    quota_took_out: &'static str,
1028    /// Followed by the status label.
1029    run_ended: &'static str,
1030    /// Followed by the question's short id.
1031    waiting_for_answer: &'static str,
1032    recovered_running: &'static str,
1033    no_run_to_recover: &'static str,
1034    could_not_start: &'static str,
1035    resume_not_latest: fn(&str, &str) -> String,
1036    resume_cannot_progress: fn(&str, &str) -> String,
1037    resume_unreadable: fn(&str, &str, &str) -> String,
1038    /// A takeover refusal: the operator-facing text. English is the error's own
1039    /// `Display`; a translation keeps the machine detail apart in parentheses.
1040    handover_refused: fn(&crate::handover::Refused) -> String,
1041    /// Appended to a refused handover's hold reason (leading space included).
1042    handover_hint: &'static str,
1043    /// (seats that never answered, review rounds) for the review loop's
1044    /// "refusing to call it clean" stop.
1045    reviewers_never_answered: fn(usize, usize) -> String,
1046}
1047
1048const PHRASES_EN: Phrases = Phrases {
1049    graph_stopped: |status, detail| {
1050        format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
1051    },
1052    quorum_lost: "the judging panel lost its quorum",
1053    quota_took_out: "; quota took out ",
1054    run_ended: "run ended ",
1055    waiting_for_answer: " - waiting for operator answer to question ",
1056    recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
1057    no_run_to_recover: "task was `running` with no live daemon and no readable \
1058                        run to recover; held for a human to check what happened",
1059    could_not_start: "could not start the run: ",
1060    resume_not_latest: |q, run| {
1061        format!("question {q} asked to resume run {run}, which is not this task's latest run")
1062    },
1063    resume_cannot_progress: |q, run| {
1064        format!("question {q} asked to resume run {run}, which cannot make progress")
1065    },
1066    resume_unreadable: |q, run, e| {
1067        format!("question {q} asked to resume run {run}, which could not be read: {e}")
1068    },
1069    handover_refused: |r| r.to_string(),
1070    handover_hint: " (clean up the other worktree, then release the task from the queue)",
1071    reviewers_never_answered: |missing, rounds| {
1072        format!(
1073            "{missing} reviewer seat(s) never answered after {rounds} rounds; \
1074             refusing to call it clean"
1075        )
1076    },
1077};
1078
1079const PHRASES_JA: Phrases = Phrases {
1080    graph_stopped: |status, detail| {
1081        format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
1082    },
1083    quorum_lost: "審査パネルが定足数を失いました",
1084    quota_took_out: "。クォータで脱落: ",
1085    run_ended: "run 終了: ",
1086    waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
1087    recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
1088    no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
1089                        何が起きたか人が確認するため保留にしました",
1090    could_not_start: "run を開始できませんでした: ",
1091    resume_not_latest: |q, run| {
1092        format!(
1093            "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
1094        )
1095    },
1096    resume_cannot_progress: |q, run| {
1097        format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません")
1098    },
1099    resume_unreadable: |q, run, e| {
1100        format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
1101    },
1102    handover_refused: |r| {
1103        use crate::handover::Refused;
1104        match r {
1105            Refused::Foreign { branch, path, why } => format!(
1106                "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
1107                 削除しません。不要なら `git worktree remove` でその worktree を削除して\
1108                 から、やり直してください(詳細: {why})"
1109            ),
1110            Refused::Unsafe { branch, path, why } => format!(
1111                "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
1112                 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
1113                 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
1114            ),
1115            Refused::ReleaseFailed { branch, path, run } => format!(
1116                "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
1117                 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1118                 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1119            ),
1120        }
1121    },
1122    handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1123    reviewers_never_answered: |missing, rounds| {
1124        format!(
1125            "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1126             クリーンとは認めません"
1127        )
1128    },
1129};
1130
1131fn phrases(language: &str) -> &'static Phrases {
1132    if crate::lang::is_japanese(language) {
1133        &PHRASES_JA
1134    } else {
1135        &PHRASES_EN
1136    }
1137}
1138
1139/// The language of the repository a task belongs to, read best-effort for the
1140/// paths that have no run (and so no config of their own) to ask. An unreadable
1141/// config is English, not an error: a hold reason must still get written.
1142fn language_of(task: &Task, fallback: &Path) -> String {
1143    crate::lang::of_repo(&repo_for(task, fallback))
1144}
1145
1146/// The task an answered question speaks for: the one whose runs include the
1147/// question's run, or - for a conductor question, filed under the task's own
1148/// id - the task with that id.
1149pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1150    if q.node == crate::conduct::NODE {
1151        return tasks.iter().find(|t| t.id == q.run);
1152    }
1153    tasks.iter().find(|t| t.runs.contains(&q.run))
1154}
1155
1156/// Legacy conductor prose never becomes a maintenance command by inference.
1157/// Replace unsupported open labels under the question lock before dispatch.
1158fn repair_choice_offers(questions: &Questions) {
1159    for q in questions.list().into_iter().filter(|q| {
1160        q.status.open()
1161            && q.node == crate::conduct::NODE
1162            && q.choices
1163                .iter()
1164                .any(|c| crate::choice_effect::describe(q, c).is_none())
1165    }) {
1166        let _ = questions.update(&q.id, |current| {
1167            if current.status.open() {
1168                crate::choice_effect::executable_conductor(current);
1169                if let Some(deputy) = &mut current.deputy {
1170                    deputy.brief = crate::deputy::brief(
1171                        &current.run,
1172                        &current.detail,
1173                        &current.choices,
1174                        &current.actions,
1175                    );
1176                }
1177            }
1178            Ok(())
1179        });
1180    }
1181}
1182
1183/// Apply answered typed choices. Only the daemon calls this in production;
1184/// deputies settle the question and never execute its actions.
1185pub async fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1186    apply_maintenance_choices(queue, questions, home).await;
1187    apply_task_choice_actions(queue, questions, home);
1188}
1189
1190/// Apply bounded maintenance effects independently of question ownership: a
1191/// release watcher need not have a queue task, and a predecessor is another run.
1192async fn apply_maintenance_choices(queue: &Queue, questions: &Questions, home: &Path) {
1193    for q in questions.list() {
1194        let Some(action) = q.chosen_action().filter(|a| a.maintenance()) else {
1195            continue;
1196        };
1197        // Receipt paths use question IDs, whose format is independent of run
1198        // IDs. Apply the question store's filename safety rule to both eras.
1199        if asker_may_still_read(questions, &q, home) || !ask::valid_asset_name(&q.id) {
1200            continue;
1201        }
1202        let dir = home.join("choice-actions");
1203        if std::fs::create_dir_all(&dir).is_err() {
1204            continue;
1205        }
1206        let Ok(lock) = std::fs::OpenOptions::new()
1207            .create(true)
1208            .truncate(false)
1209            .write(true)
1210            .open(dir.join(format!("{}.lock", q.id)))
1211        else {
1212            continue;
1213        };
1214        if crate::pr_head::try_lock_file(&lock).is_err() {
1215            continue;
1216        }
1217        let fresh = !home
1218            .join("choice-actions")
1219            .join(format!("{}.json", q.id))
1220            .exists();
1221        let result = async {
1222            let receipt = dir.join(format!("{}.json", q.id));
1223            if receipt.exists() {
1224                let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&receipt)?)?;
1225                anyhow::ensure!(
1226                    prior.get("status").and_then(|s| s.as_str()) == Some("applied"),
1227                    "previous maintenance attempt did not confirm completion; inspect its receipt"
1228                );
1229                return Ok::<_, anyhow::Error>(());
1230            }
1231            // Never retry an uncertain external effect. The receipt is written
1232            // before calling gh, exactly like release_watch's rerun record.
1233            let record = |status: &str| -> anyhow::Result<()> {
1234                let tmp = receipt.with_extension("tmp");
1235                std::fs::write(
1236                    &tmp,
1237                    serde_json::to_vec(&serde_json::json!({
1238                        "action": action, "status": status,
1239                    }))?,
1240                )?;
1241                std::fs::rename(tmp, &receipt)?;
1242                Ok(())
1243            };
1244            let applied = async {
1245                match action {
1246                    ask::ChoiceAction::ResumeRun { run } => {
1247                        crate::resume::validate(home, run)?;
1248                        record("started")?;
1249                        if !crate::resume::pin_queued(queue, run, Some(q.asked_at), Some(&q.id))? {
1250                            crate::resume::validate_unqueued(home, run)?;
1251                            crate::resume::start(run.clone());
1252                        }
1253                    }
1254                    ask::ChoiceAction::ReleaseTask {
1255                        task,
1256                        held_at,
1257                        reason,
1258                    } => {
1259                        anyhow::ensure!(
1260                            queue.resolve_id(task)? == *task,
1261                            "task action requires an exact task ID"
1262                        );
1263                        let _claim = queue.claim(task)?;
1264                        let mut task = queue.get(task)?;
1265                        if task.action_applied(&q.id) {
1266                            return Ok(());
1267                        }
1268                        // Filing this conductor question temporarily wraps the
1269                        // original hold in a Blocked state. Restore only that
1270                        // exact blocker on the local copy before checking the
1271                        // hold binding; unrelated waits never authorize release.
1272                        if q.node == crate::conduct::NODE
1273                            && q.run == task.id
1274                            && task.status == TaskStatus::Blocked
1275                            && task.blocked_from == Some(TaskStatus::Held)
1276                            && task.blocked_by.as_slice() == [q.id.as_str()]
1277                        {
1278                            task.unblock(&q.id);
1279                        }
1280                        anyhow::ensure!(
1281                            task.status == TaskStatus::Held
1282                                && task.held_at == Some(*held_at)
1283                                && task.hold_reason.as_deref() == reason.as_deref()
1284                                && task.operator_decided_at.is_none_or(|at| at <= q.asked_at),
1285                            "task no longer has the hold this question names"
1286                        );
1287                        task.release_operator("choice", Some(&q.id));
1288                        task.mark_action_applied(&q.id);
1289                        queue.put(&mut task)?;
1290                    }
1291                    ask::ChoiceAction::AbandonRun { run } => {
1292                        record("started")?;
1293                        crate::driver::abandon_proven_dead(home, run)?;
1294                    }
1295                    ask::ChoiceAction::RerunChecks {
1296                        repo,
1297                        pr,
1298                        head,
1299                        runs,
1300                    } => {
1301                        rerun_checks_once(home, &q.id, repo, pr, head, runs, || record("started"))
1302                            .await?;
1303                    }
1304                    _ => unreachable!(),
1305                }
1306                Ok::<_, anyhow::Error>(())
1307            }
1308            .await;
1309            match applied {
1310                Ok(()) => record("applied"),
1311                Err(e) => {
1312                    record(&format!("refused or failed: {e:#}"))?;
1313                    Err(e)
1314                }
1315            }
1316        }
1317        .await;
1318        // Retire the originating blocker as well as the target operation.
1319        // A foreign resume leaves its issuer held instead of competing beside
1320        // the execution just started. Other successful maintenance lets the
1321        // original task retry its normal, guarded path.
1322        if home
1323            .join("choice-actions")
1324            .join(format!("{}.json", q.id))
1325            .exists()
1326            && let Some(listed) = task_of_question(&queue.list(), &q)
1327            && !listed.action_applied(&q.id)
1328            && let Ok(_claim) = queue.claim(&listed.id)
1329            && let Ok(mut origin) = queue.get(&listed.id)
1330        {
1331            if !origin.operator_held()
1332                && origin.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1333                && !matches!(origin.status, TaskStatus::Running | TaskStatus::Done)
1334            {
1335                if result.is_err() || matches!(action, ask::ChoiceAction::ResumeRun { .. }) {
1336                    origin.hold_machine(Some(format!(
1337                        "Maintenance choice {} settled; inspect its target before releasing this task",
1338                        q.id
1339                    )));
1340                } else {
1341                    origin.unblock(&q.id);
1342                }
1343            }
1344            origin.mark_action_applied(&q.id);
1345            let _ = queue.put(&mut origin);
1346        }
1347        if let Err(e) = result
1348            && fresh
1349        {
1350            notices::raise_in(
1351                home,
1352                Notice::warn(
1353                    &format!("action:{}", q.id),
1354                    format!("Choice action {} was not completed: {e:#}", q.id),
1355                ),
1356            );
1357        }
1358    }
1359}
1360
1361/// Rerun the named failed workflow runs of a pull request, each at most once
1362/// per `request` (a question id, or a chat operation identity). The head,
1363/// lifecycle and failed state are re-read from the forge first; `started` is
1364/// called once those checks pass and before the first external call, and the
1365/// ledger entry is written before every `gh` call, so an uncertain result is
1366/// never repeated automatically.
1367pub(crate) async fn rerun_checks_once(
1368    home: &Path,
1369    request: &str,
1370    repo: &Path,
1371    pr: &str,
1372    head: &str,
1373    runs: &[String],
1374    started: impl FnOnce() -> anyhow::Result<()>,
1375) -> anyhow::Result<()> {
1376    use crate::release_watch::{GhForge, ReleaseForge};
1377    anyhow::ensure!(
1378        !runs.is_empty()
1379            && runs.len() <= 20
1380            && runs
1381                .iter()
1382                .all(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
1383            && !pr.starts_with('-'),
1384        "invalid rerun targets"
1385    );
1386    let snap = GhForge.snapshot(repo, pr).await?;
1387    anyhow::ensure!(
1388        snap.head == head && snap.state == crate::land::PrLifecycle::Open,
1389        "pull request head or lifecycle changed"
1390    );
1391    anyhow::ensure!(
1392        runs.iter().all(|r| snap
1393            .checks
1394            .iter()
1395            .any(|c| c.run.as_ref() == Some(r) && crate::release_watch::is_failed(c.verdict))),
1396        "named workflow is no longer failed on this pull request"
1397    );
1398    started()?;
1399    let dir = home.join("choice-actions");
1400    std::fs::create_dir_all(&dir)?;
1401    let rerun_lock = std::fs::OpenOptions::new()
1402        .create(true)
1403        .truncate(false)
1404        .write(true)
1405        .open(dir.join("reruns.lock"))?;
1406    crate::pr_head::try_lock_file(&rerun_lock)?;
1407    let ledger = dir.join("reruns.json");
1408    let mut recorded: std::collections::BTreeSet<String> = if ledger.exists() {
1409        serde_json::from_slice(&std::fs::read(&ledger)?)?
1410    } else {
1411        Default::default()
1412    };
1413    for run in runs {
1414        let key = serde_json::to_string(&(request, repo, pr, head, run))?;
1415        if !recorded.insert(key) {
1416            continue;
1417        }
1418        let tmp = ledger.with_extension("tmp");
1419        std::fs::write(&tmp, serde_json::to_vec(&recorded)?)?;
1420        std::fs::rename(tmp, &ledger)?;
1421        GhForge.rerun(repo, run).await?;
1422    }
1423    Ok(())
1424}
1425
1426/// Carry out the [`ask::ChoiceAction`] attached to each answered choice, once.
1427///
1428/// Runs on every poll before the conductor looks at the queue. The task is
1429/// re-read under its claim, so a task somebody completed or held by hand in
1430/// the meantime is judged on what it is now. `Resume` releases the task and
1431/// records a pinned [`crate::queue::OperatorResume`], which `crate::conduct`
1432/// honours (no re-hold, no requeue) until the task runs and [`attempt`]'s
1433/// ordinary `unfinished_run` logic resumes that same run.
1434pub(crate) fn apply_task_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1435    let tasks = queue.list();
1436    for q in questions.list() {
1437        // Dismissal is committed by the question writer, never a resume.
1438        if q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1439            continue;
1440        }
1441        if q.chosen_action().is_none_or(|a| a.maintenance()) {
1442            continue;
1443        }
1444        let Some(listed) = task_of_question(&tasks, &q) else {
1445            if q.node == land::APPROVAL_NODE
1446                && q.resolution().as_deref().is_some_and(|choice| {
1447                    choice == land::REPAIR || crate::merge_decision::stops(choice)
1448                })
1449            {
1450                notices::raise_in(
1451                    home,
1452                    Notice::warn(
1453                        &format!("repair-owner:{}", q.id),
1454                        format!(
1455                            "Approval action is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing task.",
1456                            q.run, q.run
1457                        ),
1458                    ),
1459                );
1460            }
1461            continue;
1462        };
1463        if listed.action_applied(&q.id) {
1464            continue;
1465        }
1466        let Ok(_claim) = queue.claim(&listed.id) else {
1467            continue;
1468        };
1469        let Ok(mut task) = queue.get(&listed.id) else {
1470            continue;
1471        };
1472        // Work only on this local copy until the action can be committed.
1473        // In particular, a fresh lease below leaves the persisted task blocked.
1474        if q.node == crate::conduct::NODE && task.status == TaskStatus::Blocked {
1475            let blockers: Vec<_> = task
1476                .blocked_by
1477                .iter()
1478                .filter(|id| {
1479                    crate::queue::dependency(queue, questions, id)
1480                        == crate::queue::Dependency::Question(q.id.clone())
1481                })
1482                .cloned()
1483                .collect();
1484            if !blockers.is_empty() {
1485                for id in blockers {
1486                    task.unblock(&id);
1487                }
1488                let answer = match &q.answer {
1489                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
1490                    None => String::new(),
1491                };
1492                task.record_answer(q.summary.clone(), answer);
1493            }
1494        }
1495        let language = language_of(&task, Path::new("."));
1496        let decision = decide_action(&task, &q, phrases(&language), |id| {
1497            RunState::load_under(id, home)
1498        });
1499        let ran = matches!(
1500            decision,
1501            ActionDecision::Resume(_)
1502                | ActionDecision::Requeue
1503                | ActionDecision::Hold
1504                | ActionDecision::Done
1505        );
1506        if ran && asker_may_still_read(questions, &q, home) {
1507            // The asking process or its seat can still take the word; act
1508            // once it has gone quiet. Bound on the remaining window: the
1509            // check is not atomic with the write below, so an asker that
1510            // takes the word in between (at most one poll, never more than
1511            // `ask::LEASE_TTL`) only prints it - it never touches the task,
1512            // and `Task::actions_applied` under the claim keeps the action to
1513            // one application. The waiter does not deliver an answer that
1514            // carries an action (`waiter::decide_owned`), so it cannot race.
1515            continue;
1516        }
1517        let done = matches!(decision, ActionDecision::Done);
1518        match decision {
1519            ActionDecision::Skip => continue,
1520            ActionDecision::Resume(run) => {
1521                task.release_operator("choice", Some(&q.id));
1522                task.resume_override = Some(crate::queue::OperatorResume {
1523                    question_id: q.id.clone(),
1524                    at: Timestamp::now(),
1525                    conductor_rehold: None,
1526                    forced: true,
1527                    pinned_run: Some(run),
1528                });
1529            }
1530            ActionDecision::Stale => {}
1531            ActionDecision::Requeue => {
1532                task.release_operator("choice-requeue", Some(&q.id));
1533                task.requeue();
1534            }
1535            ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1536            ActionDecision::Done => task.succeed(),
1537            ActionDecision::Refuse(why) => {
1538                if task.operator_held() {
1539                    // A rejected answer does not release the operator's hold
1540                    // or reclassify it as recoverable by the conductor.
1541                    task.hold_reason = Some(match task.hold_reason.take() {
1542                        Some(reason) => format!("{reason}\n\n{why}"),
1543                        None => why,
1544                    });
1545                } else {
1546                    task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1547                    task.hold_machine(Some(why));
1548                }
1549                notices::raise(
1550                    Notice::warn(
1551                        &format!("action:{}", q.id),
1552                        "An answer asked the daemon to resume a run that cannot be resumed; the task stays held.",
1553                    )
1554                    .link(Link::Task {
1555                        id: task.id.clone(),
1556                    }),
1557                );
1558            }
1559        }
1560        task.mark_action_applied(&q.id);
1561        // The applied id travels with the transition, so a failed save loses
1562        // neither and the answer is acted on at the next poll.
1563        record(queue, &mut task);
1564        if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1565            supersede_prior_runs(&task, home);
1566        }
1567        // Delivery is only a note of who has read the answer; the task's own
1568        // mark above is the authority. Best effort.
1569        let _ = questions.update(&q.id, |r| {
1570            r.answer_delivered = true;
1571            Ok(())
1572        });
1573    }
1574}
1575
1576/// Whether something may still read the answer to `q`: a fresh lease, or the
1577/// asking seat still listed as active in its run (its CLI can outlive the
1578/// `magi ask` that was killed).
1579fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1580    let now = Timestamp::now();
1581    if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1582        return true;
1583    }
1584    q.node != crate::conduct::NODE
1585        && RunState::load_under(&q.run, home).is_ok_and(|s| {
1586            s.seats_active()
1587                .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1588        })
1589}
1590
1591/// Retire an unanswered conductor question after its task no longer refers to
1592/// it. Conductor questions use the task id in `Question::run`, so run-based
1593/// cleanup cannot observe a manual release or completion.
1594///
1595/// Restricted to `Question::node == crate::conduct::NODE`: an ordinary run's
1596/// own question also carries a `run`, and a run id that happens to collide
1597/// with some task's id is not this loop's business — only a conductor
1598/// question actually uses the task id that way. One `Questions::list()` scan
1599/// is taken up front and matched against the in-memory task set, rather than
1600/// calling `Questions::open_for` (a full disk scan on its own) once per task.
1601fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1602    let tasks = queue.list();
1603    let by_id: std::collections::BTreeMap<&str, &Task> =
1604        tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1605    let referenced: Vec<&str> = tasks
1606        .iter()
1607        .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1608        .collect();
1609
1610    for mut question in questions.list() {
1611        if !question.status.open() || question.node != crate::conduct::NODE {
1612            continue;
1613        }
1614        // Keep questions a task still names, including when the reference
1615        // moved to a dependent task.
1616        // Preserve even ambiguous references: retiring a possibly referenced
1617        // question is unsafe until the operator disambiguates it.
1618        if referenced
1619            .iter()
1620            .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1621        {
1622            continue;
1623        }
1624        let Some(task) = by_id.get(question.run.as_str()) else {
1625            continue;
1626        };
1627        question.abandon(format!(
1628            "task {} no longer waits for this answer",
1629            task.short()
1630        ));
1631        if let Err(e) = questions.put(&mut question) {
1632            tracing::warn!(
1633                "could not retire question {} for task {}: {e:#}",
1634                question.short(),
1635                task.short()
1636            );
1637        }
1638    }
1639}
1640
1641/// What a finished run tells the queue about the task it came from.
1642///
1643/// A struct rather than a fourth and fifth boolean argument: the two flags
1644/// answer different questions about the same run, and a call site passing
1645/// `(…, true, false)` is one transposition away from refunding attempts
1646/// forever.
1647#[derive(Debug, Clone, Copy)]
1648pub struct Verdict {
1649    /// Where the graph stopped.
1650    pub status: RunStatus,
1651    /// The run opened a pull request.
1652    pub left_pr: bool,
1653    /// At least one seat was lost to a rate limit.
1654    pub quota_hit: bool,
1655    /// The run parked at a node boundary because it was asked to.
1656    pub parked: bool,
1657    /// The run never produced a single candidate a judge could look at.
1658    ///
1659    /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
1660    /// still have another candidate worth judging, in which case the loss was
1661    /// not the reason nothing came of the run. This is `true` only when the
1662    /// implement wave ended with nothing viable at all.
1663    pub no_viable_candidates: bool,
1664}
1665
1666/// Record a finished run against the task it came from.
1667///
1668/// Kept pure and separate from the loop because this mapping *is* the retry
1669/// policy, and a policy that can only be exercised by spawning a graph is a
1670/// policy nobody checks. The table:
1671///
1672/// | run status                           | task becomes        | attempt spent |
1673/// |---------------------------------------|---------------------|---------------|
1674/// | parked at a boundary                  | `Parked` (requeued) | **no**        |
1675/// | `Merged`, `Ready`                      | `Done`               | yes          |
1676/// | `AlreadyInBase`                        | `Done`, with a note  | **no**        |
1677/// | `Stalled`, quota hit                   | `Failed` (requeued) | **no**        |
1678/// | `Failed`, quota hit, no viable cand.   | `Failed` (requeued) | **no**        |
1679/// | `Stalled`, no quota                    | `Failed`, or `Held`  | yes          |
1680/// | `Blocked` with a PR                    | `Held`               | yes          |
1681/// | `Blocked`, `Failed` otherwise          | `Failed`, or `Held`  | yes          |
1682/// | `VerifiedNoop`                          | `Held`               | yes          |
1683/// | anything non-terminal                  | `Failed`, or `Held`  | yes          |
1684///
1685/// The `VerifiedNoop` row is independent of the `Failed`-quota row above it,
1686/// deliberately: every candidate agreeing there is nothing to write is not a
1687/// machine fact about a rate limit, it is an unverified claim about the
1688/// *task* that a human still has to check — see [`RunStatus::VerifiedNoop`]'s
1689/// own doc and [`Task::handed_off`]. `Held` rather than `Done` on purpose: the
1690/// claim could be wrong (a misread instruction, a stale check), and closing
1691/// the task automatically on an implementer's say-so would be the exact
1692/// failure mode task 391f's own audit was raised to avoid. `attempt spent` is
1693/// `yes` here for the same reason it is on the `Blocked`-with-a-PR row just
1694/// above, which settles through the same [`Task::handed_off`]: `Held` is not
1695/// `Failed`-and-requeued, so nothing retries this task on the same unverified
1696/// claim regardless of whether the one already-spent attempt is refunded, and
1697/// [`Task::release`] resets the count to zero anyway the moment a human looks
1698/// at the evidence and lets it run again.
1699///
1700/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
1701/// twice, together. A quorum lost to rate limits is a property of the machine
1702/// and not of the task, so the attempt is refunded and a reset quota picks
1703/// the work up where it stopped — and that is just as true when every
1704/// implement seat lost the same race and `after_implement` bails with nothing
1705/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
1706/// machine fact. The `no_viable_candidates` guard is what keeps that row
1707/// narrow: a `Failed` run that produced a real candidate which then lost for
1708/// some other reason still spends the attempt, exactly like the quorum lost
1709/// to judges that answered with the wrong shape is ordinary flakiness, and
1710/// refunding *that* takes the bound off the retry loop entirely: run e633
1711/// stalled with `quota: []` after two judges wrote unusable JSON, was
1712/// refunded, and the next attempt paid for a fresh hour-long implement wave
1713/// before it could fail the same way. `max_attempts` exists precisely so
1714/// that cannot repeat forever.
1715///
1716/// A non-terminal status means `execute` returned while the graph was still
1717/// mid-flight, which is a bug rather than a verdict; it is treated as a
1718/// failure so that a task cannot loop on it either.
1719///
1720/// `left_pr` splits the `Blocked` row, and it is the difference between a run
1721/// that failed and a run that finished into a gate. See [`Task::handed_off`].
1722pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1723    settle_in(task, verdict, detail, max_attempts, &PHRASES_EN)
1724}
1725
1726/// [`settle`], with the daemon's own fixed prose in `p`'s language.
1727fn settle_in(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize, p: &Phrases) {
1728    // A parked run is the operator's own doing, and its work is intact on
1729    // disk. The task goes back in line with its attempt refunded so the next
1730    // loop resumes the same run - which `one_task` prefers over competing
1731    // again - and so that swapping the binary a few times cannot exhaust a
1732    // budget meant for agents that actually misbehaved.
1733    if verdict.parked {
1734        task.park(detail);
1735        return;
1736    }
1737    match verdict.status {
1738        RunStatus::Merged | RunStatus::Ready
1739            if task.pr_recovery.as_ref().is_some_and(|s| {
1740                s.disposition != Some(crate::pr_recovery::Disposition::Review)
1741            }) =>
1742        {
1743            task.hold_manual(Some("Public delivery is not confirmed. Inspect the selected PR and run, then use recover-pr --disposition land with the intended source and validation configuration.".into()));
1744        }
1745        RunStatus::Merged | RunStatus::Ready => task.succeed(),
1746        RunStatus::AlreadyInBase => task.already_landed(detail),
1747        RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1748        RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1749            task.stall(detail)
1750        }
1751        RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1752        RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1753        RunStatus::Blocked => task.fail(detail, max_attempts),
1754        RunStatus::VerifiedNoop => task.handed_off(detail),
1755        other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1756    }
1757}
1758
1759/// Rewrite this task's now-moot earlier attempts — [`Task::superseded_attempts`]
1760/// — from `Blocked`/`Stalled` to [`RunStatus::Superseded`], once the task
1761/// itself has actually finished *and* its own last attempt is provably why:
1762/// this loads that run and requires `Merged`/`Ready` before touching
1763/// anything earlier in `runs`, since `Task::succeed` can also be called
1764/// directly on a task whose last attempt never landed at all.
1765///
1766/// Called right after whatever call set `task.status` to
1767/// [`TaskStatus::Done`] — this module's own `settle`'s callers below and
1768/// `reclaim`'s, but also every other place a task can be closed by hand
1769/// without the loop ever settling it itself: `magi task done`
1770/// (`main::TaskCmd::Done`) and `POST /api/queue/{id}/done`
1771/// (`web::queue_done`). Closing a task by hand — after confirming a manual
1772/// GitHub merge, say, exactly the workflow this repository's own
1773/// "Landing a run's winner by hand" documents — is just as much "this task's
1774/// story is over" as a daemon-driven `Merged`/`Ready` is, and skipping it
1775/// there would leave every earlier attempt stuck at `Blocked`/`Stalled`
1776/// forever, which is the exact backlog this status exists to clear. `pub`
1777/// for those two out-of-module callers; everything else about this stays
1778/// internal bookkeeping.
1779///
1780/// A run something is still actually driving is left alone: a
1781/// task cannot be `Done` while one of its *own* attempts is still in flight,
1782/// so a live one at this point can only be an unrelated process — a manual
1783/// `--resume` of this old, now-moot run — and rewriting under it would just
1784/// be undone (back to `Blocked`/`Stalled`, or worse) the next time that
1785/// process itself saves. This is the same `daemon_claims` + [`RunState::liveness`]
1786/// pair `run_report`/`run_detail` use for the same question elsewhere:
1787/// `is_working_on` alone only ever proves a *daemon* claim, not a `magi run
1788/// --resume` invoked by hand outside it, which `liveness` also checks via
1789/// the run's own recorded `driver_pid`. Anything not `Blocked` or `Stalled`
1790/// (already terminal in some other way, or itself mid-run) is left untouched
1791/// too.
1792///
1793/// Best-effort, like the rest of this module's bookkeeping: a load or save
1794/// failure here is a `tracing::warn`, not a failed settle, and the next time
1795/// this same task's completion is recorded — or a daemon restart replays
1796/// `reclaim_orphaned_running` — is another chance to catch up. There is no
1797/// separate reconciliation pass; if that gap ever matters in practice, one
1798/// can be added then.
1799///
1800/// `home` is a parameter, not the process-global [`crate::run::home`], for
1801/// the same reason [`RunState::save_under`] takes one: `web::queue_done`
1802/// calls this with `ui.home`, which is `crate::run::home()` in a real
1803/// process but a fixture's own directory under test — falling through to
1804/// the global there would read and write through whichever home some other
1805/// test in the same binary happened to pin into that `OnceLock` first, not
1806/// the run this call actually means.
1807pub fn supersede_prior_runs(task: &Task, home: &Path) {
1808    let now = Timestamp::now();
1809    // `Task::superseded_attempts` cannot tell a loop-driven `Done` (always
1810    // right behind a `Merged`/`Ready` verdict) from one set directly by
1811    // `magi task done`/its web equivalent/the conductor on a task whose last
1812    // recorded attempt never actually landed - that requires reading the
1813    // run itself, which is exactly what this does before trusting anything
1814    // in `runs` is safe to relabel.
1815    let last_run_succeeded = task
1816        .runs
1817        .last()
1818        .and_then(|id| RunState::load_under(id, home).ok())
1819        .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
1820    for id in task.superseded_attempts(last_run_succeeded) {
1821        let mut state = match RunState::load_under(id, home) {
1822            Ok(s) => s,
1823            Err(e) => {
1824                tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
1825                continue;
1826            }
1827        };
1828        if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
1829            continue;
1830        }
1831        let daemon_claims = is_working_on(home, id, now);
1832        if state.liveness(daemon_claims) == Liveness::Live {
1833            continue;
1834        }
1835        state.status = RunStatus::Superseded;
1836        if let Err(e) = state.save_under(home) {
1837            tracing::warn!("could not mark run {id} superseded: {e:#}");
1838        }
1839    }
1840}
1841
1842/// Catch up every `Done` task [`supersede_prior_runs`] could not fully
1843/// finish the moment it was called, because one of its earlier attempts was
1844/// still live then - a `magi run --resume` invoked by hand on an old run,
1845/// most likely.
1846///
1847/// That skip is correct at the time (rewriting under a run something is
1848/// still actively saving would just be undone), but a task only ever
1849/// reaches `Done` once, so without this nothing would ever look at it
1850/// again: if that manual process later ends anywhere other than
1851/// `Merged`/`Ready` - abandoned, or landed as another `Blocked` - the
1852/// skipped attempt would sit at `Blocked`/`Stalled` forever, exactly the
1853/// backlog this status exists to clear. Called on the same idle-only
1854/// cadence as [`janitor`], next to it rather than folded into it: this
1855/// walks `queue` and `janitor` never otherwise needs one.
1856///
1857/// Simply re-running [`supersede_prior_runs`] over every `Done` task with
1858/// more than one attempt, every pass: each call is a handful of local file
1859/// reads bounded by that task's own attempt count, the same order of cost
1860/// [`clean::fold_due`] already pays scanning every run on disk on the same
1861/// cadence, and a task already fully resolved costs one failed liveness
1862/// check turned no-op the moment its lingering attempt is no longer live.
1863fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
1864    for task in queue.list() {
1865        if task.status != TaskStatus::Done || task.runs.len() < 2 {
1866            continue;
1867        }
1868        supersede_prior_runs(&task, home);
1869    }
1870}
1871
1872/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
1873/// task ends up held.
1874///
1875/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
1876/// dead daemon never got back to) share this, so the two cannot drift into
1877/// disagreeing about which held tasks get a diagnostic.
1878fn settle_and_diagnose(
1879    task: &mut Task,
1880    verdict: Verdict,
1881    detail: &str,
1882    max_attempts: usize,
1883    state: &RunState,
1884) {
1885    let p = phrases(&state.config.graph.language);
1886    // Shared by normal completion and crash recovery, under the task claim.
1887    // No new attempt can own the task until the old driver has exited.
1888    if let Some(d) = &state.merge_decision {
1889        use crate::merge_decision as md;
1890        if task.runs.last().is_some_and(|id| id != &state.id) {
1891            return;
1892        }
1893        if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
1894            task.succeed();
1895        } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
1896            if state.liveness(false) != Liveness::Dead {
1897                task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
1898                return;
1899            }
1900            let replacement = md::Replacement {
1901                question: d.question.clone(),
1902                run: state.id.clone(),
1903                pr: d.target.pr.clone(),
1904                agent: agent.to_owned(),
1905                context: format!(
1906                    "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
1907                    d.target.pr,
1908                    state.id,
1909                    serde_json::to_string(&state.reviews).unwrap_or_default()
1910                ),
1911            };
1912            task.requeue();
1913            task.pr_recovery = None;
1914            task.review_of = None;
1915            task.replacement = Some(replacement);
1916        } else {
1917            task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
1918                format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
1919            } 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())) }));
1920        }
1921        task.mark_action_applied(&d.question);
1922        if let Some(pass) = state.passes.last() {
1923            task.record_pass(&state.id, pass.index, task.attempts, None);
1924        }
1925        return;
1926    }
1927    if let Some(replacement) = &task.replacement
1928        && !state.parked
1929        && state.resource_block.is_none()
1930        && (state.viable().is_empty()
1931            || (state.status == RunStatus::Blocked && state.tally.is_none()))
1932    {
1933        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)));
1934        return;
1935    }
1936    let attempts_before = task.attempts;
1937    // A run that stopped because a shared resource stayed busy was never a
1938    // failure of the task or of any agent: nothing was asked. The attempt is
1939    // refunded and the task is held by the machine, under a reason `triage`
1940    // can re-check, so the same run resumes with the same agents once the
1941    // resource is free. A park request still wins (it is the operator's).
1942    if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
1943        task.notice_cause(
1944            &format!("resource:{}:{}", block.kind, block.node),
1945            None,
1946            None,
1947        );
1948        task.last_error = Some(detail.to_owned());
1949        task.diagnostic = None;
1950        task.attempts = task.attempts.saturating_sub(1);
1951        if block.kind == "disk pressure" {
1952            task.hold_machine(Some(format!(
1953                "{}{}",
1954                crate::disk::RUNNING_PRESSURE,
1955                block.detail
1956            )));
1957        } else {
1958            task.hold_machine(Some(format!(
1959                "{}{} stayed busy past the resource-wait limit before `{}` could start; \
1960             no agent was asked and no attempt was spent",
1961                crate::cache::RESOURCE_HOLD,
1962                block.kind,
1963                block.node
1964            )));
1965        }
1966        if let Some(pass) = state.passes.last() {
1967            task.record_pass(&state.id, pass.index, attempts_before, None);
1968        }
1969        return;
1970    }
1971    let unresolved = task.hold_notice_cause.clone();
1972    if !verdict.parked
1973        && task
1974            .pr_recovery
1975            .as_ref()
1976            .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
1977        && matches!(
1978            verdict.status,
1979            RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
1980        )
1981    {
1982        if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
1983            task.succeed();
1984        } else {
1985            task.hold_manual(Some("Selected PR delivery is incomplete: local review or publication is not a confirmed public merge. Inspect the run and PR; use recover-pr --disposition land with --source-head <reviewed-full-SHA> and the required verification configuration. No automatic new attempt will start.".into()));
1986        }
1987    } else if !verdict.parked
1988        && task.pr_recovery.is_some()
1989        && matches!(
1990            verdict.status,
1991            RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
1992        )
1993        && !verdict.quota_hit
1994    {
1995        task.hold_unrequested_retry(Some(format!("Selected recovery stopped: {detail}. Inspect the retained source and run; correct the cause before explicitly releasing or selecting again. No automatic replacement will start.")));
1996    } else {
1997        settle_in(task, verdict, detail, max_attempts, p);
1998    }
1999    if !verdict.parked
2000        && !verdict.quota_hit
2001        && matches!(
2002            verdict.status,
2003            RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
2004        )
2005    {
2006        task.recovery_failed(state);
2007    }
2008    if state.prep_failure.is_some() {
2009        // Minting a run whose candidates could not be prepared is not work
2010        // on a newly approved attempt. Keep the unresolved outcome anchor.
2011        task.hold_notice_cause = unresolved;
2012        task.startup_notice_cause("startup-candidates");
2013    }
2014    // Written here, where the refund (or not) is decided, so the history is a
2015    // fact and not a later guess from the run's status.
2016    if let Some(pass) = state.passes.last() {
2017        let parked = match &pass.end {
2018            Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2019            _ => None,
2020        };
2021        task.record_pass(&state.id, pass.index, attempts_before, parked);
2022    }
2023    if task.status == TaskStatus::Held {
2024        if state.prep_failure.is_none() {
2025            task.notice_cause(
2026                label(verdict.status),
2027                Some(&state.id),
2028                state.passes.last().map(|p| p.index),
2029            );
2030        }
2031        task.diagnostic = diagnostic(state);
2032        note_open_question(task, &state.id, p);
2033    }
2034}
2035
2036/// If `task` is held with a `magi ask` question still open on `run`, name the
2037/// question in [`Task::hold_reason`] rather than leaving the hold reading
2038/// only [`describe`]'s run summary.
2039///
2040/// This is the shape task 20260928-191407-05fd left underspecified: an
2041/// implementer settled a verified no-op and filed a question for the
2042/// operator, and the hold that followed said nothing about the question
2043/// waiting on them. Appended, not substituted - [`crate::triage`] parses the
2044/// existing text ([`is_disk_hold`](crate::triage), the answered-question
2045/// marker) and must keep seeing it unchanged.
2046///
2047/// Best-effort: an unreadable question store must not stop a run from
2048/// settling, so this is a no-op rather than a propagated error when
2049/// [`crate::run::try_home`] has nothing to offer or the store is empty.
2050fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2051    let Some(home) = crate::run::try_home() else {
2052        return;
2053    };
2054    let open = Questions::at(home.join("questions")).open_for(run);
2055    let Some(q) = open.first() else {
2056        return;
2057    };
2058    let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2059    decisions.sort_unstable();
2060    task.notice_cause(
2061        &format!("questions:{}", decisions.join(",")),
2062        Some(run),
2063        None,
2064    );
2065    let base = task.hold_reason.clone().unwrap_or_default();
2066    task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2067}
2068
2069/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
2070/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
2071/// by some other means entirely, like a manual `magi run` resume that
2072/// finishes the graph outside the queue's bookkeeping.
2073///
2074/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
2075/// `settle` is separate from `attempt`: a task recovered this way must land
2076/// exactly where a live daemon would have put it — the same policy table,
2077/// not a second one that quietly drifts from it — and that is only checkable
2078/// without spawning a real run.
2079fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2080    match last_run {
2081        Some(state) => {
2082            let verdict = Verdict {
2083                status: state.status,
2084                left_pr: state.pr.is_some(),
2085                quota_hit: !state.quota.is_empty(),
2086                parked: state.parked,
2087                no_viable_candidates: state.viable().is_empty(),
2088            };
2089            let detail = format!(
2090                "{}{}",
2091                phrases(&state.config.graph.language).recovered_running,
2092                describe(&state)
2093            );
2094            settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2095        }
2096        None => {
2097            // No run, so no config of its own: `language` is the task's
2098            // repository's setting, read by the caller.
2099            let why = phrases(language).no_run_to_recover;
2100            task.last_error = Some(why.to_owned());
2101            // The phone shows `hold_reason`, so a task held by the machine
2102            // says why there too and not only in `last_error`.
2103            task.notice_cause("missing-run", None, None);
2104            task.hold_machine(Some(why.to_owned()));
2105        }
2106    }
2107}
2108
2109/// Find every task left at `running` that no live process is actually
2110/// driving, and settle each one against whatever its last run became.
2111///
2112/// # Why a claim is proof, not a guess
2113///
2114/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
2115/// `running`, and the guard is held for the task's whole time in that status:
2116/// `attempt` does not return, and the loop does not move past the scope
2117/// holding the claim, until the run has settled. So a `running` task whose
2118/// lock is gone cannot have a live owner — this process or any other —
2119/// without needing a staleness threshold or a pid check the way
2120/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
2121/// task that never got as far as `running` at all. Taking the claim here is
2122/// the whole test: it either fails, because something really does hold it
2123/// and the task is left alone, or it succeeds, which is the proof — and it is
2124/// kept for the rest of the decision so nothing else can start a competing
2125/// run while this one is being written.
2126///
2127/// Called on every poll, not only at startup, for the reason
2128/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
2129/// keep noticing this, not only on the one morning it happened to restart.
2130fn reclaim_orphaned_running(queue: &Queue, max_attempts: usize) -> Vec<String> {
2131    let mut reclaimed = Vec::new();
2132    for listed in queue.list() {
2133        if listed.status != TaskStatus::Running {
2134            continue;
2135        }
2136        let Ok(_claim) = queue.claim(&listed.id) else {
2137            continue;
2138        };
2139        // Re-read under the claim: a release or an edit landed by a human
2140        // between the listing above and the claim just taken must not be
2141        // clobbered by a decision based on the stale copy.
2142        let Ok(mut task) = queue.get(&listed.id) else {
2143            continue;
2144        };
2145        if task.status != TaskStatus::Running {
2146            continue;
2147        }
2148        let last_run = task.runs.last().and_then(|id| RunState::load(id).ok());
2149        // `execute` normally abandons a run's own open questions the moment
2150        // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
2151        // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
2152        // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
2153        // with the question still `open`, because the process died before
2154        // reaching that call. `reclaim` itself stays pure on purpose (see its
2155        // own doc), so the same cleanup runs here instead, against the run
2156        // this reclaim is already reading. `settle_run` costs nothing when
2157        // `execute` already got there first.
2158        if let Some(state) = &last_run
2159            && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2160        {
2161            tracing::warn!("abandon questions for {}: {e:#}", state.id);
2162        }
2163        let language = if last_run.is_none() {
2164            language_of(&task, Path::new("."))
2165        } else {
2166            String::new()
2167        };
2168        reclaim(&mut task, last_run, max_attempts, &language);
2169        if task.status == TaskStatus::Done {
2170            supersede_prior_runs(&task, &crate::run::home());
2171        }
2172        record(queue, &mut task);
2173        reclaimed.push(task.id.clone());
2174    }
2175    reclaimed
2176}
2177
2178/// Find every run whose `run.json` is provably dead — every seat it still
2179/// lists as [`crate::run::RunState::active`] has overrun its own timeout, and
2180/// [`crate::run::RunState::liveness`] reads [`crate::run::Liveness::Dead`],
2181/// not merely "no daemon claims it" — and fail it, clearing the leftover
2182/// active seats so the run stops reading as `implementing` (or whichever
2183/// node) forever.
2184///
2185/// [`reclaim_orphaned_running`] settles the *task* a dead daemon left
2186/// `running`, using whatever `run.json` already says — but nothing in that
2187/// path, nor in [`reclaim`], ever writes back to the run itself (`reclaim`
2188/// stays pure on purpose, see its own doc), so a `run.json` a killed process
2189/// never got back to sits exactly where it was left: `active` full of seats
2190/// nobody will ever answer for, `status` stuck on whatever node was in
2191/// flight. `magi show` already tells an operator this in prose (`no live
2192/// daemon claims this run right now`); this is what makes that fact durable
2193/// on disk, the same way a task's own `TaskStatus::Running` does not get to
2194/// stay stuck once nothing is driving it.
2195///
2196/// Runs on every poll, not only at startup, for the reason
2197/// [`sweep_stale_claims`] and [`reclaim_orphaned_running`] already are: a
2198/// daemon up for days must keep noticing a run some other, now-dead, daemon
2199/// left behind just as readily as one it trips over on the way up.
2200///
2201/// Walks `home.join("runs")` directly and reads each `run.json` on its own,
2202/// rather than the process-global [`RunState::load`] / [`crate::run::list_ids`] —
2203/// the same reason [`crate::clean`]'s housekeeping passes take an explicit
2204/// `runs` directory instead: `home` here is a parameter precisely so a test
2205/// can point it away from the operator's real history (see [`drive`]'s own
2206/// doc), and a scan that fell through to the global home anyway would walk
2207/// whichever directory some *other* process or test pinned into that
2208/// `OnceLock` first — mutating runs this call was never handed.
2209fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2210    reclaim_abandoned_runs_with(
2211        home,
2212        now,
2213        crate::proc::pid_status,
2214        crate::proc::process_started_at,
2215    )
2216}
2217
2218/// [`reclaim_abandoned_runs`] with its `driver_pid` liveness/identity queries
2219/// supplied by the caller — mirrors [`sweep_stale_claims_with`], which exists
2220/// for the identical reason: this sweep's real damage (wiping a run's active
2221/// seats and failing it) has to be provable against an injected answer in a
2222/// test, not just the real process table.
2223fn reclaim_abandoned_runs_with<F, G>(
2224    home: &Path,
2225    now: Timestamp,
2226    query: F,
2227    identity: G,
2228) -> Vec<String>
2229where
2230    F: Fn(u32) -> Option<bool>,
2231    G: Fn(u32) -> Option<String>,
2232{
2233    let mut abandoned = Vec::new();
2234    for entry in std::fs::read_dir(home.join("runs"))
2235        .into_iter()
2236        .flatten()
2237        .flatten()
2238    {
2239        let id = entry.file_name().to_string_lossy().into_owned();
2240        if !crate::run::is_run_id(&id) {
2241            continue;
2242        }
2243        // Serialize the proof and save with claims and takeover: a new
2244        // execution must not be overwritten after the liveness observation.
2245        let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2246            continue;
2247        };
2248        // Unreadable is `clean::fold_due`'s problem, not this one's — see
2249        // that module's docs for why a run this cannot parse is left alone
2250        // rather than guessed at. A different schema number is not that: this
2251        // touches only `status` and `active`, never a field whose meaning a
2252        // schema bump changed, so an old record's values serve this exactly
2253        // as well as a current one's (see `clean::read_state`'s own doc for
2254        // the same reasoning applied to folding).
2255        let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2256            continue;
2257        };
2258        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2259            continue;
2260        };
2261        if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2262            continue;
2263        }
2264        // Not `!is_working_on(..)` alone: that is only "no *daemon* claims
2265        // it", which is also the normal, healthy shape of a manual `magi
2266        // run` / `magi review` sharing this same home — this scan walks
2267        // every run on disk, not only ones this daemon itself started. Such
2268        // a run's active seats can legitimately sit past their own timeout
2269        // for a little while (the CLI finishing up, its result still being
2270        // collected) without the process driving it having died. `liveness`
2271        // is what actually tells the two apart, by corroborating
2272        // `driver_pid` against the process it names — see its own doc. Only
2273        // its strongest, provable answer licenses wiping this run's active
2274        // seats and failing it out from under whatever is still running it.
2275        let daemon_claims = is_working_on(home, &id, now);
2276        if state.liveness_under_with(home, daemon_claims, &query, &identity)
2277            != crate::run::Liveness::Dead
2278        {
2279            continue;
2280        }
2281        state.abandon("daemon");
2282        if let Err(e) = state.save_under(home) {
2283            tracing::warn!("could not persist abandoned run {id}: {e:#}");
2284            continue;
2285        }
2286        // This run never passes through `Runner::execute` again, so its end
2287        // is announced here.
2288        if let Some(notice) = notices::run_ended(&state) {
2289            notices::raise_in(home, notice);
2290        }
2291        // The seat that asked is gone for good now, exactly like any other
2292        // door `graph::Runner::settle_questions` closes the moment `status`
2293        // lands somewhere non-resumable - see that method's own doc. Nothing
2294        // else reaches this one before the next `janitor()` startup pass
2295        // (`clean::abandon_settled_questions`), and a daemon that stays up
2296        // for days must not leave an open question badging the operator
2297        // until it happens to restart.
2298        if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2299            tracing::warn!("abandon questions for {id}: {e:#}");
2300        }
2301        abandoned.push(id);
2302    }
2303    abandoned
2304}
2305
2306/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
2307///
2308/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
2309/// sets, so there is one loop body rather than two that drift apart the first
2310/// time the retry policy changes on only one of them.
2311pub async fn serve(opts: Opts) -> Result<()> {
2312    serve_until(opts, Stop::new()).await
2313}
2314
2315/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
2316///
2317/// Neither a signal nor a `stop` abandons a run in flight. Killing the graph
2318/// mid-node leaves worktrees, branches and agent sessions behind, and every
2319/// agent call already paid for is lost; finishing the run costs the operator a
2320/// wait and saves them a cleanup. A stop therefore only sets a flag: the
2321/// current `execute` runs to its terminal status, the task's outcome is
2322/// recorded, and only then does the loop return. That window is what
2323/// [`Stop::finishing`] is for. An operator who genuinely wants the run dead
2324/// still has a second Ctrl-C, which the runtime turns into a process kill —
2325/// and the task left `Running` then tells the next daemon, and the next human,
2326/// where to look.
2327///
2328/// While the queue is empty the stop is honoured within one wakeup rather than
2329/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
2330/// caller that taps stop does not sit through the remainder of a sleep.
2331pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
2332    let signal = {
2333        let stop = stop.clone();
2334        tokio::spawn(async move {
2335            if tokio::signal::ctrl_c().await.is_ok() {
2336                stop.stop();
2337                tracing::info!("shutdown requested; a run in flight will be finished first");
2338            }
2339        })
2340    };
2341
2342    let worktrees_root = opts
2343        .worktrees_root
2344        .clone()
2345        .unwrap_or_else(crate::run::default_worktree_root);
2346    let outcome = drive(
2347        &opts,
2348        &Queue::open(),
2349        &status_path(),
2350        &crate::run::home(),
2351        &worktrees_root,
2352        &stop,
2353    )
2354    .await;
2355
2356    signal.abort();
2357    outcome
2358}
2359
2360/// The loop proper: setup, poll, teardown, with the queue and the status file
2361/// supplied rather than discovered.
2362///
2363/// All three of `home`, `worktrees_root` and the queue/status paths are
2364/// parameters rather than resolved here, for the same reason:
2365/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
2366/// so a unit test that pinned it would fight every other test in the binary,
2367/// and a loop that resolved its own worktree bay could only be exercised
2368/// against the operator's real `~/wt/<repo>` - publishing over a live
2369/// daemon's status file, claiming tasks out of a live backlog, and, since
2370/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
2371/// whatever the operator actually has on disk.
2372async fn drive(
2373    opts: &Opts,
2374    queue: &Queue,
2375    status_file: &Path,
2376    home: &Path,
2377    worktrees_root: &Path,
2378    stop: &Stop,
2379) -> Result<()> {
2380    // The status file is a *snapshot*, not a stream of events: a reader only
2381    // ever wants the latest values, and every tick rewrites the whole file
2382    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
2383    // while an mpsc channel would force the loop to re-send unchanged fields on
2384    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
2385    // for no gain. The lock is only ever held across a field assignment, never
2386    // across an await.
2387    let recovery_cfg = prepare(&opts.repo, opts).ok();
2388    let daemon_cfg = recovery_cfg
2389        .as_ref()
2390        .map(|c| c.daemon.clone())
2391        .unwrap_or_default();
2392    let reconciled = crate::driver::reconcile(home);
2393    if !reconciled.is_empty() {
2394        tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
2395    }
2396    let mut initial_status = Status::new();
2397    initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
2398        recovery_cfg.as_ref(),
2399        daemon_cfg.max_deputies,
2400    ));
2401    let status = Arc::new(Mutex::new(initial_status));
2402    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
2403    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
2404
2405    // Read once at startup, not per task: how many runs this loop drives at
2406    // once is a property of the machine running it, not of whichever
2407    // repository a given task happens to name - see
2408    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
2409    // fact in the same sense the agent roster is.
2410    let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
2411
2412    // Something has to be waiting on every question for as long as it is open,
2413    // whether or not the agent's own `magi ask` survived. Its own task rather
2414    // than a step of the poll loop: the poll loop is busy for the whole of a
2415    // run, and an owner's reply must not queue behind one.
2416    let waiter = tokio::spawn(crate::waiter::run(
2417        crate::waiter::Waiter::new(
2418            crate::ask::Questions::at(home.join("questions")),
2419            home.to_path_buf(),
2420            recovery_cfg.clone(),
2421        ),
2422        stop.clone(),
2423    ));
2424
2425    // The follow-up seats for the conductor's questions: the conductor files a
2426    // question and moves on, and each open one gets a deputy that reads the
2427    // owner's reply. Its own task for the same reason the waiter's is.
2428    let deputies = tokio::spawn(crate::deputy::run(
2429        crate::deputy::Deputies::new(
2430            crate::ask::Questions::at(home.join("questions")),
2431            home.to_path_buf(),
2432            recovery_cfg.clone(),
2433            opts.repo.clone(),
2434            daemon_cfg.max_deputies,
2435            {
2436                let stop = stop.clone();
2437                Arc::new(move || stop.parking())
2438            },
2439        ),
2440        stop.clone(),
2441    ));
2442
2443    // Keeps every checkout's origin/main fresh; its own task so a slow remote
2444    // never holds up the poll loop.
2445    let fetcher = tokio::spawn(fetch_loop(opts.repo.clone(), opts.clone(), stop.clone()));
2446
2447    // Watches the release-bump pull requests until they land; its own task, not
2448    // tied to any run, because a pending bump outlives the run that opened it.
2449    let release_watch = tokio::spawn(crate::release_watch::run(
2450        crate::release_watch::Watcher::new(
2451            Box::new(crate::release_watch::GhForge),
2452            home.to_path_buf(),
2453        ),
2454        {
2455            let (repo, opts) = (opts.repo.clone(), opts.clone());
2456            move || release_watch_settings(&repo, &opts)
2457        },
2458        stop.clone(),
2459    ));
2460
2461    tracing::info!(
2462        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
2463        queue.root().display(),
2464        opts.poll.as_secs(),
2465        opts.max_attempts,
2466        concurrency,
2467        if daemon_cfg.pause_for_interrupts {
2468            ", interrupts enabled"
2469        } else {
2470            ""
2471        }
2472    );
2473
2474    // `--once` drains an already-idle queue without reaching the idle wait,
2475    // but must still perform the startup cleanup.
2476    janitor(&opts.repo, opts, home, worktrees_root).await;
2477    resweep_superseded_attempts(queue, home);
2478
2479    let outcome = poll(
2480        opts,
2481        queue,
2482        &status,
2483        home,
2484        worktrees_root,
2485        stop,
2486        DispatchLimits {
2487            max_concurrent: concurrency,
2488            pause_for_interrupts: daemon_cfg.pause_for_interrupts,
2489        },
2490    )
2491    .await;
2492
2493    beat.abort();
2494    waiter.abort();
2495    deputies.abort();
2496    fetcher.abort();
2497    release_watch.abort();
2498    clear_status_at(status_file);
2499    outcome
2500}
2501
2502/// The checkouts the release watcher covers and `[daemon] release_stall_minutes`,
2503/// re-read each lap. An unreadable config yields `0` minutes: the watcher idles.
2504fn release_watch_settings(repo: &Path, opts: &Opts) -> (Vec<PathBuf>, u64) {
2505    let Ok(cfg) = prepare(repo, opts) else {
2506        return (Vec::new(), 0);
2507    };
2508    let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
2509        .into_iter()
2510        .map(|r| r.path)
2511        .collect();
2512    // Repositories the daemon has worked in, wherever they live: a task may
2513    // name one outside `[repos] roots`, and its release PR must be watched too.
2514    let mut known: Vec<PathBuf> = Queue::open().list().into_iter().map(|t| t.repo).collect();
2515    let runs = crate::run::home().join("runs");
2516    for id in crate::run::list_ids_in(&runs) {
2517        let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
2518            .ok()
2519            .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
2520            .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
2521        known.extend(repo);
2522    }
2523    for k in known {
2524        let k = k.canonicalize().unwrap_or(k);
2525        if k.join(".git").exists() && !paths.contains(&k) {
2526            paths.push(k);
2527        }
2528    }
2529    let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
2530    if !paths.contains(&own) {
2531        paths.push(own);
2532    }
2533    (paths, cfg.daemon.release_stall_minutes)
2534}
2535
2536/// Per-repo bound on one `git fetch`, so a dead remote cannot stall the pass.
2537const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
2538
2539/// Run [`crate::clean::fetch_origins`] every `[repos] fetch_interval` seconds
2540/// until `stop`. The config is re-read each lap; `0` (or an unreadable config)
2541/// disables the fetch for that lap. Never fails.
2542async fn fetch_loop(repo: PathBuf, opts: Opts, stop: Stop) {
2543    while !stop.stopped() {
2544        let (interval, roots) = match prepare(&repo, &opts) {
2545            Ok(c) => (c.repos.fetch_interval, c.repos.roots),
2546            Err(_) => (0, Vec::new()),
2547        };
2548        if interval > 0 && !roots.is_empty() {
2549            let r = crate::clean::fetch_origins(&roots, FETCH_TIMEOUT, || stop.stopped()).await;
2550            tracing::debug!("fetch origins: {r:?}");
2551        }
2552        // Sleep in slices so a stop or a config change is noticed promptly.
2553        let wait = if interval > 0 { interval } else { 60 };
2554        let mut slept = 0;
2555        while slept < wait && !stop.stopped() {
2556            tokio::time::sleep(Duration::from_secs(1)).await;
2557            slept += 1;
2558        }
2559    }
2560}
2561
2562/// Refresh the status file on a fixed tick.
2563///
2564/// Separate from the loop because a run takes tens of minutes: a status file
2565/// written only between tasks would look stale for the whole of every run, and
2566/// a reader would report the daemon dead exactly while it was busiest.
2567async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
2568    loop {
2569        tokio::time::sleep(HEARTBEAT).await;
2570        let snapshot = {
2571            let mut guard = lock(&status);
2572            guard.updated_at = Timestamp::now();
2573            guard.clone()
2574        };
2575        if let Err(e) = write_status_to(&path, &snapshot) {
2576            // A failed heartbeat must not take the daemon down: the loop is the
2577            // product, the status file is only the window onto it.
2578            tracing::warn!("could not refresh the daemon status file: {e:#}");
2579        }
2580    }
2581}
2582
2583/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
2584/// if so, whether that wait is over.
2585#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2586enum LandResume {
2587    /// The task's last run is not parked on a land approval; schedule it
2588    /// like any other candidate.
2589    NotLanding,
2590    /// Parked in `land`, waiting on a question nobody has answered yet.
2591    /// Left alone: attempting it now would only re-observe the same pull
2592    /// request and park again, spending a `gh` call on a decision that has
2593    /// not changed since the last time this was checked.
2594    StillWaiting,
2595    /// Parked in `land`, and the question is settled - answered or
2596    /// abandoned. Resuming this is the one kind of candidate that must not
2597    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
2598    Ready,
2599}
2600
2601/// Classify a runnable candidate by whether it is parked on a land-merge
2602/// approval. Read-only - no claim taken, nothing written - so it is cheap
2603/// enough to call on every candidate, every poll.
2604fn land_resume_state(task: &Task) -> LandResume {
2605    let Some(run_id) = task.runs.last() else {
2606        return LandResume::NotLanding;
2607    };
2608    let Ok(state) = RunState::load(run_id) else {
2609        return LandResume::NotLanding;
2610    };
2611    if !state.parked {
2612        return LandResume::NotLanding;
2613    }
2614    if state.status == RunStatus::Landing
2615        && state.land_approval.as_ref().is_some_and(|binding| {
2616            ask::Questions::open()
2617                .get(&binding.question)
2618                .is_ok_and(|q| {
2619                    q.run == state.id
2620                        && q.resolution()
2621                            .as_deref()
2622                            .is_some_and(crate::merge_decision::stops)
2623                })
2624        })
2625    {
2626        return LandResume::Ready;
2627    }
2628    if !implementers_match(task, &state) {
2629        return LandResume::NotLanding;
2630    }
2631    // Parked in `land` on the merge approval, or at `merge` on the owner's
2632    // word about a title/body the posting gate withheld. Told apart by the
2633    // run's own record, not by a status both can share.
2634    let node = if state.status == RunStatus::Landing {
2635        land::APPROVAL_NODE
2636    } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
2637        crate::github_text::ASK_NODE
2638    } else {
2639        return LandResume::NotLanding;
2640    };
2641    let store = ask::Questions::open();
2642    let waiting = store
2643        .list()
2644        .into_iter()
2645        .filter(|q| &q.run == run_id && q.node == node)
2646        .max_by(|a, b| a.id.cmp(&b.id));
2647    let Some(mut q) = waiting else {
2648        return LandResume::Ready;
2649    };
2650    if !q.status.open() {
2651        // Repair spends agent resources and must obey concurrency and quota
2652        // waits; only a merge/hold decision may use the decision-only lane.
2653        if q.resolution().as_deref() == Some(land::REPAIR) {
2654            return if state.liveness(false) == Liveness::Live {
2655                LandResume::StillWaiting
2656            } else {
2657                LandResume::NotLanding
2658            };
2659        }
2660        return LandResume::Ready;
2661    }
2662    // `ask::ask_and_wait`'s own deadline is what used to retire a question
2663    // nobody ever answered; land's approval bypasses that wait entirely (see
2664    // `land::approval_gate`), so the same deadline has to be enforced here
2665    // instead, or `graph.answer_timeout` silently stops meaning anything for
2666    // a land approval and a run can sit `StillWaiting` forever with nobody
2667    // told to look at it.
2668    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
2669    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
2670    if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
2671        q.abandon(format!(
2672            "no answer within {}s of asking",
2673            timeout.as_secs().max(1)
2674        ));
2675        // If this can't be persisted, do not treat the wait as settled on a
2676        // guess: fall through and try again next poll.
2677        if store.put(&mut q).is_ok() {
2678            return LandResume::Ready;
2679        }
2680    }
2681    LandResume::StillWaiting
2682}
2683
2684/// How often the loop rechecks for new work while something it already
2685/// started is still running, rather than sleeping out the whole
2686/// [`Opts::poll`] interval.
2687///
2688/// Short on purpose: this is what lets a land-merge approval that comes back
2689/// while another task is mid-competition be noticed and resumed within a
2690/// fraction of a second, not within the next multi-second poll.
2691const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
2692
2693/// How often [`poll`] rechecks the shared build cache against its cap at a
2694/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
2695/// waiting for the queue to run dry.
2696///
2697/// A queue that never empties means the `janitor` call at the bottom of this
2698/// loop's fully-idle branch can go unreached for as long as the backlog
2699/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
2700/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
2701/// 81.8 GiB an idle-only check let it reach before this existed, and it is
2702/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
2703/// backlog of short tasks does not pay for that walk on every poll.
2704const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
2705
2706/// Frees one attempt's concurrency slot - `Stop`'s busy count and its entry
2707/// in `Status::current` - on drop, so both are released even if the attempt
2708/// panics rather than returning.
2709///
2710/// A `Drop` impl rather than statements written after the `.await` it
2711/// guards: a panic unwinds straight past code placed "after" a call, and
2712/// `Runner::execute`'s chain reaches deep enough into agent-output parsing
2713/// that ruling a panic out there is not a bet this loop can make. Without
2714/// this, one panicking run would leave [`Stop::busy_now`] stuck `true`
2715/// forever - the idle branch in [`poll`], and with it the janitor, would
2716/// never run again - and a ghost entry in `Status::current` naming a task
2717/// nothing is still working on.
2718struct InFlightGuard<'a> {
2719    status: &'a Arc<Mutex<Status>>,
2720    stop: &'a Stop,
2721    task_id: &'a str,
2722}
2723
2724impl Drop for InFlightGuard<'_> {
2725    fn drop(&mut self) {
2726        lock(self.status).current.retain(|c| c.task != self.task_id);
2727        self.stop.exit();
2728    }
2729}
2730
2731/// State of [`poll`]'s own interrupt-scheduling sequence - see
2732/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
2733/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
2734/// both kept free of `Task`'s non-identity fields on purpose: every decision
2735/// here turns only on task ids and which ones are in flight, so the "never
2736/// more than one run at once" and "exactly one resume" invariants can be
2737/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
2738/// queue - which is exactly the coverage this feature's first two attempts
2739/// were missing.
2740///
2741/// Deliberately in-memory only, not written to disk anywhere: a daemon
2742/// restart mid-sequence loses track of which run it had asked to park and
2743/// which task was meant to run first, and simply falls back to `Idle` -
2744/// see [`drive`]'s own setup. The parked run itself is not lost - it is
2745/// sitting in the queue exactly like any other resumable, interrupted task,
2746/// `RunStatus::resumable` and [`Task::interrupt`] both intact on disk - it
2747/// just resumes on the ordinary priority order rather than guaranteed to go
2748/// first. Giving that guarantee a crash-proof memory would mean a new queue
2749/// field and a recovery ordering to go with it, which is exactly the
2750/// complexity this feature's constraints rule out for the one property that
2751/// actually matters: at most one run, ever, at once.
2752#[derive(Debug, Clone, PartialEq, Eq)]
2753enum Interrupt {
2754    /// No interrupt sequence in progress. Ordinary dispatch applies.
2755    Idle,
2756    /// `interrupt_task` is runnable and exactly one other run is in flight;
2757    /// `parked` names that one task's id. Dispatch is withheld from
2758    /// everyone, including `interrupt_task` itself, until it has left
2759    /// flight - only then is `interrupt_task` let through.
2760    ///
2761    /// `parked` is a `Vec` rather than a bare id for symmetry with
2762    /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
2763    /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
2764    /// when exactly one run is in flight, so it is guaranteed to hold
2765    /// exactly one entry in practice - see that branch's own doc for why
2766    /// more than one is deliberately never attempted.
2767    Parking {
2768        parked: Vec<String>,
2769        interrupt_task: String,
2770    },
2771    /// `interrupt_task` is dispatched and in flight alone. Dispatch is
2772    /// withheld from everyone until it leaves flight - merged, failed, held,
2773    /// it makes no difference - at which point the sequence moves to
2774    /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
2775    /// going straight to `Idle` would hand `parked` back to ordinary
2776    /// priority-order dispatch, where a higher-priority task filed in the
2777    /// meantime could start ahead of it.
2778    Running {
2779        parked: Vec<String>,
2780        interrupt_task: String,
2781    },
2782    /// `interrupt_task` left flight; `parked` still names the one run this
2783    /// sequence owes a resume. Dispatch is withheld from everyone except
2784    /// that task - see [`interrupt_gate`] - so the resume this feature
2785    /// promises is never raced by, or run alongside, an unrelated candidate.
2786    /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
2787    /// own doc on abandonment - the moment it is no longer runnable at all.
2788    Resuming { parked: Vec<String> },
2789}
2790
2791/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
2792/// and `runnable` are read-only snapshots of this tick's reality, and the
2793/// only side effect the caller still owes the world is asking whichever
2794/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
2795/// site.
2796///
2797/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
2798/// accepted rather than a narrower type because that is what [`poll`] already
2799/// has on hand from [`runnable`], and building a second, smaller list on
2800/// every tick just to satisfy this signature would cost more than it proves.
2801///
2802/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
2803/// back to a task they are waiting on no longer being [`runnable`] - held,
2804/// blocked, deleted, or finished by some other means entirely, all of which
2805/// an operator can do to a task sitting in the queue with no claim on it at
2806/// all, at any moment, interrupt sequence or not. Without this check the
2807/// sequence would wait forever for a dispatch that can never come, and
2808/// `interrupt_gate` would withhold every other task in the queue right along
2809/// with it - a single `magi task hold` on the wrong id turning into a
2810/// daemon that never dispatches anything again.
2811fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
2812    match state {
2813        Interrupt::Idle => {
2814            // Not just "something to interrupt": exactly one thing. More
2815            // than one run in flight only happens above the default
2816            // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
2817            // one resume, never run alongside anything else" only because
2818            // it is only ever seeded with exactly one id - see
2819            // `Interrupt::Resuming`'s own doc on why releasing more than one
2820            // parked id back to ordinary dispatch cannot be made safe
2821            // against that same setting's own extra concurrency slots.
2822            // Waiting here for the herd to settle to one is the
2823            // simplification this feature's own constraints ask for rather
2824            // than a second concurrency model to reconcile with the first.
2825            if in_flight.len() != 1 {
2826                return Interrupt::Idle;
2827            }
2828            match runnable.iter().find(|t| t.interrupt) {
2829                Some(t) => Interrupt::Parking {
2830                    parked: in_flight.to_vec(),
2831                    interrupt_task: t.id.clone(),
2832                },
2833                None => Interrupt::Idle,
2834            }
2835        }
2836        Interrupt::Parking {
2837            parked,
2838            interrupt_task,
2839        } => {
2840            if in_flight.iter().any(|id| parked.contains(id)) {
2841                // Still waiting for what was in flight to actually stop.
2842                Interrupt::Parking {
2843                    parked,
2844                    interrupt_task,
2845                }
2846            } else if in_flight.contains(&interrupt_task) {
2847                Interrupt::Running {
2848                    parked,
2849                    interrupt_task,
2850                }
2851            } else if runnable.iter().any(|t| t.id == interrupt_task) {
2852                // The parked run(s) are gone, but the interrupt task has not
2853                // been dispatched yet on this tick - `interrupt_gate` is
2854                // what lets it through next.
2855                Interrupt::Parking {
2856                    parked,
2857                    interrupt_task,
2858                }
2859            } else {
2860                // The interrupt task itself is no longer runnable - see this
2861                // function's own doc on abandonment. The parked run(s) still
2862                // get their guaranteed resume; there is simply no interrupt
2863                // to run ahead of them any longer.
2864                Interrupt::Resuming { parked }
2865            }
2866        }
2867        Interrupt::Running {
2868            parked,
2869            interrupt_task,
2870        } => {
2871            if in_flight.contains(&interrupt_task) {
2872                Interrupt::Running {
2873                    parked,
2874                    interrupt_task,
2875                }
2876            } else {
2877                // The interrupt task's own run reached a terminal status,
2878                // whichever one - this is the *only* trigger that moves the
2879                // sequence on, driven straight off the same in-flight
2880                // bookkeeping `poll` already reaps every tick, not a second,
2881                // independent poll of anything.
2882                Interrupt::Resuming { parked }
2883            }
2884        }
2885        Interrupt::Resuming { parked } => {
2886            if in_flight.iter().any(|id| parked.contains(id)) {
2887                // One of the parked runs has been dispatched - the resume
2888                // this sequence owed is fulfilled. Whatever else is left in
2889                // `parked` (ordinarily nothing, at the default concurrency
2890                // of one) rejoins ordinary priority-order dispatch, same as
2891                // any other runnable task.
2892                Interrupt::Idle
2893            } else if runnable.iter().any(|t| parked.contains(&t.id)) {
2894                Interrupt::Resuming { parked }
2895            } else {
2896                // Abandonment (see this function's own doc): nothing left in
2897                // `parked` is even runnable any longer.
2898                Interrupt::Idle
2899            }
2900        }
2901    }
2902}
2903
2904/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
2905/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
2906/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
2907/// indistinguishable from any other runnable task - exactly the "off does
2908/// nothing" this feature promises.
2909fn advance_interrupt_tick(
2910    enabled: bool,
2911    state: Interrupt,
2912    in_flight: &[String],
2913    runnable: &[Task],
2914) -> Interrupt {
2915    if !enabled {
2916        return Interrupt::Idle;
2917    }
2918    advance_interrupt(state, in_flight, runnable)
2919}
2920
2921/// Which of this tick's runnable candidates the interrupt sequence actually
2922/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
2923/// each half is assertable on its own: this is the half that keeps a
2924/// competition and an interrupt from ever running at the same moment.
2925fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
2926    match state {
2927        Interrupt::Idle => candidates,
2928        Interrupt::Parking {
2929            parked,
2930            interrupt_task,
2931        } => {
2932            if in_flight.iter().any(|id| parked.contains(id)) {
2933                Vec::new()
2934            } else {
2935                candidates
2936                    .into_iter()
2937                    .filter(|t| &t.id == interrupt_task)
2938                    .collect()
2939            }
2940        }
2941        Interrupt::Running { .. } => Vec::new(),
2942        // At most one: even if `parked` names more than one id (more than
2943        // one run was in flight when the sequence began, only possible
2944        // above the default `max_concurrent_runs = 1`), only the first match
2945        // is offered. Capping this to a single candidate - not merely to
2946        // `parked`'s own ids - is what makes "exactly one resume, never two
2947        // dispatched together" true regardless of how many ordinary slots
2948        // happen to be free this tick.
2949        Interrupt::Resuming { parked } => candidates
2950            .into_iter()
2951            .find(|t| parked.contains(&t.id))
2952            .into_iter()
2953            .collect(),
2954    }
2955}
2956
2957/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
2958/// bundled into one parameter so `poll`'s own signature stays readable -
2959/// see [`drive`]'s call site for where these are actually read.
2960struct DispatchLimits {
2961    /// How many *ordinary* candidates run at once. See
2962    /// [`crate::config::Daemon::max_concurrent_runs`].
2963    max_concurrent: usize,
2964    /// See [`crate::config::Daemon::pause_for_interrupts`].
2965    pause_for_interrupts: bool,
2966}
2967
2968/// Which semaphore, if any, dispatching a candidate should draw its permit
2969/// from.
2970///
2971/// Pure and separate from [`poll`]'s loop body for the same reason
2972/// [`advance_interrupt`] is: the choice between "skip the ordinary pool
2973/// entirely", "spend the one urgent slot" and "spend an ordinary slot" is
2974/// exactly the policy this feature adds, and a policy only exercisable by
2975/// running the whole loop is a policy nobody checks.
2976#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2977enum PermitKind {
2978    /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
2979    /// Checked first - a task can be both a land resume and marked
2980    /// [`Task::urgent`], and the resume's own "must not queue behind
2981    /// anything" guarantee takes precedence.
2982    None,
2983    /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
2984    /// (never in addition to trying) the ordinary pool. This is what lets
2985    /// an urgent task dispatch while every ordinary slot is already checked
2986    /// out, and what stops a second urgent task from opening a third run: it
2987    /// waits on this same one-slot semaphore rather than falling through to
2988    /// the ordinary one.
2989    Urgent,
2990    /// The ordinary `max_concurrent_runs` pool - unaffected by either of the
2991    /// above.
2992    Ordinary,
2993}
2994
2995/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
2996/// own boolean, already computed by the caller from [`land_resume_state`].
2997fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
2998    if priority {
2999        PermitKind::None
3000    } else if urgent {
3001        PermitKind::Urgent
3002    } else {
3003        PermitKind::Ordinary
3004    }
3005}
3006
3007struct DispatchClaim {
3008    task: Task,
3009    claim: crate::queue::Claim,
3010    permit: Option<tokio::sync::OwnedSemaphorePermit>,
3011}
3012
3013/// Claim and re-read before choosing a lane: a queue listing may predate an
3014/// urgent toggle. All unsuccessful paths release the claim without an attempt.
3015fn claim_dispatch(
3016    queue: &Queue,
3017    candidate: &Task,
3018    cooling_down: bool,
3019    ordinary: &Arc<tokio::sync::Semaphore>,
3020    urgent: &Arc<tokio::sync::Semaphore>,
3021) -> Option<DispatchClaim> {
3022    let Ok(claim) = queue.claim(&candidate.id) else {
3023        tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
3024        return None;
3025    };
3026    let task = match queue.get(&candidate.id) {
3027        Ok(t) if t.status.runnable() => t,
3028        Ok(_) => return None,
3029        Err(e) => {
3030            tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
3031            return None;
3032        }
3033    };
3034    let resume = land_resume_state(&task);
3035    if resume == LandResume::StillWaiting {
3036        return None;
3037    }
3038    let priority = resume == LandResume::Ready;
3039    if !priority && cooling_down {
3040        return None;
3041    }
3042    // Never borrow an ordinary slot when the single urgent slot is busy.
3043    // Keep scanning other candidates when either pool has no free slot.
3044    let permit = match permit_kind(priority, task.urgent) {
3045        PermitKind::None => None,
3046        PermitKind::Urgent => Some(Arc::clone(urgent).try_acquire_owned().ok()?),
3047        PermitKind::Ordinary => Some(Arc::clone(ordinary).try_acquire_owned().ok()?),
3048    };
3049    Some(DispatchClaim {
3050        task,
3051        claim,
3052        permit,
3053    })
3054}
3055
3056/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
3057/// teardown and cannot skip the teardown on an early return.
3058///
3059/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
3060/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
3061/// land approval that has since been answered is dispatched outside that
3062/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
3063/// the whole point of parking there is that it must not queue behind
3064/// whatever else the loop happens to be running, even at the default of one.
3065/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
3066/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
3067/// these exemptions is still subject to the interrupt gate below, urgent
3068/// included: a land-resume or urgent candidate is exactly as much "something
3069/// else running" as an ordinary one from the interrupt sequence's point of
3070/// view, and letting either slip through while a run is being parked, or
3071/// while the interrupt task itself has the floor, is precisely the second
3072/// run 75dd's own "at most one run, ever, at once" guarantee must never
3073/// allow - see [`Interrupt`]'s own doc.
3074async fn poll(
3075    opts: &Opts,
3076    queue: &Queue,
3077    status: &Arc<Mutex<Status>>,
3078    home: &Path,
3079    worktrees_root: &Path,
3080    stop: &Stop,
3081    limits: DispatchLimits,
3082) -> Result<()> {
3083    let DispatchLimits {
3084        max_concurrent,
3085        pause_for_interrupts,
3086    } = limits;
3087    // Only consulted by `once`, where a task that just failed is still
3088    // `runnable` and would otherwise be picked up again inside the same drain.
3089    // In the long-running mode a later poll retrying a failed task is the point,
3090    // and the attempt counter is what bounds it.
3091    let mut attempted: Vec<String> = Vec::new();
3092    let sem = Arc::new(tokio::sync::Semaphore::new(max_concurrent));
3093    // One extra, permanent slot for `--urgent` tasks (see `Task::urgent`),
3094    // entirely separate from `sem`: an urgent candidate must dispatch
3095    // alongside whatever `sem` already has checked out, never by waiting for
3096    // one of those ordinary slots to free up and never by growing
3097    // `max_concurrent_runs` itself. Sized at one, not unbounded - see
3098    // `permit_kind`'s own doc - so a second `--urgent` task queues behind the
3099    // first on this same slot rather than opening a third run.
3100    let urgent_sem = Arc::new(tokio::sync::Semaphore::new(1));
3101    // A quota hit is a fact about the machine, not the task that happened to
3102    // surface it, and every other *ordinary* candidate is no less likely to
3103    // hit the same wall - see the warning below. A land-merge resume is
3104    // exempt: it is a human decision finishing, not a fresh competition, and
3105    // must not sit out a quota cooldown it did not cause.
3106    let quota_cooldown_until: Arc<Mutex<Option<Timestamp>>> = Arc::new(Mutex::new(None));
3107    let mut inflight: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
3108    let mut conductor = Conductor::new();
3109    // See `maybe_prune_cache_between_runs`'s own doc: this is the cache check
3110    // a congested queue would otherwise starve of the fully-idle branch below.
3111    let mut cache_last_checked: Option<Timestamp> = None;
3112    let mut disk_last_checked: Option<Timestamp> = None;
3113    // See `Interrupt`'s own doc: in-memory only, advanced once per tick.
3114    let mut interrupt = Interrupt::Idle;
3115    // The `Pause` handed to each dispatched candidate's own `Runner` - see
3116    // `attempt`'s new parameter - kept here so the tick that decides to park
3117    // a run for an interrupt can reach that specific run's handle and no
3118    // other's. Pruned to whatever is still in flight at the top of every
3119    // tick, so a finished attempt's handle does not linger.
3120    let mut interrupt_pauses: std::collections::HashMap<String, crate::graph::Pause> =
3121        std::collections::HashMap::new();
3122
3123    while !stop.stopped() {
3124        lock(status).polls += 1;
3125
3126        // Reap whatever finished since the last tick without blocking on
3127        // anything still running. `InFlightGuard` already released the slot
3128        // even if the spawned attempt panicked; this only surfaces that it
3129        // happened, since a panic swallowed here otherwise leaves no trace.
3130        while let Some(result) = inflight.try_join_next() {
3131            if let Err(e) = result {
3132                tracing::error!("a spawned attempt did not finish cleanly: {e}");
3133                notices::raise(Notice::error(
3134                    "loop:attempt",
3135                    "A queued attempt ended abnormally; check the task it was running.",
3136                ));
3137            }
3138        }
3139
3140        let swept = sweep_stale_claims(queue, STALE_CLAIM);
3141        if !swept.is_empty() {
3142            tracing::warn!(
3143                "swept {} stale claim(s) left behind by an earlier daemon: {}",
3144                swept.len(),
3145                swept.join(", ")
3146            );
3147        }
3148        // Capture stalled work before reclaiming it. A dead daemon's ordinary
3149        // lock is swept and reclaimed in this same poll, but the conductor
3150        // must still see that it was stranded rather than only its mechanical
3151        // terminal state.
3152        let now = Timestamp::now();
3153
3154        // No run this daemon spawned is mid-compile right now, whether or
3155        // not another candidate is about to start - see
3156        // `maybe_prune_cache_between_runs`'s own doc for why this cannot
3157        // wait for the queue to run dry.
3158        if !stop.busy_now() {
3159            maybe_prune_cache_between_runs(
3160                &opts.repo,
3161                opts,
3162                home,
3163                stop,
3164                &mut cache_last_checked,
3165                now,
3166            )
3167            .await;
3168        }
3169
3170        if cache_check_due(disk_last_checked, now, 30) {
3171            disk_last_checked = Some(now);
3172            if let Ok(cfg) = prepare(&opts.repo, opts) {
3173                crate::retention::sweep(home, &cfg.disk, now).await;
3174                // Shared-cache ownership makes this safe even with other runs
3175                // active. Reclaim idle outputs before asking writers to park.
3176                if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
3177                    tracing::warn!("disk pressure cache cleanup failed: {e:#}");
3178                }
3179                for current in lock(status).current.clone() {
3180                    if let Ok(state) = RunState::load_under(&current.run, home)
3181                        && let Some(reason) = disk_gate(&state.repo, &state.config)
3182                    {
3183                        if let Some(pause) = interrupt_pauses.get(&current.task) {
3184                            pause.park_because(reason);
3185                        }
3186                        notices::raise_in(
3187                            home,
3188                            Notice::warn(
3189                                "disk:pressure",
3190                                "Disk pressure persists after cleanup; active runs were asked to checkpoint and park. New starts and resumes wait for free space.",
3191                            ),
3192                        );
3193                    }
3194                }
3195            }
3196        }
3197
3198        let stalled = stalled_tasks(queue, home, now);
3199        let stalled_ids: std::collections::BTreeSet<_> =
3200            stalled.iter().map(|task| task.id.clone()).collect();
3201        let reclaimed = reclaim_orphaned_running(queue, opts.max_attempts);
3202        if !reclaimed.is_empty() {
3203            tracing::warn!(
3204                "reclaimed {} task(s) left `running` by a daemon that never \
3205                 recorded the outcome: {}",
3206                reclaimed.len(),
3207                reclaimed.join(", ")
3208            );
3209        }
3210        let abandoned_runs = reclaim_abandoned_runs(home, now);
3211        if !abandoned_runs.is_empty() {
3212            tracing::warn!(
3213                "failed {} run(s) left behind by a killed process, past every \
3214                 active seat's own timeout: {}",
3215                abandoned_runs.len(),
3216                abandoned_runs.join(", ")
3217            );
3218        }
3219
3220        // `home`, not `ask::Questions::open()`'s own process-global default:
3221        // `poll` is handed its home explicitly precisely so a test can point
3222        // it elsewhere, the same reason `Queue::at` and the status file path
3223        // are parameters rather than resolved here - see `drive`'s own doc.
3224        let questions = Questions::at(home.join("questions"));
3225
3226        // Deterministic: no model, run before the conductor sees anything so
3227        // its input reflects the queue's current, already-resolved state.
3228        repair_choice_offers(&questions);
3229        resolve_blockers(queue, &questions);
3230        apply_choice_actions(queue, &questions, home).await;
3231        triage::apply_answers(queue, &questions);
3232        reconcile_task_questions(queue, &questions);
3233        // Tell the chat a filed task or watched command has ended. Reconciled
3234        // here regardless of how it ended, and started only when no
3235        // upgrade is parking (the draft then waits for a manual resume).
3236        {
3237            let talks = crate::talk::Talks::at(home.join("talks"));
3238            crate::chat_notify::sweep(queue, &talks, home);
3239            crate::chat_watch::sweep(home, &talks);
3240            crate::chat_notify::start_turns(&talks, stop.parking(), &mut inflight);
3241        }
3242
3243        // The conductor gets one look per cycle, right before the loop takes
3244        // its next task, and only when there is something new to look at -
3245        // see `Conductor::worth_a_look`'s own doc for why "stalled is
3246        // non-empty" is the wrong test. Checked before `prepare` so an
3247        // unchanged cycle never pays for a synchronous config load.
3248        let finished: Vec<Task> = finished_tasks(queue)
3249            .into_iter()
3250            .filter(|task| !stalled_ids.contains(&task.id))
3251            // A parked run is waiting for this loop, not for a decision: the
3252            // conductor must not get to hold it or requeue it (a requeue
3253            // sets `fresh_start` and re-competes) before `attempt` resumes.
3254            .filter(|task| !awaiting_resume_with(task, |id| RunState::load_under(id, home)))
3255            .collect();
3256        let queued = queued_tasks(queue);
3257        // An empty queue has nothing to arrange. In particular, do not let
3258        // the conductor's initial snapshot cause synchronous config I/O
3259        // between the caller's stop notification and the idle wait below.
3260        if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3261            && conductor.worth_a_look(queue, &stalled, &finished)
3262        {
3263            match prepare(&opts.repo, opts) {
3264                Ok(cfg) => {
3265                    conductor
3266                        .maybe_run(
3267                            &cfg,
3268                            &opts.repo,
3269                            queue,
3270                            &questions,
3271                            home,
3272                            &queued,
3273                            &stalled,
3274                            &finished,
3275                            opts.max_attempts,
3276                        )
3277                        .await;
3278                }
3279                Err(e) => {
3280                    tracing::warn!("conductor: no config: {e:#}");
3281                    notices::raise(Notice::warn(
3282                        "loop:no-config",
3283                        "The loop could not read this repository's config, so held tasks are not being triaged.",
3284                    ));
3285                }
3286            }
3287        }
3288
3289        let candidates: Vec<Task> = runnable(queue)
3290            .into_iter()
3291            .filter(|t| !opts.once || !attempted.contains(&t.id))
3292            .collect();
3293
3294        // A task id only stays a key here while its attempt is genuinely in
3295        // flight; `status.current` is the same liveness fact `InFlightGuard`
3296        // maintains for the phone's own status file, so this piggybacks on
3297        // it rather than tracking a second copy of the same thing.
3298        let in_flight: Vec<String> = lock(status)
3299            .current
3300            .iter()
3301            .map(|c| c.task.clone())
3302            .collect();
3303        interrupt_pauses.retain(|id, _| in_flight.contains(id));
3304
3305        interrupt =
3306            advance_interrupt_tick(pause_for_interrupts, interrupt, &in_flight, &candidates);
3307        if let Interrupt::Parking {
3308            parked,
3309            interrupt_task,
3310        } = &interrupt
3311        {
3312            let reason = format!(
3313                "task {} asked to run first",
3314                crate::run::short_of(interrupt_task)
3315            );
3316            for id in parked {
3317                if let Some(pause) = interrupt_pauses.get(id) {
3318                    pause.park_because(reason.clone());
3319                }
3320            }
3321        }
3322        let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
3323
3324        let cooling_down =
3325            lock(&quota_cooldown_until).is_some_and(|until| Timestamp::now() < until);
3326
3327        let mut started_any = false;
3328        for candidate in candidates {
3329            if stop.stopped() {
3330                break;
3331            }
3332
3333            let Some(DispatchClaim {
3334                mut task,
3335                claim,
3336                permit,
3337            }) = claim_dispatch(queue, &candidate, cooling_down, &sem, &urgent_sem)
3338            else {
3339                continue;
3340            };
3341
3342            let task_id = task.id.clone();
3343            attempted.push(task_id.clone());
3344            lock(status).idle = false;
3345            // A stop asked for from here on is "finishing", not "stopped": the
3346            // run gets to reach a terminal status before the loop returns.
3347            stop.enter();
3348            started_any = true;
3349
3350            // A fresh, unshared handle - never `stop.pause()` - so parking
3351            // this run for an interrupt cannot leak into any other run this
3352            // loop ever drives. See `Pause`'s own doc.
3353            let run_pause = crate::graph::Pause::new();
3354            interrupt_pauses.insert(task_id.clone(), run_pause.clone());
3355
3356            let opts = opts.clone();
3357            let queue = queue.clone();
3358            let status = Arc::clone(status);
3359            let stop = stop.clone();
3360            let quota_cooldown_until = Arc::clone(&quota_cooldown_until);
3361            inflight.spawn(async move {
3362                // Held for the whole attempt: dropping either at the end of
3363                // this task is what releases the claim and, for an ordinary
3364                // candidate, frees its concurrency slot back to the loop.
3365                let _claim = claim;
3366                let _permit = permit;
3367                // See `InFlightGuard`: this must survive a panic inside `attempt`.
3368                let _inflight = InFlightGuard {
3369                    status: &status,
3370                    stop: &stop,
3371                    task_id: &task_id,
3372                };
3373                let quota = attempt(&opts, &queue, &status, &stop, run_pause, &mut task).await;
3374                lock(&status).completed += 1;
3375                // A quota loss is a fact about the machine, not this task, and
3376                // the next ordinary candidate the loop offers is no less
3377                // likely to hit the same wall: without a cooldown here a
3378                // whole backlog can be run - and failed - in the seconds it
3379                // takes each attempt to notice the CLI is out of quota.
3380                let now = Timestamp::now();
3381                if let Some(until) = cooldown_until(&quota, now) {
3382                    let wait = until.as_second() - now.as_second();
3383                    *lock(&quota_cooldown_until) = Some(until);
3384                    let hint = quota
3385                        .iter()
3386                        .find(|q| q.reset.is_some())
3387                        .and_then(|q| q.reset.as_deref());
3388                    match hint {
3389                        Some(h) => tracing::warn!(
3390                            "quota hit; waiting {wait}s before taking another ordinary task \
3391                             (CLI reported reset: {h})"
3392                        ),
3393                        None => tracing::warn!(
3394                            "quota hit; waiting {wait}s before taking another ordinary task \
3395                             (no reset hint reported)"
3396                        ),
3397                    }
3398                }
3399            });
3400        }
3401
3402        if started_any {
3403            continue;
3404        }
3405
3406        if stop.busy_now() {
3407            // Something started on an earlier tick is still running. Recheck
3408            // soon rather than sleeping out the whole poll interval - a freed
3409            // slot, or a land approval answered mid-run, must not sit idle
3410            // for it.
3411            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
3412            continue;
3413        }
3414
3415        // Truly idle: nothing new to start and nothing still running.
3416        lock(status).idle = true;
3417        if opts.once {
3418            // A one-shot drain must perform the same post-work cleanup as a
3419            // daemon that reached a normal idle interval. The startup pass
3420            // cannot see runs or cache files produced by this drain.
3421            janitor(&opts.repo, opts, home, worktrees_root).await;
3422            resweep_superseded_attempts(queue, home);
3423            triage_held(queue, home, opts).await;
3424            break;
3425        }
3426        stop.idle(opts.poll).await;
3427        if stop.stopped() {
3428            continue;
3429        }
3430        // Housekeeping only after a full quiet interval. Running it before
3431        // the first idle wait can block the executor while an operator's
3432        // stop request is waiting to be scheduled, defeating Stop's retained
3433        // wake permit. No run can start while this branch is active, so the
3434        // janitor still never races an in-flight compile.
3435        janitor(&opts.repo, opts, home, worktrees_root).await;
3436        resweep_superseded_attempts(queue, home);
3437        triage_held(queue, home, opts).await;
3438    }
3439
3440    // Never return while a run is still in flight, whichever way the loop
3441    // above exited: a stop only sets a flag - see `serve_until` - and
3442    // returning here while `inflight` still holds spawned work would abandon
3443    // it exactly as a mid-node kill would.
3444    while let Some(result) = inflight.join_next().await {
3445        if let Err(e) = result {
3446            tracing::error!("a spawned attempt did not finish cleanly: {e}");
3447            notices::raise(Notice::error(
3448                "loop:attempt",
3449                "A queued attempt ended abnormally; check the task it was running.",
3450            ));
3451        }
3452    }
3453    Ok(())
3454}
3455
3456/// Run one claimed task to a terminal status and record the outcome.
3457///
3458/// Every transition is flushed to the queue as it happens, so the state on disk
3459/// is what actually occurred rather than what this process still intends to
3460/// write.
3461async fn attempt(
3462    opts: &Opts,
3463    queue: &Queue,
3464    status: &Arc<Mutex<Status>>,
3465    stop: &Stop,
3466    interrupt_pause: crate::graph::Pause,
3467    task: &mut Task,
3468) -> Vec<QuotaLoss> {
3469    let repo = repo_for(task, &opts.repo);
3470    tracing::info!(
3471        "task {} — {} (repo {})",
3472        task.short(),
3473        task.title,
3474        repo.display()
3475    );
3476
3477    // A stop spends no agent resources and uses the saved landing owner.
3478    // Current roster edits, missing attachments or a failed config fetch must
3479    // never turn it into a new implementation, or prevent a PR from closing.
3480    if let Some(previous) = task.runs.last().and_then(|id| RunState::load(id).ok())
3481        && previous
3482            .merge_decision
3483            .as_ref()
3484            .is_some_and(|decision| !decision.closed)
3485        && previous.status != RunStatus::Landing
3486        && !crate::merge_decision::resumable_hold(&previous)
3487    {
3488        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)));
3489        record(queue, task);
3490        return Vec::new();
3491    }
3492    let stop_owner = task
3493        .runs
3494        .last()
3495        .and_then(|id| RunState::load(id).ok())
3496        .filter(|state| {
3497            crate::merge_decision::resumable_hold(state)
3498                || state.status == RunStatus::Landing
3499                    && state.land_approval.as_ref().is_some_and(|binding| {
3500                        Questions::open().get(&binding.question).is_ok_and(|q| {
3501                            q.run == state.id
3502                                && q.resolution()
3503                                    .as_deref()
3504                                    .is_some_and(crate::merge_decision::stops)
3505                        })
3506                    })
3507        });
3508    if let Some(owner) = stop_owner {
3509        let mut runner = match Runner::resume(&owner.id) {
3510            Ok(runner) => runner,
3511            Err(e) => {
3512                task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
3513                record(queue, task);
3514                return Vec::new();
3515            }
3516        };
3517        runner.on_pause(stop.pause());
3518        runner.watch_interrupt(interrupt_pause);
3519        let quota_before = runner.state.quota.clone();
3520        task.start(owner.id.clone());
3521        record(queue, task);
3522        lock(status).current.push(Current {
3523            task: task.id.clone(),
3524            run: owner.id,
3525        });
3526        runner.state.next_pass_task_entry = true;
3527        let result = runner.execute().await;
3528        return finish_attempt(
3529            opts.max_attempts,
3530            queue,
3531            task,
3532            &runner.state,
3533            &quota_before,
3534            result,
3535        );
3536    }
3537
3538    let unfinished = (!task.fresh_start)
3539        .then(|| unfinished_run(&task.runs, task.short()))
3540        .flatten()
3541        .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
3542    let previous = task.runs.last().and_then(|id| RunState::load(id).ok());
3543    if !task.fresh_start
3544        && task.pr_recovery.is_none()
3545        && task.review_branch.is_none()
3546        && task.resume_override.is_none()
3547        && previous
3548            .as_ref()
3549            .is_some_and(|run| run.retired_to.is_some())
3550        && unfinished.is_none()
3551    {
3552        task.hold_unrequested_retry(Some("Recorded recovery authority is unavailable, no longer resumable or no longer authorized for these instructions. Inspect the retained lineage and select a recovery source explicitly; no replacement competition was started.".into()));
3553        record(queue, task);
3554        return Vec::new();
3555    }
3556
3557    let saved_recovery = previous.as_ref().filter(|run| {
3558        task.replacement.is_none()
3559            && task.pr_recovery.as_ref().is_some_and(|selected| {
3560                selected.check_task(&task.id, &task.instruction).is_ok()
3561                    && selected_starter(selected, Some(run), unfinished.as_deref())
3562                        == Starter::Resume(run.id.clone())
3563            })
3564    });
3565
3566    // The repository's magi.toml comes from `<remote>/<base>`, fetched now. A
3567    // failure here is the network's or the operator's, not the task's: hold
3568    // without spending an attempt, never fall back to a possibly stale copy.
3569    let explicit = match &task.overrides {
3570        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
3571        Some(_) => opts.config.as_deref(),
3572        None => opts.config.as_deref(),
3573    };
3574    let (mut config, layers) = if let Some(run) = saved_recovery {
3575        // A matching resume owns its resolved configuration and evidence;
3576        // current layers and inherited overrides only configure new work.
3577        let mut saved = run.clone();
3578        if let Err(e) = saved.configure_recovery_resume() {
3579            task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
3580            record(queue, task);
3581            return Vec::new();
3582        }
3583        (saved.config, Vec::new())
3584    } else {
3585        let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
3586            Ok(loaded) => loaded,
3587            Err(e) => {
3588                let reason = format!("[config] {e:#}");
3589                record_config_failure(task, &e);
3590                task.last_error = Some(reason.clone());
3591                task.hold_machine(Some(reason));
3592                record(queue, task);
3593                return Vec::new();
3594            }
3595        };
3596        if let Err(e) = apply_options(&mut config, opts, task) {
3597            task.hold_manual(Some(format!(
3598                "[config] {e:#}; correct the merge override before releasing the task"
3599            )));
3600            record(queue, task);
3601            return Vec::new();
3602        }
3603        if let Some(selected) = &task.pr_recovery
3604            && let Err(e) = selected.configure(&mut config)
3605        {
3606            task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
3607            record(queue, task);
3608            return Vec::new();
3609        }
3610        (config, layers)
3611    };
3612    let config_evidence = crate::pr_recovery::ConfigEvidence {
3613        layers,
3614        overrides: task.overrides.clone(),
3615        daemon_merge: task
3616            .overrides
3617            .as_ref()
3618            .is_none_or(|o| o.inherit_daemon_options)
3619            .then(|| opts.merge.clone())
3620            .flatten(),
3621    };
3622    apply_task_implementers(&mut config, task);
3623    if let Some(replacement) = &task.replacement {
3624        let safe = RunState::load(&replacement.run).is_ok_and(|old| {
3625            old.liveness(false) == Liveness::Dead
3626                && old.merge_decision.as_ref().is_some_and(|d| {
3627                    d.closed
3628                        && d.question == replacement.question
3629                        && d.replacement_run.as_ref().is_none_or(|run| {
3630                            task.runs.last() == Some(run)
3631                                && RunState::load(run).is_ok_and(|current| {
3632                                    current.replaces.as_ref().is_some_and(|pin| {
3633                                        pin.question == replacement.question
3634                                            && pin.agent == replacement.agent
3635                                    })
3636                                })
3637                        })
3638                })
3639        });
3640        if !safe {
3641            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()));
3642            record(queue, task);
3643            return Vec::new();
3644        }
3645        match config.agent(&replacement.agent) {
3646            Ok(agent) if crate::agent::installed(agent) => {}
3647            _ => {
3648                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)));
3649                record(queue, task);
3650                return Vec::new();
3651            }
3652        }
3653        config.graph.implementers = 1;
3654        config.graph.land_approval = true;
3655        config.merge.mode = MergeMode::Pr;
3656        config.graph.selected_implementer = Some(replacement.agent.clone());
3657    }
3658    let p = phrases(&config.graph.language);
3659    let start_failed = p.could_not_start;
3660    // Resolve once for both admission and settlement. Review-only runs do not
3661    // have seed records, and may rebase later; neither fact can refund a failed
3662    // automatic generation. Include an explicit review source's current head.
3663    if let Ok(base) =
3664        crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
3665            .await
3666        && let Ok(head) =
3667            crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
3668    {
3669        let seeds = crate::refs::resolve(
3670            &repo,
3671            &head,
3672            &config.merge.remote,
3673            &format!("{}\n{}", task.title, instruction_for(task)),
3674        )
3675        .await;
3676        let mut inputs = crate::queue::recovery_inputs(&seeds);
3677        if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
3678            let source = crate::git::rev_parse(&repo, branch)
3679                .await
3680                .unwrap_or_default();
3681            inputs.push_str(&format!(";review:{branch}:{source}"));
3682        }
3683        if let Some(reason) = task.recovery_exhausted(
3684            &head,
3685            &inputs,
3686            task.attempt_limit
3687                .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
3688        ) {
3689            task.hold_unrequested_retry(Some(reason));
3690            record(queue, task);
3691            return Vec::new();
3692        }
3693        task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
3694    }
3695
3696    // The free-space gate, checked *before* anything is minted: a task that
3697    // waits out a full disk costs nothing yet, and must not spend an attempt
3698    // or start a run the machine cannot finish. Held tasks stay in the list
3699    // for the human to see, and `magi task release` re-queues them when space
3700    // comes back - the same recovery as any other hold. A volume whose free
3701    // space cannot be measured closes the gate too: starting a run blind on a
3702    // disk that may be full is how the machine ends up with 6.7 GB free.
3703    if let Some(reason) = disk_gate(&repo, &config) {
3704        task.notice_cause("disk-space", None, None);
3705        task.last_error = Some(reason.clone());
3706        task.hold_machine(Some(reason.clone()));
3707        record(queue, task);
3708        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
3709        // Stable wording - the free-space figures live in the task's hold
3710        // reason, and changing numbers would relight the bell every poll.
3711        notices::raise(
3712            Notice::warn(
3713                &format!("disk:{}", repo.display()),
3714                "A task was held for want of free disk space; free some, then release it from the queue.",
3715            )
3716            .link(Link::Task {
3717                id: task.id.clone(),
3718            }),
3719        );
3720        return Vec::new();
3721    }
3722
3723    // A resumable run of this task is carried on, never re-competed. The
3724    // candidates are built and paid for, and a fresh competition races a
3725    // second implementation against them.
3726    //
3727    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
3728    // started 3cbf on the same task a moment later, duplicating two and a
3729    // half hours of agent work. Then b25f stalled on a judge that timed out
3730    // and one that answered with no JSON - `quota: 0`, so nothing the machine
3731    // was to blame for - and 4043 started **one second** later, buying three
3732    // fresh implementations to reach the same panel. `RunStatus::resumable`
3733    // rather than `!done()` is what catches the second case: a stall is
3734    // terminal, and its cheap recovery re-asks only the absent seats.
3735    //
3736    // A load failure is warned about rather than silently read as "not
3737    // resumable": the alternative is exactly what let a schema mismatch on
3738    // run `eba2` fall through to a full re-competition with nobody told why.
3739    // `crate::conduct` is what actually offers a better answer than
3740    // `Runner::start` here (see `Recovery::Review`), once this task's next
3741    // failure shows it up as `held`/`failed` with the run state unreadable.
3742    // `crate::conduct` chose `Review` for this task on an earlier cycle: its
3743    // branch survived, and this reopens exactly that branch as a
3744    // review-only pass rather than resuming or competing again. Consumed
3745    // (cleared) here whichever way this goes, so it never outlives this one
3746    // attempt - see `queue::Task::review_branch`.
3747    let review_branch = take_review_branch(task, previous.as_ref());
3748    let branch_exists = match &review_branch {
3749        Some(branch) => crate::git::branch_exists(&repo, branch)
3750            .await
3751            .unwrap_or(false),
3752        None => false,
3753    };
3754    // An explicit `magi review <branch>` is reviewed whatever happens to the
3755    // branch unless an explicit implementer change requires fresh work. An
3756    // unfinished run of the same task still wins, so a retry resumes.
3757    let proposed = match (&review_branch, &unfinished, &task.review_of) {
3758        (None, None, Some(branch)) => Starter::Review(branch.clone()),
3759        _ => choose_starter(
3760            review_branch.as_deref(),
3761            branch_exists,
3762            unfinished.as_deref(),
3763        ),
3764    };
3765    let retry_selected = task.replacement.is_some()
3766        && task.resumption.is_some()
3767        && !task.fresh_start
3768        && previous.as_ref().is_some_and(|run| {
3769            run.replaces.is_some()
3770                && ((run.status == RunStatus::Failed && run.viable().is_empty())
3771                    || (run.status == RunStatus::Blocked && run.tally.is_none()))
3772        });
3773    let stop_pin = task
3774        .resume_override
3775        .as_ref()
3776        .filter(|pin| {
3777            Questions::open().get(&pin.question_id).is_ok_and(|q| {
3778                q.node == land::APPROVAL_NODE
3779                    && q.resolution()
3780                        .as_deref()
3781                        .is_some_and(crate::merge_decision::stops)
3782            })
3783        })
3784        .and_then(|pin| pin.pinned_run.clone());
3785    let starter = if let Some(run) = stop_pin {
3786        // Stop actions resume their exact owner even after seat-count edits;
3787        // they must never fall through to implementation or a takeover.
3788        Starter::Resume(run)
3789    } else if retry_selected {
3790        Starter::Resume(previous.as_ref().unwrap().id.clone())
3791    } else if let Some(selected) = &task.pr_recovery {
3792        if selected.check_task(&task.id, &task.instruction).is_ok() {
3793            selected_starter(selected, previous.as_ref(), unfinished.as_deref())
3794        } else {
3795            Starter::Review(selected.branch.clone())
3796        }
3797    } else {
3798        starter_with_implementers(task, previous.as_ref(), proposed)
3799    };
3800    // An explicit resume pin must never degrade into a new competition or
3801    // takeover, including when its run stops being eligible after the answer.
3802    if let Some(pin) = &task.resume_override
3803        && let Some(run) = &pin.pinned_run
3804        && starter != Starter::Resume(run.clone())
3805    {
3806        let run = run.clone();
3807        task.notice_cause("resume-owner", Some(&run), None);
3808        task.hold_machine(Some(format!(
3809            "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
3810            task.id
3811        )));
3812        record(queue, task);
3813        return Vec::new();
3814    }
3815    if task.replacement.is_some()
3816        && previous.as_ref().is_some_and(|run| run.replaces.is_some())
3817        && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
3818    {
3819        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()));
3820        record(queue, task);
3821        return Vec::new();
3822    }
3823    if let Some(reason) = retained_attempt_hold(
3824        task,
3825        &starter,
3826        config.disk.retained_attempt_limit,
3827        RunState::load,
3828    ) {
3829        // The review choice was consumed above. Preserve it across this hold
3830        // so a later release cannot silently become a fresh implementation.
3831        if let Starter::Review(branch) = &starter {
3832            task.review_branch = Some(branch.clone());
3833        }
3834        task.hold_unrequested_retry(Some(reason));
3835        record(queue, task);
3836        return Vec::new();
3837    }
3838    // Absolute paths of the files the task was filed with, re-read from the
3839    // task now so a file attached while it was held reaches a resumed run
3840    // too. A stored name whose file has gone is an error before any agent is
3841    // paid for, never a silent omission the implementer cannot notice.
3842    let attachments = match task_attachments(queue, task) {
3843        Ok(a) => a,
3844        Err(e) => {
3845            task.attempts += 1;
3846            task.fail_startup_target(
3847                "startup-attachments",
3848                e.name.clone(),
3849                format!("{start_failed}{e:#}"),
3850                opts.max_attempts,
3851            );
3852            record(queue, task);
3853            return Vec::new();
3854        }
3855    };
3856    let startup_pause = stop.pause();
3857    let startup_interrupt = interrupt_pause.clone();
3858    let wait = crate::repo_lock::WaitPolicy::new(
3859        Duration::from_secs(config.graph.timeout_resource_wait),
3860        move || startup_pause.parked() || startup_interrupt.parked(),
3861    );
3862    // Startup includes review takeover and recovery. Do not embed its large
3863    // future in both the wait scope and the surrounding attempt stack frame.
3864    let started = wait.scope(Box::pin(async { match &starter {
3865        Starter::Review(_) if task.pr_recovery.is_some() => {
3866            let selected = task.pr_recovery.clone().expect("selected recovery");
3867            match selected.check_task(&task.id, &task.instruction) {
3868                Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
3869                    .await
3870                    .map(|mut r| {
3871                        r.state.attachments = attachments.clone();
3872                        r
3873                    }),
3874                Err(e) => Err(e),
3875            }
3876        }
3877        Starter::Review(branch) => {
3878            tracing::info!(
3879                "task {} reopens `{branch}` as a review-only pass",
3880                task.short()
3881            );
3882            // Every earlier attempt is superseded by the one being minted
3883            // now, so a branch one of them still holds may be taken over.
3884            let takeover = crate::handover::Takeover {
3885                earlier: task.earlier_attempts().to_vec(),
3886                home: crate::run::home(),
3887                choice: take_divergence_answer(branch, &config.merge.remote, task),
3888                task_instruction: Some(instruction_for(task)),
3889            };
3890            Runner::review_taking_over(
3891                &repo,
3892                branch,
3893                config,
3894                Some(takeover),
3895                crate::run::Origin::queue(&task.id),
3896            )
3897            .await
3898        }
3899        Starter::Resume(id) => {
3900            tracing::info!("resuming run {id} rather than competing again");
3901            Runner::resume(id).and_then(|mut r| {
3902                if retry_selected {
3903                    // The explicit queue release retries this same pinned
3904                    // implementation, preserving the attempt and worktrees.
3905                    for candidate in &mut r.state.candidates {
3906                        candidate.failed = None;
3907                        candidate.empty = false;
3908                        candidate.commits = 0;
3909                    }
3910                    r.state.status = RunStatus::Implementing;
3911                    r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
3912                }
3913                if r.state.prep_failure.is_some() {
3914                    let approval = task
3915                        .resumption
3916                        .as_ref()
3917                        .context("preparation retry requires an explicit task release")?;
3918                    r.retry_preparation(approval.at)?;
3919                }
3920                if let Some(instruction) =
3921                    prepare_instruction(&starter, Some(&r.state.instruction), task)
3922                {
3923                    r.state.instruction = instruction;
3924                }
3925                r.state.attachments = attachments.clone();
3926                if task.replacement.is_some() {
3927                    r.state.config.merge.mode = MergeMode::Pr;
3928                    r.state.config.graph.land_approval = true;
3929                }
3930                // Replacements publish a new PR and ask again. Selected PR
3931                // recoveries keep their saved disposition; ordinary runs can
3932                // retain the task's merge override.
3933                if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
3934                    .overrides
3935                    .as_ref()
3936                    .and_then(|o| o.merge.as_deref())
3937                    .and_then(|m| merge_mode(m).ok())
3938                {
3939                    r.state.config.merge.mode = mode;
3940                }
3941                Ok(r)
3942            })
3943        }
3944        Starter::Start => {
3945            if let Some(branch) = &review_branch {
3946                tracing::warn!(
3947                    "conductor chose review for task {} but branch `{branch}` no longer \
3948                     exists; requeuing as a fresh competition instead",
3949                    task.short()
3950                );
3951            }
3952            let instruction = prepare_instruction(&starter, None, task)
3953                .unwrap_or_else(|| task.instruction.clone());
3954            Runner::start_naming(
3955                &repo,
3956                instruction,
3957                &task.title,
3958                config,
3959                crate::run::Origin::queue(&task.id),
3960            )
3961            .await
3962            .map(|mut r| {
3963                r.state.attachments = attachments.clone();
3964                r
3965            })
3966        }
3967    }})).await;
3968    let mut runner = match started {
3969        Ok(r) => r,
3970        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
3971            task.last_error = Some(e.to_string());
3972            if stop.parking() || interrupt_pause.parked() {
3973                let attempts = task.attempts;
3974                task.park(e.to_string());
3975                // Startup has not spent an attempt to refund.
3976                task.attempts = attempts;
3977            } else {
3978                task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
3979            }
3980            record(queue, task);
3981            return Vec::new();
3982        }
3983        // A branch an earlier attempt still holds and magi will not release
3984        // by itself is the operator's call, not a failed attempt: hold the
3985        // task with the reason, spend nothing, and say so on the bell.
3986        Err(e) if task.pr_recovery.is_some() => {
3987            task.startup_notice_cause("startup-public-head");
3988            task.attempts += 1;
3989            if let Some(partial) = e.downcast_ref::<crate::pr_recovery::StartupFailed>() {
3990                task.link_run(&partial.run);
3991                task.record_pass(&partial.run, 0, task.attempts, None);
3992            }
3993            task.last_error = Some(format!("{start_failed}{e:#}"));
3994            task.hold_unrequested_retry(Some(format!(
3995                "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."
3996            )));
3997            record(queue, task);
3998            return Vec::new();
3999        }
4000        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
4001            let detail = match e.downcast_ref::<crate::handover::Refused>() {
4002                Some(r) => (p.handover_refused)(r),
4003                None => format!("{e:#}"),
4004            };
4005            task.startup_notice_cause("startup-handover");
4006            let reason = format!("{start_failed}{detail}");
4007            task.last_error = Some(reason.clone());
4008            // Consumed above by `take`; keep it so the released task retries
4009            // as a review of this same branch.
4010            let branch = match &starter {
4011                Starter::Review(branch) => Some(branch.clone()),
4012                _ => None,
4013            };
4014            // The hold's own `task:<id>` notice (raised by `Queue::put`) is the
4015            // one page; the guidance rides in the reason, fixed per state so a
4016            // re-put never changes the wording and relights it.
4017            task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
4018            record(queue, task);
4019            tracing::warn!(
4020                "holding {} for a branch it cannot take over: {e:#}",
4021                task.short()
4022            );
4023            return Vec::new();
4024        }
4025        // A branch that differs between here and the remote in ways magi
4026        // cannot prove are the same change is a decision for the owner, not a
4027        // failed attempt: ask with both sides laid out, spend no attempt, and
4028        // let the answer requeue the task.
4029        Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
4030            let d = e
4031                .downcast_ref::<crate::reconcile::Diverged>()
4032                .expect("checked by the guard");
4033            let mut q = ask::Question::new(
4034                task.id.clone(),
4035                crate::reconcile::NODE.to_owned(),
4036                crate::reconcile::SEAT.to_owned(),
4037                d.summary(),
4038                d.detail(),
4039                d.choices(),
4040            );
4041            match Questions::open().put(&mut q) {
4042                Ok(()) => {
4043                    task.last_error = Some(format!("{e:#}"));
4044                    // Consumed above by `take`; the answer has to reach a review
4045                    // of this same branch, so keep pointing the task at it.
4046                    task.review_branch = Some(d.branch.clone());
4047                    task.review_instruction = Some(task.instruction.clone());
4048                    task.block(vec![q.id.clone()], Some(d.summary()));
4049                }
4050                Err(put) => {
4051                    tracing::warn!("could not file the divergence question: {put:#}");
4052                    task.attempts += 1;
4053                    task.fail_startup(
4054                        "startup-question-store",
4055                        format!("{start_failed}{e:#}"),
4056                        opts.max_attempts,
4057                    );
4058                }
4059            }
4060            record(queue, task);
4061            return Vec::new();
4062        }
4063        Err(e) => {
4064            // The answer was stale and nothing was applied: keep pointing at
4065            // the branch so the next attempt asks again against its new tips.
4066            // Nothing went wrong with the task, so no attempt is spent: a
4067            // budget one short of its limit must not hold it instead of
4068            // letting the question be asked again.
4069            if e.downcast_ref::<crate::reconcile::Stale>().is_some()
4070                && let Starter::Review(branch) = &starter
4071            {
4072                task.review_branch = Some(branch.clone());
4073                task.review_instruction = Some(task.instruction.clone());
4074                task.last_error = Some(format!("{start_failed}{e:#}"));
4075                task.status = crate::queue::TaskStatus::Failed;
4076                record(queue, task);
4077                return Vec::new();
4078            }
4079            task.attempts += 1;
4080            task.last_error = Some(format!("{start_failed}{e:#}"));
4081            task.startup_notice_cause("startup-source");
4082            task.hold_unrequested_retry(Some(format!(
4083                "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
4084            )));
4085            record(queue, task);
4086            return Vec::new();
4087        }
4088    };
4089    if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
4090        runner.state.recovery_config = Some(config_evidence);
4091    }
4092    if let Some(replacement) = &task.replacement {
4093        if matches!(starter, Starter::Start) {
4094            runner.state.instruction.push_str(&format!(
4095                "\n\n# Replacement review context\n{}",
4096                replacement.context
4097            ));
4098        }
4099        runner.state.replaces = Some(replacement.clone());
4100        runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
4101        if let Ok(mut old) = RunState::load(&replacement.run)
4102            && let Some(d) = &mut old.merge_decision
4103        {
4104            d.replacement_run = Some(runner.state.id.clone());
4105            old.event(
4106                "replacement",
4107                format!(
4108                    "replacement run {} owns the next attempt; old PR remains closed",
4109                    runner.state.id
4110                ),
4111            );
4112            if let Err(e) = old.save() {
4113                task.hold_manual(Some(format!(
4114                    "Could not link replacement history: {e}; no agents dispatched"
4115                )));
4116                record(queue, task);
4117                return Vec::new();
4118            }
4119        }
4120    }
4121    runner.state.task_instruction = Some(task.instruction.clone());
4122    // The follow-up depth is fixed now, while the task certainly exists:
4123    // deleting it later must not reset the cap (`crate::followup`).
4124    runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
4125    if runner.state.origin_chat.is_none() {
4126        runner.state.origin_chat = task.chat_talk().map(str::to_owned);
4127    }
4128    // A stop that means "park" reaches the graph through this handle.
4129    runner.on_pause(stop.pause());
4130    // `poll`'s interrupt scheduler reaches this one run - and no other -
4131    // through this handle. See `Pause`'s own doc for why these are never
4132    // the same one.
4133    runner.watch_interrupt(interrupt_pause);
4134
4135    // `start` has minted the run, so the task can now point at it. Persisting
4136    // `Running` before `execute` is what makes a crash mid-run legible.
4137    let run = runner.state.id.clone();
4138    task.start(run.clone());
4139    record(queue, task);
4140    lock(status).current.push(Current {
4141        task: task.id.clone(),
4142        run,
4143    });
4144
4145    // `RunState::quota` is the run's whole history across every resume, so
4146    // only what this execution added may arm the cooldown or earn a refund.
4147    let quota_before = runner.state.quota.clone();
4148    runner.state.next_pass_task_entry = true;
4149    let result = runner.execute().await;
4150    finish_attempt(
4151        opts.max_attempts,
4152        queue,
4153        task,
4154        &runner.state,
4155        &quota_before,
4156        result,
4157    )
4158}
4159
4160/// Settle `task` after its run executed: the verdict, the diagnosis, the
4161/// supersession of earlier attempts and the save. Shared by the loop and by
4162/// `magi run --resume`, so an attempt is counted one way wherever it ran.
4163/// Returns the quota losses this execution added to the run.
4164pub fn finish_attempt(
4165    max_attempts: usize,
4166    queue: &Queue,
4167    task: &mut Task,
4168    state: &RunState,
4169    quota_before: &[QuotaLoss],
4170    result: Result<()>,
4171) -> Vec<QuotaLoss> {
4172    let detail = match result {
4173        Ok(()) => describe(state),
4174        Err(e) => format!("{e:#}"),
4175    };
4176    let fresh = losses_this_attempt(quota_before, &state.quota);
4177    let verdict = Verdict {
4178        status: state.status,
4179        // A run that opened a pull request handed its work over, whatever the
4180        // gate then decided about merging it.
4181        left_pr: state.pr.is_some(),
4182        // Only a rate limit earns the task its attempt back - and only one
4183        // suffered now: a refund justified by a previous session's loss is
4184        // the same mistake as re-arming the cooldown from it. A stalled run
4185        // resumed without hitting quota again therefore spends its attempt,
4186        // like any other failure of the task's own.
4187        quota_hit: !fresh.is_empty(),
4188        // A run that parked was asked to stop; that is not a failure and must
4189        // not spend an attempt, or replacing the binary a few times would
4190        // exhaust a task's budget without an agent ever misbehaving.
4191        parked: state.parked,
4192        // A quota loss that left nothing viable is the same machine fact as a
4193        // `Stalled` quota loss; see `settle`'s doc table.
4194        no_viable_candidates: state.viable().is_empty(),
4195    };
4196    if let Some(replacement) = &state.replaces
4197        && let Some(pr) = &state.pr
4198        && let Ok(mut old) = RunState::load(&replacement.run)
4199        && let Some(d) = &mut old.merge_decision
4200    {
4201        d.replacement_pr = Some(pr.url.clone());
4202        let _ = old.save();
4203    }
4204    settle_and_diagnose(task, verdict, &detail, max_attempts, state);
4205    if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
4206        task.hold_unrequested_retry(Some(format!(
4207            "Candidate setup failed: {detail}. Select a complete implementation with `magi task recover-pr`, or correct the referenced source before explicitly releasing the task."
4208        )));
4209    }
4210    if task.status == TaskStatus::Done {
4211        supersede_prior_runs(task, &crate::run::home());
4212    }
4213    record(queue, task);
4214    tracing::info!(
4215        "task {} is {} after run {} ({})",
4216        task.short(),
4217        task.status.as_str(),
4218        state.short(),
4219        label(state.status)
4220    );
4221    fresh
4222}
4223
4224/// A task a hand-started run leaves runnable (failed with attempts to spare,
4225/// or requeued) is **held**: nobody asked for a retry, and a loop starting
4226/// later must not spend agent calls on it. `magi task release` retries.
4227pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
4228    // A run parked on the owner's word about a withheld PR title/body is not a
4229    // failure nobody asked to retry: it resumes (answer, or the neutral text on
4230    // the deadline) the moment a loop serves the queue, via `land_resume_state`.
4231    // Holding it would keep it from ever being a candidate.
4232    let waits_on_owner = withheld_text_wait(task).is_some();
4233    if task.status.runnable()
4234        && !waits_on_owner
4235        && !(task.fresh_start && task.replacement.is_some())
4236    {
4237        let why = task.last_error.clone().map_or_else(
4238            || "the run did not finish".to_owned(),
4239            |e| format!("the run did not finish: {e}"),
4240        );
4241        task.hold_unrequested_retry(Some(format!(
4242            "{why}. It was started by hand, so it is not retried \
4243             automatically; `magi task release` retries it."
4244        )));
4245        record(queue, task);
4246    }
4247}
4248
4249/// Whether an attempt at a task whose newest run is `run` would resume that
4250/// run rather than start a fresh competition. `magi run --resume` hands a run
4251/// to a live loop only when this holds.
4252#[must_use]
4253pub fn loop_would_resume(run: &str) -> bool {
4254    unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
4255}
4256
4257/// A loop in another process that is alive right now: a fresh heartbeat in
4258/// `<home>/daemon.json` published by a pid that is not `own_pid`. `Some(pid)`
4259/// carries the pid it published (`None` inside when it published none - a
4260/// fresh heartbeat is still evidence of a live loop).
4261///
4262/// The one judgement of "is somebody else serving this queue", shared by the
4263/// web UI's refusal to start a second loop and by `magi run` / `magi review`
4264/// deciding whether to hand a task to the loop. A claim file proves nothing
4265/// here: whether a claim succeeds says nothing about whether its owner lives.
4266#[must_use]
4267pub fn foreign_loop(
4268    reading: Option<&Reading>,
4269    now: Timestamp,
4270    own_pid: u32,
4271) -> Option<Option<u32>> {
4272    let reading = reading.filter(|r| r.running(now))?;
4273    match reading.pid {
4274        Some(pid) if pid == own_pid => None,
4275        pid => Some(pid),
4276    }
4277}
4278
4279/// Run one task this process has claimed, in this process, through exactly the
4280/// attempt a daemon would make: the same starter choice (start, resume,
4281/// review), the same `Task::start` / `settle` transitions, attempt counting,
4282/// quota refund and parking. No second dispatcher - `magi run` and `magi
4283/// review` call this when no daemon is alive.
4284///
4285/// The caller holds the [`Queue::claim`] for the whole call, which is what
4286/// keeps a daemon that starts meanwhile from taking the task.
4287///
4288/// The one deliberate difference from the loop: a task the attempt leaves
4289/// runnable (failed with attempts to spare, or requeued) is **held** instead.
4290/// Nobody asked for a retry, and a daemon starting later must not spend agent
4291/// calls re-running a hand-started task behind the operator's back;
4292/// `magi task release` is the explicit retry.
4293pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
4294    let status = Arc::new(Mutex::new(Status::new()));
4295    let stop = Stop::new();
4296    // An attempt embeds startup and graph futures. Keep it off the standalone
4297    // caller's stack, on both the initial execution and withheld-text resume.
4298    Box::pin(attempt(
4299        opts,
4300        queue,
4301        &status,
4302        &stop,
4303        crate::graph::Pause::new(),
4304        task,
4305    ))
4306    .await;
4307    // A run parked on the owner's word about a withheld PR title/body has no
4308    // daemon to finish it. Nobody else will enforce `answer_timeout`, so wait
4309    // here with the claim still held, and resume once the question is settled
4310    // (answered, or abandoned at its deadline -> the neutral text).
4311    // A rejected reply files one more question (the gate asks at most twice),
4312    // so after a resume the run may be waiting again: keep going, with a fresh
4313    // limit for the new question. `resumes` bounds it even if a resume parks
4314    // without asking anything new.
4315    let mut resumes = 0;
4316    while resumes < MAX_WITHHELD_RESUMES {
4317        let Some(timeout) = withheld_text_wait(task) else {
4318            break;
4319        };
4320        eprintln!(
4321            "waiting for the owner's answer on a withheld pull request text \
4322             (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
4323        );
4324        // The deadline abandons the question itself; the extra margin only
4325        // covers an abandon that could not be saved.
4326        let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
4327        let ready = loop {
4328            match land_resume_state(task) {
4329                LandResume::StillWaiting if std::time::Instant::now() < limit => {
4330                    tokio::time::sleep(WITHHELD_POLL).await;
4331                }
4332                LandResume::Ready => break true,
4333                _ => break false,
4334            }
4335        };
4336        if !ready {
4337            break;
4338        }
4339        resumes += 1;
4340        Box::pin(attempt(
4341            opts,
4342            queue,
4343            &status,
4344            &stop,
4345            crate::graph::Pause::new(),
4346            task,
4347        ))
4348        .await;
4349    }
4350    hold_if_runnable(queue, task);
4351}
4352
4353/// Resumes an in-process run makes for withheld-text questions: the gate asks
4354/// at most twice, plus one for a resume that asks nothing new.
4355const MAX_WITHHELD_RESUMES: u32 = 3;
4356
4357/// How often an in-process run rechecks its withheld-text question.
4358const WITHHELD_POLL: Duration = Duration::from_secs(15);
4359
4360/// The `answer_timeout` (seconds) of the task's last run when that run is
4361/// parked on an unresolved withheld-text question; `None` otherwise.
4362fn withheld_text_wait(task: &Task) -> Option<u64> {
4363    let id = task.runs.last()?;
4364    let s = RunState::load(id).ok()?;
4365    (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
4366        .then_some(s.config.graph.answer_timeout)
4367}
4368
4369/// The quota losses `after` holds that `before` did not: what one execution
4370/// suffered, as opposed to the run's history.
4371///
4372/// Compared by value rather than by length or position because
4373/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
4374/// the vector can shrink and shift under a resume. A retried seat that hits
4375/// quota again is a `push` with a new `at`, so it shows up as new here.
4376/// `reclaim` deliberately keeps reading the whole history: after a crash there
4377/// is no attempt boundary to diff against.
4378fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
4379    after
4380        .iter()
4381        .filter(|q| !before.contains(q))
4382        .cloned()
4383        .collect()
4384}
4385
4386/// When the loop-wide quota cooldown should end, given this attempt's losses;
4387/// `None` when there were none. Reset-hint parsing and the cap live here.
4388fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
4389    if quota.is_empty() {
4390        return None;
4391    }
4392    let with_hint = quota.iter().find(|q| q.reset.is_some());
4393    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
4394    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
4395    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
4396    Some(
4397        now.checked_add(jiff::SignedDuration::from_secs(secs))
4398            .unwrap_or(Timestamp::MAX),
4399    )
4400}
4401
4402/// An explicit task count must agree with a run before any resume.
4403fn implementers_match(task: &Task, state: &RunState) -> bool {
4404    task.replacement.as_ref().map_or_else(
4405        || {
4406            task.implementers()
4407                .is_none_or(|n| n == state.config.graph.implementers)
4408        },
4409        |replacement| {
4410            state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
4411                && state.config.graph.implementers == 1
4412        },
4413    )
4414}
4415
4416/// Never resume or take over candidate work built for a different seat count.
4417fn starter_with_implementers(
4418    task: &Task,
4419    previous: Option<&RunState>,
4420    proposed: Starter,
4421) -> Starter {
4422    if previous.is_some_and(|s| !implementers_match(task, s)) {
4423        task.review_of
4424            .as_ref()
4425            .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
4426    } else {
4427        proposed
4428    }
4429}
4430
4431/// Apply this task's explicit count to the new attempt, without changing defaults.
4432fn apply_task_implementers(config: &mut Config, task: &Task) {
4433    if let Some(n) = task.implementers() {
4434        config.graph.implementers = n;
4435    }
4436}
4437
4438/// [`prepare`] for one task: its own `--config` and command-line overrides
4439/// (`Task::overrides`, filed by `magi run` / `magi review`) take precedence
4440/// over the loop's, so handing a hand-started task to a daemon changes nothing
4441/// about what it does.
4442#[cfg(test)]
4443fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
4444    let explicit = match &task.overrides {
4445        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
4446        _ => opts.config.as_deref(),
4447    };
4448    let (mut config, _) = Config::discover(repo, explicit)?;
4449    apply_options(&mut config, opts, task)?;
4450    Ok(config)
4451}
4452
4453fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
4454    if task
4455        .overrides
4456        .as_ref()
4457        .is_none_or(|o| o.inherit_daemon_options)
4458        && let Some(mode) = opts.merge.as_deref()
4459    {
4460        config.merge.mode = merge_mode(mode)?;
4461    }
4462    if let Some(o) = &task.overrides {
4463        o.apply(config);
4464    }
4465    Ok(())
4466}
4467
4468/// Load the config for a task's repository, with the merge override applied.
4469fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
4470    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
4471    if let Some(mode) = &opts.merge {
4472        config.merge.mode = merge_mode(mode)?;
4473    }
4474    Ok(config)
4475}
4476
4477/// Prune the shared build cache back under its cap at a safe boundary
4478/// between runs, so a queue that never empties - and so never reaches
4479/// [`poll`]'s fully-idle branch, where the ordinary [`janitor`] pass lives -
4480/// does not leave the cache to grow unchecked for as long as the backlog
4481/// lasts.
4482///
4483/// Called from [`poll`] only when `stop.busy_now()` is already `false`: the
4484/// same liveness fact the idle branch's own janitor call rests on - no run
4485/// this daemon spawned is still mid-compile - so pruning here races nothing.
4486/// The caller must not call this while a run is in flight; there is no
4487/// second `busy_now()` check inside this function, on purpose, because there
4488/// is nothing left to check that `busy_now()` has not already answered.
4489///
4490/// A stop that has already been asked for *is* checked here, for a different
4491/// reason. [`clean::prune_cache_if_over_limit`] walks the whole cache
4492/// synchronously before it decides anything, so the poll loop cannot get back
4493/// to its own `stopped()` test until that walk is over — and a loop already
4494/// on its way out must not make the operator wait out housekeeping it is
4495/// about to stop needing. This is the same call the idle branch makes when it
4496/// rechecks `stop.stopped()` after its wait before reaching [`janitor`], and
4497/// it matters more here: `busy_now()` is false throughout, so
4498/// [`Stop::finishing`] would report a stop as already landed while the walk
4499/// still held the loop. Nothing is lost by skipping — the cap is a standing
4500/// policy, and the next daemon's startup pass measures the same cache.
4501///
4502/// Rate-limited by [`CACHE_CHECK_INTERVAL_SECS`] rather than run on every
4503/// poll: a busy loop reaches this the instant one run's `InFlightGuard` drops
4504/// and the next has not yet claimed a task, which can be every few
4505/// milliseconds, and re-walking a multi-gigabyte cache that often would cost
4506/// more than the growth it is guarding against.
4507async fn maybe_prune_cache_between_runs(
4508    repo: &Path,
4509    opts: &Opts,
4510    home: &Path,
4511    stop: &Stop,
4512    last_checked: &mut Option<Timestamp>,
4513    now: Timestamp,
4514) {
4515    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
4516        return;
4517    }
4518    *last_checked = Some(now);
4519    let cfg = match prepare(repo, opts) {
4520        Ok(cfg) => cfg,
4521        Err(e) => {
4522            tracing::warn!("cache check: no config: {e:#}");
4523            return;
4524        }
4525    };
4526    match clean::prune_cache_if_over_limit(&cfg, home) {
4527        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
4528            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
4529            pruned.files,
4530            pruned.freed
4531        ),
4532        Ok(_) => {}
4533        Err(e) => {
4534            tracing::warn!("housekeep: prune cache: {e:#}");
4535            notices::raise_in(
4536                home,
4537                Notice::warn(
4538                    "housekeep:cache",
4539                    "Pruning the shared build cache failed; disk usage may keep growing.",
4540                ),
4541            );
4542        }
4543    }
4544}
4545
4546/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
4547/// now, given when it last did (if ever). Pure, so the cadence is asserted
4548/// directly rather than by waiting out real minutes in a test.
4549fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
4550    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
4551}
4552
4553/// The disk janitor, with its housekeeping logged rather than fatal.
4554///
4555/// Called only at the loop's idle points, for the reason the caller documents:
4556/// a prune racing a live compile would delete files mid-build. The config is
4557/// re-read on every call because the repository that just ran may not be the
4558/// daemon's own default, and the cache directory is a repository fact.
4559///
4560/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
4561/// and [`crate::run::default_worktree_root`] read here, for the same reason
4562/// [`drive`] takes its queue and status file rather than resolving them: a
4563/// test driving the loop must not reach through to the operator's real home
4564/// or worktree bay just because the janitor runs on every idle tick.
4565/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
4566/// to get wrong silently - a test's `home` was already isolated, but nothing
4567/// exercised the parameter next to it, so a real worktree bay stayed wired in
4568/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
4569/// it for real, every test in this file that drives the loop at all started
4570/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
4571async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
4572    let cfg = match prepare(repo, opts) {
4573        Ok(cfg) => cfg,
4574        Err(e) => {
4575            tracing::warn!("housekeep: no config: {e:#}");
4576            return;
4577        }
4578    };
4579    // A run's own worktree lives under `config.graph.worktree_root` when the
4580    // repository sets one - the same precedence `RunState::worktree_root`
4581    // uses - and `worktrees_root` only stands in for the *default* an
4582    // unconfigured repository resolves to (see this function's own
4583    // parameter, or the test fixture wiring one to a fake path). Housekeeping
4584    // that always swept the default regardless of this override would never
4585    // see, and so never reclaim, a single worktree for a repository that
4586    // relocated them elsewhere.
4587    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
4588    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
4589    // Reported whenever there is anything to say, not only when `folded > 0`:
4590    // the incident this exists to prevent was 90 of 93 runs skipped and 0
4591    // folded, on every single pass, for months - a report gated on `folded`
4592    // would have stayed silent through every one of them.
4593    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
4594        let mut extra = Vec::new();
4595        if out.unreadable > 0 {
4596            extra.push(format!("{} unreadable", out.unreadable));
4597        }
4598        if out.orphaned_worktrees > 0 {
4599            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
4600        }
4601        let detail = if extra.is_empty() {
4602            String::new()
4603        } else {
4604            format!(" ({})", extra.join(", "))
4605        };
4606        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
4607    }
4608    if out.external_merges_recorded > 0 {
4609        tracing::info!(
4610            "housekeep: recorded {} run(s) as merged externally",
4611            out.external_merges_recorded
4612        );
4613    }
4614    if out.stale_pr_states_repaired > 0 {
4615        tracing::info!(
4616            "housekeep: rewrote {} run record(s) whose pull request had already settled",
4617            out.stale_pr_states_repaired
4618        );
4619    }
4620    if out.cache_files > 0 {
4621        tracing::info!(
4622            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
4623            out.cache_files,
4624            out.cache_freed
4625        );
4626    }
4627    if out.questions_abandoned > 0 {
4628        tracing::info!(
4629            "housekeep: abandoned {} question(s) left open by a finished run",
4630            out.questions_abandoned
4631        );
4632    }
4633}
4634
4635/// Run [`triage::run_once`] and log whatever it did, the same "only when
4636/// there is something to say" rule [`janitor`] follows for its own report.
4637///
4638/// Called at the same idle points as [`janitor`] - once per full poll
4639/// interval, never mid-attempt - for the same reason: it is not liveness
4640/// critical, and a task's own `hold_reason` string is the one thing this
4641/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
4642/// tick for no benefit.
4643async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
4644    let questions = Questions::at(home.join("questions"));
4645    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
4646    if report.is_empty() {
4647        return;
4648    }
4649    if !report.quarantined.is_empty() {
4650        tracing::info!(
4651            "triage: held {} blocked task(s) whose blocked-on task or \
4652             question no longer exists: {}",
4653            report.quarantined.len(),
4654            report.quarantined.join(", ")
4655        );
4656    }
4657    if !report.resumed.is_empty() {
4658        tracing::info!(
4659            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
4660            report.resumed.len(),
4661            report.resumed.join(", ")
4662        );
4663    }
4664    if !report.asked.is_empty() {
4665        tracing::info!(
4666            "triage: asked about {} held task(s): {}",
4667            report.asked.len(),
4668            report.asked.join(", ")
4669        );
4670    }
4671    if !report.answered.is_empty() {
4672        tracing::info!(
4673            "triage: applied {} operator answer(s): {}",
4674            report.answered.len(),
4675            report.answered.join(", ")
4676        );
4677    }
4678}
4679
4680/// The free-space gate: what stands between this task and a new run, if
4681/// anything. `Some(reason)` holds the task; `None` lets it start.
4682///
4683/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
4684/// the operator opted out. A measurement failure is a gate, not a pass: both
4685/// sides of "cannot tell" are served by not starting.
4686pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
4687    disk_gate_with(repo, config, crate::disk::free_bytes)
4688}
4689
4690/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
4691/// test can assert the exact wiring `attempt` runs - config's threshold in,
4692/// task-holding reason out - without asking the real machine's disk anything.
4693fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
4694    repo: &Path,
4695    config: &Config,
4696    free_bytes: F,
4697) -> Option<String> {
4698    let min = config.disk.min_free_bytes;
4699    if min == 0 {
4700        return None;
4701    }
4702    let mut paths = vec![repo.to_owned()];
4703    if let Some(cache) = config.cache_dir() {
4704        paths.push(cache);
4705    }
4706    if let Some(root) = &config.graph.worktree_root {
4707        paths.push(root.clone());
4708    }
4709    for path in paths {
4710        let probe = if path == repo {
4711            path.as_path()
4712        } else {
4713            path.ancestors().find(|p| p.exists()).unwrap_or(&path)
4714        };
4715        let reason = match free_bytes(probe) {
4716            Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
4717            Err(e) => Some(crate::disk::unmeasured_in(
4718                probe,
4719                &e,
4720                &config.graph.language,
4721            )),
4722        };
4723        if reason.is_some() {
4724            return reason;
4725        }
4726    }
4727    None
4728}
4729
4730/// How long to wait before offering another task when a run lost a seat to a
4731/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
4732/// could read, or carried nothing at all. Long enough that a quota outage
4733/// cannot burn through a whole backlog in the few seconds each doomed attempt
4734/// takes to fail; short enough that a quota which clears early is not left
4735/// idle for the fallback's sake.
4736const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
4737
4738/// Longest a parsed reset hint may push the wait out to. The hint comes from
4739/// the CLI's own words, not a contract, so a parsing slip that lands a day
4740/// away must not leave the loop asleep for a day.
4741const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
4742
4743/// How long [`poll`] should wait before offering the next task, after a run
4744/// lost at least one seat to a rate limit.
4745///
4746/// Pure and separate from the loop so the policy can be exercised without a
4747/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
4748/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
4749/// nothing to parse, or the parsed time has already passed; `cap` bounds how
4750/// far a parsed hint is trusted to push the wait out.
4751fn quota_wait(
4752    reset_at: Option<Timestamp>,
4753    now: Timestamp,
4754    fallback: Duration,
4755    cap: Duration,
4756) -> Duration {
4757    match reset_at {
4758        Some(at) if at > now => {
4759            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
4760            Duration::from_secs(secs).min(cap)
4761        }
4762        _ => fallback,
4763    }
4764}
4765
4766/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
4767///
4768/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
4769/// explains why parsing it exactly "would be a bug factory" — so this only
4770/// recognises the shapes actually observed in the wild, and returns `None`
4771/// for anything else rather than guess at a format nobody has seen.
4772///
4773/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
4774/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
4775/// said it, not from whenever this loop happens to read it: anchoring on `now`
4776/// would push the reset later on every read and would read an already-elapsed
4777/// reset as still in the future. (A long hint is still clamped by
4778/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
4779fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
4780    parse_reset_hint_zoned(text, now)
4781        .or_else(|| parse_reset_hint_dated(text))
4782        .or_else(|| parse_reset_hint_relative(text, recorded))
4783}
4784
4785/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
4786/// optional but at least one required, in that order. A bare number or any
4787/// unknown unit is refused.
4788fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
4789    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
4790    let mut rest = rest.trim();
4791    if rest.is_empty() {
4792        return None;
4793    }
4794    let mut total: i64 = 0;
4795    let mut matched = false;
4796    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
4797        if let Some((digits, tail)) = rest.split_once(unit)
4798            && !digits.is_empty()
4799            && digits.bytes().all(|b| b.is_ascii_digit())
4800        {
4801            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
4802            rest = tail;
4803            matched = true;
4804        }
4805    }
4806    if !rest.is_empty() || !matched {
4807        return None;
4808    }
4809    recorded
4810        .checked_add(jiff::SignedDuration::from_secs(total))
4811        .ok()
4812}
4813
4814/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
4815/// case-insensitive) into a 24-hour hour and minute. Shared by every
4816/// reset-hint shape below.
4817fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
4818    let clock = clock.trim().to_lowercase();
4819    let (digits, pm) = clock
4820        .strip_suffix("am")
4821        .map(|d| (d, false))
4822        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
4823    let (h, m) = digits.trim().split_once(':')?;
4824    let mut hour: i8 = h.trim().parse().ok()?;
4825    let minute: i8 = m.trim().parse().ok()?;
4826    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
4827        return None;
4828    }
4829    if pm && hour != 12 {
4830        hour += 12;
4831    } else if !pm && hour == 12 {
4832        hour = 0;
4833    }
4834    Some((hour, minute))
4835}
4836
4837/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
4838/// and a zone, never a date. A clock reading already past today is read as
4839/// tomorrow's: a CLI naming a same-day reset that has already gone by means
4840/// the window rolled over while nothing was watching.
4841fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
4842    let open = text.find('(')?;
4843    let close = text.rfind(')')?;
4844    if close <= open {
4845        return None;
4846    }
4847    let zone = text[open + 1..close].trim();
4848    let (hour, minute) = parse_12h_clock(&text[..open])?;
4849    let tz = jiff::tz::TimeZone::get(zone).ok()?;
4850    let candidate = now
4851        .to_zoned(tz)
4852        .with()
4853        .hour(hour)
4854        .minute(minute)
4855        .second(0)
4856        .millisecond(0)
4857        .microsecond(0)
4858        .nanosecond(0)
4859        .build()
4860        .ok()?;
4861    let mut at = candidate.timestamp();
4862    if at <= now {
4863        at += jiff::SignedDuration::from_hours(24);
4864    }
4865    Some(at)
4866}
4867
4868/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
4869/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
4870/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
4871/// "already past today" correction to make: the year already disambiguates
4872/// it. Scanned as a five-word window so it can be pulled out of the middle
4873/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
4874/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
4875/// any other timestamp with no zone attached.
4876fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
4877    let words: Vec<&str> = text.split_whitespace().collect();
4878    if words.len() < 5 {
4879        return None;
4880    }
4881    (0..=words.len() - 5)
4882        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
4883}
4884
4885/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
4886/// parenthesis right after the window is refused rather than ignored — it
4887/// reads as an explicit zone annotation on a shape that otherwise carries
4888/// none, and guessing UTC anyway would be exactly the silent misread this
4889/// module's parsing otherwise avoids.
4890fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
4891    if trailing.is_some_and(|next| next.starts_with('(')) {
4892        return None;
4893    }
4894    let month = month_number(window[0])?;
4895    let day_token = window[1].strip_suffix(',')?.to_lowercase();
4896    let day_digits = ["st", "nd", "rd", "th"]
4897        .iter()
4898        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
4899    let day: i8 = day_digits.parse().ok()?;
4900    let year_token = window[2];
4901    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
4902        return None;
4903    }
4904    let year: i16 = year_token.parse().ok()?;
4905    // The am/pm word carries the sentence's own trailing punctuation, e.g.
4906    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
4907    // reusing the same 12-hour clock reader the bracketed shape uses.
4908    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
4909    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
4910    let date = jiff::civil::Date::new(year, month, day).ok()?;
4911    let candidate = date
4912        .at(hour, minute, 0, 0)
4913        .to_zoned(jiff::tz::TimeZone::UTC)
4914        .ok()?;
4915    Some(candidate.timestamp())
4916}
4917
4918/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
4919/// case-insensitively, into a 1-based month number.
4920fn month_number(name: &str) -> Option<i8> {
4921    const NAMES: [&str; 12] = [
4922        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
4923    ];
4924    let lower = name.to_lowercase();
4925    NAMES
4926        .iter()
4927        .position(|n| *n == lower.as_str())
4928        .map(|i| i as i8 + 1)
4929}
4930
4931/// Resuming a `Blocked` run that already spent every review round its own
4932/// config allowed cannot make progress: `graph::Runner`'s review loop walks
4933/// `(reviews.len()+1)..=max_rounds`, which is empty once `reviews.len()` has
4934/// reached `max_rounds`, so `execute` would settle straight back to
4935/// `Blocked` without asking anyone anything. Read-only against a state this
4936/// build never mutates — `src/graph.rs` stays untouched — but without this
4937/// check, [`unfinished_run`] would keep reporting such a run as still
4938/// "unfinished", and `crate::conduct::Recovery::Requeue` (whose whole
4939/// promise is a fresh competition when a design needs to change) would
4940/// silently resume the exhausted run instead, spending an attempt on a
4941/// cycle that cannot change anything.
4942fn exhausted_review_budget(state: &RunState) -> bool {
4943    // A run whose task-head publication failed has nothing left to review:
4944    // resuming it only retries the publication, so it is never "exhausted".
4945    state.status == RunStatus::Blocked
4946        && !state.pr_publication_pending
4947        && state.reviews.len() >= state.config.graph.review_rounds
4948}
4949
4950/// This task's *most recent* run, if resuming it would actually make
4951/// progress. `short` is only for the warning's own message.
4952///
4953/// Only ever `runs.last()` — never a search back through older history.
4954/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
4955/// mint, oldest first, and every entry before the last one was already
4956/// superseded at the moment it was minted: the daemon only ever starts a new
4957/// run when the previous one was not worth resuming (unresumable, exhausted,
4958/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
4959/// opens a fresh review-only run alongside an older, already-failed
4960/// competition. Searching further back would let an old run that merely
4961/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
4962/// behind, say — get resumed instead of the fresh competition
4963/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
4964/// nothing asked to revisit.
4965///
4966/// Two runs paid for the "prefer resuming over restarting" half of this
4967/// lesson, which is why this still checks `runs.last()` rather than always
4968/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
4969/// task a moment later, duplicating two and a half hours of agent work. Then
4970/// b25f stalled on a judge that timed out and one that answered with no JSON
4971/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
4972/// **one second** later, buying three fresh implementations to reach the
4973/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
4974/// the second case: a stall is terminal, and its cheap recovery re-asks only
4975/// the absent seats. [`exhausted_review_budget`] is the other half: a run
4976/// that is technically `resumable()` but provably cannot progress must not
4977/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
4978/// no-op instead of the fresh competition it promises.
4979///
4980/// A load failure is warned about rather than silently read as "not
4981/// resumable": the alternative is exactly what let a schema mismatch on run
4982/// `eba2` fall through to a full re-competition with nobody told why.
4983/// `crate::conduct` is what actually offers a better answer than
4984/// `Runner::start` here (see `Recovery::Review`), once this task's next
4985/// failure shows it up as `held`/`failed` with the run state unreadable.
4986fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
4987    unfinished_run_with(runs, short, RunState::load)
4988}
4989
4990/// [`unfinished_run`] with an injected state reader. Tests provide their
4991/// fixtures directly rather than touching the process-global run home.
4992pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
4993where
4994    F: FnMut(&str) -> Result<RunState>,
4995{
4996    let mut id = runs.last()?.clone();
4997    let mut visited = std::collections::BTreeSet::new();
4998    let mut repo = None;
4999    loop {
5000        if !runs.contains(&id) || !visited.insert(id.clone()) {
5001            tracing::warn!("invalid or cyclic recovery authority for task {short}");
5002            return None;
5003        }
5004        let state = match load(&id) {
5005            Ok(state) if state.id == id => state,
5006            Ok(_) => return None,
5007            Err(e) => {
5008                tracing::warn!("could not read run {id} for task {short}: {e:#}");
5009                return None;
5010            }
5011        };
5012        if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
5013            return None;
5014        }
5015        repo = Some(state.repo.clone());
5016        if let Some(authority) = state.retired_to {
5017            id = authority;
5018            continue;
5019        }
5020        return (state.status.resumable()
5021            && !state.released()
5022            && !exhausted_review_budget(&state)
5023            && state.liveness(false) != crate::run::Liveness::Live)
5024            .then_some(id);
5025    }
5026}
5027
5028/// Is `task` a parked (or, from an older build, failed) task whose last run was parked at a node boundary, so
5029/// that [`attempt`] will resume it on its own?
5030///
5031/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
5032/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
5033/// injected reader like its sibling. An unreadable run is not awaiting
5034/// anything: it keeps going to the conductor as before.
5035fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
5036where
5037    F: FnOnce(&str) -> Result<RunState>,
5038{
5039    // `Failed` stays: a record an older build wrote for a parked run.
5040    if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
5041        || task.fresh_start
5042        || task.review_branch.is_some()
5043    {
5044        return false;
5045    }
5046    let Some(id) = task.runs.last() else {
5047        return false;
5048    };
5049    load(id).is_ok_and(|s| {
5050        s.parked
5051            && s.status.resumable()
5052            && !s.released()
5053            && s.retired_to.is_none()
5054            && !exhausted_review_budget(&s)
5055    })
5056}
5057
5058/// Which of the three ways [`attempt`] can mint or continue a run this task
5059/// should use.
5060#[derive(Debug, Clone, PartialEq, Eq)]
5061enum Starter {
5062    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
5063    /// and that still exists.
5064    Review(String),
5065    /// `crate::graph::Runner::resume` on an unfinished run of this task.
5066    Resume(String),
5067    /// `crate::graph::Runner::start`: a fresh competition.
5068    Start,
5069}
5070
5071/// A second bound independent of inputs and the resettable failure counter.
5072/// Count recovery records, not history entries: resuming appends the same id.
5073/// Unknown history is not evidence that a new set of worktrees is affordable.
5074fn retained_attempt_hold(
5075    task: &Task,
5076    starter: &Starter,
5077    limit: usize,
5078    mut load: impl FnMut(&str) -> Result<RunState>,
5079) -> Option<String> {
5080    if limit == 0 || matches!(starter, Starter::Resume(_)) {
5081        return None;
5082    }
5083    let mut retained = 0;
5084    for id in task.runs.iter().collect::<std::collections::BTreeSet<_>>() {
5085        let state = match load(id) {
5086            Ok(state) if state.id == *id => state,
5087            _ => {
5088                return Some(format!(
5089                    "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
5090                ));
5091            }
5092        };
5093        if state.retired_to.is_some() || state.released() {
5094            continue;
5095        }
5096        // Neither a completed status nor an empty candidate array proves that
5097        // all recovery sources (including unrecorded preparation) were retired.
5098        retained += 1;
5099    }
5100    (retained >= limit).then(|| format!(
5101        "[recovery-backlog] {retained} unretired attempts reach the limit of {limit}. Resume an existing recovery owner or inspect the lineage and retire proved-obsolete attempts before creating another run. Releases, refunds and changed upstream inputs do not reset this limit. No source or historical report was removed."
5102    ))
5103}
5104
5105/// A selected public implementation overrides every historical candidate and pin.
5106fn selected_starter(
5107    selected: &crate::pr_recovery::Selection,
5108    previous: Option<&RunState>,
5109    unfinished: Option<&str>,
5110) -> Starter {
5111    if let Some(id) = unfinished
5112        && previous.is_some_and(|r| {
5113            r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
5114        })
5115    {
5116        Starter::Resume(id.to_owned())
5117    } else {
5118        Starter::Review(selected.branch.clone())
5119    }
5120}
5121
5122/// The owner's answer to this branch's divergence question, consumed from the
5123/// task so a later, different divergence asks again. The runner applies it
5124/// (see `Runner::review_taking_over`), after the earlier worktree is released.
5125fn take_divergence_answer(
5126    branch: &str,
5127    remote: &str,
5128    task: &mut Task,
5129) -> Option<crate::reconcile::Choice> {
5130    let summary = crate::reconcile::summary_for(branch, remote);
5131    let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
5132        (a.question == summary)
5133            .then(|| crate::reconcile::Choice::from_answer(&a.answer))
5134            .flatten()
5135            .map(|c| (i, c))
5136    })?;
5137    task.answers.remove(idx);
5138    Some(choice)
5139}
5140
5141/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
5142/// this attempt should use. Pure, and separate from [`attempt`], so the
5143/// routing itself is assertable without spawning a real graph or a git
5144/// process: `attempt`'s own `crate::git::branch_exists` call has already
5145/// happened by the time this is called.
5146///
5147/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
5148/// whose branch is gone falls all the way through to [`Starter::Start`], not
5149/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
5150/// old (likely `Blocked`) run in the first place, and a branch that vanished
5151/// out from under that choice is not evidence resuming it would fare better.
5152fn choose_starter(
5153    review_branch: Option<&str>,
5154    branch_exists: bool,
5155    unfinished: Option<&str>,
5156) -> Starter {
5157    match review_branch {
5158        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
5159        Some(_) => Starter::Start,
5160        None => match unfinished {
5161            Some(id) => Starter::Resume(id.to_owned()),
5162            None => Starter::Start,
5163        },
5164    }
5165}
5166
5167/// Consume a retained review only while its authored criteria still match.
5168fn take_review_branch(task: &mut Task, previous: Option<&RunState>) -> Option<String> {
5169    let branch = task.review_branch.take();
5170    let instruction = task.review_instruction.take();
5171    branch.filter(|branch| match &instruction {
5172        Some(authored) => *authored == task.instruction,
5173        // Legacy retained branches must agree with their prior run; only an
5174        // explicitly pinned review can proceed without recoverable provenance.
5175        None => previous.map_or_else(
5176            || task.review_of.as_ref() == Some(branch),
5177            |run| compatible_run_instruction(run, task),
5178        ),
5179    })
5180}
5181
5182/// A current explicit pin can select an otherwise incompatible run. Edits
5183/// and subsequent approvals invalidate pins selected for earlier criteria.
5184fn may_resume_run(run: &RunState, task: &Task) -> bool {
5185    task.resume_override
5186        .as_ref()
5187        .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
5188        || compatible_run_instruction(run, task)
5189}
5190
5191/// Review scaffolding is execution context, not evidence of an operator edit.
5192pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
5193    if let Some(authored) = &run.task_instruction {
5194        return compatible_instruction(authored, task);
5195    }
5196    if compatible_instruction(&run.instruction, task) {
5197        return true;
5198    }
5199    // Recognize only the existing generated review shapes on legacy runs.
5200    // Ordinary authored text with a similar heading is left intact.
5201    if run.reviewed_commits.is_some() {
5202        if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
5203            return strip_answers_block(authored, task).trim() == task.instruction.trim();
5204        }
5205        if let Some(branch) = &task.review_of {
5206            let canonical = format!(
5207                "Review the branch `{branch}` (review-only: no implementation, no judging)."
5208            );
5209            let generated = format!(
5210                "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"
5211            );
5212            return task.instruction == canonical && run.instruction.starts_with(&generated);
5213        }
5214    }
5215    false
5216}
5217
5218/// Compare authored instructions, excluding answer blocks appended by the daemon.
5219pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
5220    strip_answers_block(old, task) == task.instruction
5221}
5222
5223/// Which repository a task runs in. A task that names none — the normal case
5224/// for one filed from a phone — runs in the daemon's own default.
5225fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
5226    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
5227        return fallback.to_path_buf();
5228    }
5229    task.repo.clone()
5230}
5231
5232/// The header [`append_answers`] appends operator answers under. Shared with
5233/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
5234/// rather than grown a new block on every resume.
5235const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
5236
5237/// Render the first `count` answers in the block appended to an instruction.
5238fn answers_block(task: &Task, count: usize) -> String {
5239    let mut s = ANSWERS_HEADER.to_owned();
5240    for a in &task.answers[..count] {
5241        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
5242    }
5243    s
5244}
5245
5246/// Render the approval independently of transient task state, so historical
5247/// suffixes remain recognizable after another explicit release.
5248fn resumption_block(r: &crate::queue::Resumption) -> String {
5249    format!(
5250        "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
5251         Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
5252        r.generation, r.at, r.instruction, r.answers_through,
5253    )
5254}
5255
5256/// Append audit answers and the latest explicit approval to the instruction.
5257fn append_answers(base: &str, task: &Task) -> String {
5258    let mut s = base.to_owned();
5259    if !task.answers.is_empty() {
5260        s.push_str(&answers_block(task, task.answers.len()));
5261    }
5262    if let Some(r) = &task.resumption {
5263        s.push_str(&resumption_block(r));
5264    }
5265    s
5266}
5267
5268/// Drop the prior answer block only when it is exactly the suffix this task
5269/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
5270/// the task author is ordinary instruction text, not a block to remove.
5271fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
5272    let mut instruction = instruction;
5273    for approval in task
5274        .resumption
5275        .iter()
5276        .chain(task.resumption_history.iter().rev())
5277    {
5278        if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
5279            instruction = base;
5280            break;
5281        }
5282    }
5283    for count in (1..=task.answers.len()).rev() {
5284        let block = answers_block(task, count);
5285        if let Some(base) = instruction.strip_suffix(&block) {
5286            return base;
5287        }
5288    }
5289    instruction
5290}
5291
5292/// The instruction handed to `Runner::start`: the task's own text, plus any
5293/// operator answers `crate::conduct` collected for it (see
5294/// [`Task::answers`]), so a decision the operator actually made reaches the
5295/// implementers rather than only clearing the block that was waiting on it.
5296///
5297/// Appended rather than merged into [`Task::instruction`] itself, so the
5298/// task's own record stays exactly what its author wrote.
5299fn instruction_for(task: &Task) -> String {
5300    append_answers(&task.instruction, task)
5301}
5302
5303/// The instruction a resumed run should carry on with: whatever it already
5304/// had, refreshed with the task's *current* operator answers.
5305///
5306/// A resumable run's own `RunState::instruction` predates any answer
5307/// `crate::conduct` collects after the run parks, so resuming it unchanged —
5308/// the behaviour before this function existed — silently drops the very
5309/// decision the operator made to unblock it. Re-stripping any block this
5310/// function appended on an earlier resume before re-appending the current
5311/// list (rather than blindly appending again) is what keeps a task resumed
5312/// three times over three answered questions from carrying the same answer
5313/// three times.
5314fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
5315    append_answers(strip_answers_block(old_instruction, task), task)
5316}
5317
5318/// Preserve the producer's verified boundary and target, independent of prose.
5319fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
5320    let failure = error.downcast_ref::<crate::config::ConfigFailure>();
5321    task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
5322    if let Some(cause) = task.hold_notice_cause.as_mut() {
5323        cause.target = failure.map(|f| f.target.clone());
5324    }
5325}
5326
5327#[derive(Debug, thiserror::Error)]
5328#[error("attachment `{name}` is recorded on the task but {path} is missing")]
5329struct MissingAttachment {
5330    name: String,
5331    path: PathBuf,
5332}
5333
5334/// The task's attachments as absolute paths, each checked to still exist.
5335fn task_attachments(
5336    queue: &Queue,
5337    task: &Task,
5338) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
5339    let paths = queue.attachment_paths(task);
5340    for (name, path) in task.attachments.iter().zip(&paths) {
5341        if !path.is_file() {
5342            return Err(MissingAttachment {
5343                name: name.clone(),
5344                path: path.clone(),
5345            });
5346        }
5347    }
5348    Ok(paths)
5349}
5350
5351/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
5352/// answers before handing it to `Runner` — the actual boundary between
5353/// [`choose_starter`]'s routing and the graph, factored out so it is
5354/// assertable without a real repository, git branch, or agent CLI.
5355///
5356/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
5357/// instruction from the reviewed branch's own commit log because there is no
5358/// task statement to speak of for hand-written work, and splicing operator
5359/// answers into that text would contradict the very message it sends
5360/// reviewers ("there is no task statement").
5361fn prepare_instruction(
5362    starter: &Starter,
5363    old_instruction: Option<&str>,
5364    task: &Task,
5365) -> Option<String> {
5366    match starter {
5367        Starter::Start => Some(instruction_for(task)),
5368        Starter::Resume(_) => Some(resumed_instruction(
5369            old_instruction.expect("a resumed run always has a prior instruction"),
5370            task,
5371        )),
5372        Starter::Review(_) => None,
5373    }
5374}
5375
5376/// Persist a transition. A queue write failure is logged rather than fatal: the
5377/// run already happened, and taking the daemon down would only add a lost
5378/// backlog to a full disk.
5379fn record(queue: &Queue, task: &mut Task) {
5380    if let Err(e) = queue.put(task) {
5381        tracing::error!("could not record task {}: {e:#}", task.short());
5382        let notice = Notice::error(
5383            "loop:record",
5384            "The loop could not save a task's state; check the disk.",
5385        )
5386        .link(Link::Task {
5387            id: task.id.clone(),
5388        });
5389        // The queue lives at `<home>/queue`, so its parent is the home.
5390        match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
5391            Some(home) => notices::raise_in(home, notice),
5392            None => notices::raise(notice),
5393        }
5394    }
5395}
5396
5397/// Every runnable task, in the order the loop should try them.
5398///
5399/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
5400/// tail exists so that a claim somebody else holds costs the loop the next
5401/// candidate rather than a whole poll interval of idleness.
5402fn runnable(queue: &Queue) -> Vec<Task> {
5403    let mut tasks: Vec<Task> = queue
5404        .list()
5405        .into_iter()
5406        .filter(|t| t.status.runnable())
5407        .collect();
5408    tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
5409    tasks
5410}
5411
5412/// Why a run ended where it did, in one line, for [`Task::last_error`].
5413///
5414/// A stalled run names the seats the quota took out: "out of quota" is not
5415/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
5416/// agent to replace or which plan to top up.
5417///
5418/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
5419/// purpose: unlike `label`'s other callers (an internal log line, an
5420/// already-a-bug fallback message), this string becomes `Task::last_error`
5421/// verbatim, which the phone renders in the same alarm-styled box an
5422/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
5423/// `.err` styling. A bare `verified_noop` there would read exactly like the
5424/// failure this whole feature exists to tell apart from one.
5425fn describe(state: &RunState) -> String {
5426    let p = phrases(&state.config.graph.language);
5427    let mut detail = if state.status == RunStatus::Stalled {
5428        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
5429        seats.sort_unstable();
5430        seats.dedup();
5431        if seats.is_empty() {
5432            p.quorum_lost.to_owned()
5433        } else {
5434            format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
5435        }
5436    } else {
5437        format!("{}{}", p.run_ended, state.status.display_label())
5438    };
5439    if let Some(last) = state.events.last() {
5440        // The review loop's "never answered" stop is the one event worth
5441        // translating; it is recognised from structured state, not by
5442        // matching the English event text (which stays as recorded).
5443        let unanswered = state
5444            .reviews
5445            .last()
5446            .filter(|r| {
5447                state.status == RunStatus::Blocked
5448                    && last.node == "review"
5449                    && r.incomplete()
5450                    && r.blocking == 0
5451                    && r.round == state.config.graph.review_rounds
5452                    && r.e2e.iter().all(crate::run::CommandOutcome::ok)
5453            })
5454            .map(|r| (r.expected - r.answered, r.round));
5455        match unanswered {
5456            Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
5457                detail.push_str(&format!(
5458                    " ({}: {})",
5459                    last.node,
5460                    (p.reviewers_never_answered)(missing, rounds)
5461                ));
5462            }
5463            _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
5464        }
5465    }
5466    detail.push_str(&format!(" [run {}]", state.id));
5467    detail
5468}
5469
5470/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
5471///
5472/// The task file lives in the backlog indefinitely; a diagnostic is an
5473/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
5474/// stay small regardless of how much a gate command or a candidate printed.
5475const DIAGNOSTIC_MAX: usize = 4_000;
5476
5477/// Tail kept from a single failing command's output inside a diagnostic.
5478/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
5479/// pointer for a human deciding whether to go read the full artifact by hand,
5480/// not a replacement for reading it.
5481const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
5482
5483/// Assemble a bounded diagnostic excerpt from a held task's own run, so
5484/// `magi task show` says more than the one-line reason in [`describe`].
5485///
5486/// The one-liner answers "where did the run stop"; this answers "what would a
5487/// human have found opening `artifacts/` by hand" — the point of the whole
5488/// feature is the case that one-liner actively misleads on: a run held as "no
5489/// candidate produced a change" can mean the implementer actually finished
5490/// the task (opened a PR, merged it, tagged a release) and only left a clean
5491/// local worktree behind, which reads as "nothing happened" unless someone
5492/// goes and reads what the agent actually said. `None` when the run carries
5493/// none of the three shapes this recognises — an ordinary run held for
5494/// something not diagnosable from `RunState` alone still explains itself
5495/// through `Task::last_error`.
5496fn diagnostic(state: &RunState) -> Option<String> {
5497    let mut parts: Vec<String> = Vec::new();
5498
5499    // Gate failure: which check(s), and the tail of what each printed.
5500    for o in state.gate.iter().filter(|o| !o.ok()) {
5501        parts.push(format!(
5502            "gate `{}` failed ({}):\n{}",
5503            o.command,
5504            notices::exit_status(o.code),
5505            crate::run::tail(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
5506        ));
5507    }
5508
5509    // The land loop gave up because the fixer declined while checks were
5510    // still red: the message already names them (see `land::run`).
5511    if let Some(last) = state
5512        .events
5513        .iter()
5514        .rev()
5515        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
5516    {
5517        parts.push(last.message.clone());
5518    }
5519
5520    // No viable candidate: every implementer's own final word, sanitized the
5521    // same way a judge would have read it, so a run that actually finished
5522    // the job does not read as an unexplained failure. A verified no-op is
5523    // called out ahead of its own summary and apart from an ordinary
5524    // failure's `why` — this is the one candidate shape whose diagnostic a
5525    // human is expected to actually judge, not just skim.
5526    if state.viable().is_empty() {
5527        for c in &state.candidates {
5528            if let Some(evidence) = &c.verified_noop {
5529                parts.push(format!(
5530                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
5531                    c.label
5532                ));
5533            } else if !c.summary.trim().is_empty() {
5534                parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
5535            } else if let Some(why) = &c.failed {
5536                parts.push(format!("candidate {}: {why}", c.label));
5537            }
5538        }
5539    }
5540
5541    if parts.is_empty() {
5542        return None;
5543    }
5544    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
5545    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
5546    // back slightly over. Leave it enough room to always land under the
5547    // limit.
5548    Some(crate::run::tail(
5549        &parts.join("\n\n"),
5550        DIAGNOSTIC_MAX.saturating_sub(100),
5551    ))
5552}
5553
5554/// Stable lower-case name for a run status, for an internal log line and the
5555/// "graph stopped without reaching a terminal status" bug message in
5556/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
5557/// doc for why that one reads [`RunStatus::display_label`] instead. One
5558/// definition of a status's name, on the type that owns it: this table used
5559/// to live here as a second copy, and a status renamed in one place would
5560/// have gone on reading correctly in the other.
5561fn label(status: RunStatus) -> &'static str {
5562    status.as_str()
5563}
5564
5565/// Parse a merge mode override.
5566pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
5567    match mode {
5568        "none" => Ok(MergeMode::None),
5569        "local" => Ok(MergeMode::Local),
5570        "pr" => Ok(MergeMode::Pr),
5571        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
5572    }
5573}
5574
5575/// Take the status lock, recovering from a poisoned one.
5576///
5577/// A panic elsewhere must not silently stop the heartbeat: the status is plain
5578/// data, and the worst a poisoned lock can hold is a stale timestamp.
5579fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
5580    mutex
5581        .lock()
5582        .unwrap_or_else(std::sync::PoisonError::into_inner)
5583}
5584
5585#[cfg(test)]
5586mod tests {
5587    use super::*;
5588    use crate::queue::{Source, TaskStatus};
5589    use crate::run::{Candidate, CommandOutcome};
5590    use pretty_assertions::assert_eq;
5591
5592    fn task() -> Task {
5593        Task::new(
5594            "add retries".to_owned(),
5595            "add retries".to_owned(),
5596            PathBuf::from("/repo"),
5597            Source::Human,
5598        )
5599    }
5600
5601    #[test]
5602    fn selected_public_head_overrides_historical_resume_and_pin() {
5603        let mut t = task();
5604        let mut old = run_state(RunStatus::Blocked);
5605        let selection = crate::pr_recovery::Selection {
5606            url: "url".into(),
5607            branch: format!("magi/task-{}", t.id),
5608            head: "a".repeat(40),
5609            source_head: None,
5610            source_run: None,
5611            source_proof: None,
5612            disposition: Some(crate::pr_recovery::Disposition::Review),
5613            instruction: t.instruction.clone(),
5614            approved_at: Timestamp::now(),
5615        };
5616        t.resume_override = Some(crate::queue::OperatorResume {
5617            pinned_run: Some(old.id.clone()),
5618            question_id: "choice".into(),
5619            at: Timestamp::now(),
5620            conductor_rehold: None,
5621            forced: false,
5622        });
5623        assert_eq!(
5624            selected_starter(&selection, Some(&old), Some(&old.id)),
5625            Starter::Review(selection.branch.clone())
5626        );
5627        old.pr_recovery = Some(selection.clone());
5628        assert_eq!(
5629            selected_starter(&selection, Some(&old), Some(&old.id)),
5630            Starter::Review(selection.branch.clone())
5631        );
5632        old.reviewed_commits = Some(vec!["implementation".into()]);
5633        assert_eq!(
5634            selected_starter(&selection, Some(&old), Some(&old.id)),
5635            Starter::Resume(old.id.clone())
5636        );
5637        let mut changed = selection.clone();
5638        changed.head = "b".repeat(40);
5639        assert_eq!(
5640            selected_starter(&changed, Some(&old), Some(&old.id)),
5641            Starter::Review(changed.branch)
5642        );
5643    }
5644
5645    #[test]
5646    fn candidate_transplant_failure_is_one_actionable_hold() {
5647        let dir = tempfile::tempdir().unwrap();
5648        let q = Queue::at(dir.path().join("queue"));
5649        let mut t = task();
5650        let mut state = run_state(RunStatus::Blocked);
5651        state.event("prep", "cannot apply referenced commit: conflict");
5652        state.prep_failure = Some("conflict".into());
5653        t.start(state.id.clone());
5654        finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
5655        assert_eq!(t.attempts, 1);
5656        assert_eq!(t.status, TaskStatus::Held);
5657        assert!(t.operator_held());
5658        assert!(!t.status.runnable());
5659        assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
5660        let first = t.chat_notice_key().unwrap();
5661        t.chat_notices.push(first.clone());
5662        t.release_operator("test", None);
5663        state.id = "another-unprepared-run".into();
5664        t.start(state.id.clone());
5665        finish_attempt(
5666            3,
5667            &q,
5668            &mut t,
5669            &state,
5670            &[],
5671            Err(anyhow::anyhow!("still conflicts")),
5672        );
5673        assert_eq!(
5674            t.chat_notice_key().as_ref(),
5675            Some(&first),
5676            "no work happened"
5677        );
5678        t.release_operator("test", None);
5679        state.prep_failure = None;
5680        state.status = RunStatus::Failed;
5681        state.begin_pass();
5682        t.start(state.id.clone());
5683        finish_attempt(
5684            1,
5685            &q,
5686            &mut t,
5687            &state,
5688            &[],
5689            Err(anyhow::anyhow!("new gate failure")),
5690        );
5691        let failure = t.chat_notice_key().unwrap();
5692        assert_ne!(failure, first, "approved recovery reached a real failure");
5693        t.release_operator("test", None);
5694        state.begin_pass();
5695        t.start(state.id.clone());
5696        finish_attempt(
5697            1,
5698            &q,
5699            &mut t,
5700            &state,
5701            &[],
5702            Err(anyhow::anyhow!("new failure on resume")),
5703        );
5704        assert_ne!(
5705            t.chat_notice_key().as_ref(),
5706            Some(&failure),
5707            "a new settled pass"
5708        );
5709    }
5710
5711    #[test]
5712    fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
5713        for source in ["cli", "web"] {
5714            let mut t = task();
5715            let mut run = run_state(RunStatus::Blocked);
5716            run.instruction = "Run A original criteria".into();
5717            run.task_instruction = Some(run.instruction.clone());
5718            t.start(run.id.clone());
5719            t.release_operator("choice", Some("resume-question"));
5720            t.resume_override = Some(crate::queue::OperatorResume {
5721                question_id: "resume-question".into(),
5722                at: Timestamp::now(),
5723                conductor_rehold: None,
5724                forced: true,
5725                pinned_run: Some(run.id.clone()),
5726            });
5727            t.hold_machine(Some("not enough free space to start a run".into()));
5728            let mut unchanged = t.clone();
5729            unchanged
5730                .edit("title changed".into(), unchanged.instruction.clone())
5731                .unwrap();
5732            unchanged.release_operator(source, None);
5733            assert_eq!(
5734                unchanged
5735                    .resume_override
5736                    .as_ref()
5737                    .unwrap()
5738                    .pinned_run
5739                    .as_deref(),
5740                Some(run.id.as_str())
5741            );
5742            assert!(!compatible_run_instruction(&run, &unchanged));
5743            assert!(may_resume_run(&run, &unchanged));
5744
5745            t.edit(
5746                "approved recovery".into(),
5747                "Reuse measured PR head B; fix Clippy; review".into(),
5748            )
5749            .unwrap();
5750            assert!(t.resume_override.is_none());
5751            t.release_operator(source, None);
5752            let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
5753            assert!(reloaded.resume_override.is_none());
5754            assert!(!may_resume_run(&run, &reloaded));
5755            let unfinished =
5756                unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
5757                    .filter(|_| may_resume_run(&run, &reloaded));
5758            assert_eq!(
5759                choose_starter(None, false, unfinished.as_deref()),
5760                Starter::Start
5761            );
5762            assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
5763            assert_eq!(
5764                reloaded.resumption_history[0].question_id.as_deref(),
5765                Some("resume-question")
5766            );
5767
5768            // A revision already persisted with the old approval/pin is also
5769            // invalidated when the new operator release is recorded.
5770            unchanged.instruction = "Reuse measured PR head B".into();
5771            unchanged.hold_machine(Some("disk hold".into()));
5772            unchanged.release_operator(source, None);
5773            assert!(unchanged.resume_override.is_none());
5774            assert!(!may_resume_run(&run, &unchanged));
5775        }
5776    }
5777
5778    #[test]
5779    fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
5780        let mut t = task();
5781        let mut run = run_state(RunStatus::Blocked);
5782        t.review_of = Some("approved-head".into());
5783        t.instruction =
5784            "Review the branch `approved-head` (review-only: no implementation, no judging)."
5785                .into();
5786        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();
5787        run.reviewed_commits = Some(vec!["Commit log".into()]);
5788        t.start(run.id.clone());
5789        t.hold_machine(Some("interrupted review".into()));
5790        t.release_operator("cli", None);
5791        assert!(
5792            compatible_run_instruction(&run, &t),
5793            "legacy explicit review remains resumable"
5794        );
5795        let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
5796            .filter(|_| compatible_run_instruction(&run, &t));
5797        assert_eq!(
5798            choose_starter(None, false, unfinished.as_deref()),
5799            Starter::Resume(run.id.clone())
5800        );
5801        run.task_instruction = Some(t.instruction.clone());
5802        assert!(compatible_run_instruction(&run, &t));
5803        let reloaded: RunState =
5804            serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
5805        assert!(compatible_run_instruction(&reloaded, &t));
5806        t.edit(
5807            "new approved head".into(),
5808            "Reuse measured PR head B".into(),
5809        )
5810        .unwrap();
5811        assert!(!compatible_run_instruction(&run, &t));
5812
5813        // Legacy recovery reviews retain the task criteria ahead of the log.
5814        t.review_of = None;
5815        t.instruction = "Fix Clippy on approved head".into();
5816        run.task_instruction = None;
5817        run.instruction = format!(
5818            "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
5819            t.instruction
5820        );
5821        assert!(compatible_run_instruction(&run, &t));
5822        t.instruction.push('\n');
5823        assert!(
5824            compatible_run_instruction(&run, &t),
5825            "legacy generated review trimmed the original criteria"
5826        );
5827        t.hold_for_handover(Some("approved-head".into()), "refused".into());
5828        let mut unchanged = t.clone();
5829        assert_eq!(
5830            take_review_branch(&mut unchanged, Some(&run)).as_deref(),
5831            Some("approved-head")
5832        );
5833        t.edit("new plan".into(), "Reuse measured PR head B".into())
5834            .unwrap();
5835        assert!(take_review_branch(&mut t, Some(&run)).is_none());
5836        assert!(!compatible_run_instruction(&run, &t));
5837        t.review_branch = Some("approved-head".into());
5838        t.review_instruction = None;
5839        assert!(
5840            take_review_branch(&mut t, Some(&run)).is_none(),
5841            "legacy retained candidate cannot replace a revised approved head"
5842        );
5843    }
5844
5845    #[test]
5846    fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
5847        crate::run::pin_test_home();
5848        let dir = tempfile::tempdir().unwrap();
5849        let queue = Queue::at(dir.path().join("queue"));
5850        for resume in [true, false] {
5851            let state = run_state(RunStatus::Blocked);
5852            let mut t = task();
5853            t.start(state.id.clone());
5854            let action = if resume {
5855                ask::ChoiceAction::Resume {
5856                    run: state.id.clone(),
5857                }
5858            } else {
5859                ask::ChoiceAction::Requeue
5860            };
5861            let mut q = action_question(&state.id, action);
5862            q.status = ask::QuestionStatus::Open;
5863            q.answer = None;
5864            q.answered_at = None;
5865            t.fail("run stopped with a question", 3);
5866            hold_if_runnable(&queue, &mut t);
5867            assert!(t.operator_decided_at.is_none());
5868            assert!(t.operator_held());
5869            q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
5870            let expected = if resume {
5871                ActionDecision::Resume(state.id.clone())
5872            } else {
5873                ActionDecision::Requeue
5874            };
5875            assert_eq!(
5876                decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
5877                expected
5878            );
5879            t.hold_manual(Some("later explicit hold".into()));
5880            assert_eq!(
5881                decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
5882                ActionDecision::Stale
5883            );
5884        }
5885    }
5886
5887    #[test]
5888    fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
5889        let mut t = task();
5890        t.answers.push(crate::queue::AnsweredQuestion {
5891            question: "Inspect the remote?".into(),
5892            answer: "Inspect then wait".into(),
5893        });
5894        let old = instruction_for(&t);
5895        assert!(compatible_instruction(&old, &t));
5896        t.instruction = "Reuse approved PR head and review".into();
5897        t.release_operator("cli", None);
5898        assert!(!compatible_instruction(&old, &t));
5899        let approved = instruction_for(&t);
5900        assert!(approved.contains("waiting premises are superseded"));
5901        assert!(compatible_instruction(&approved, &t));
5902        assert_eq!(resumed_instruction(&approved, &t), approved);
5903        t.release_operator("web", None);
5904        assert!(compatible_instruction(&approved, &t));
5905        assert_eq!(t.resumption_history.len(), 1);
5906        t.start("run".into());
5907        assert!(instruction_for(&t).contains("Explicit operator resumption"));
5908    }
5909
5910    /// A run that stopped on an infrastructure wait asked no agent anything:
5911    /// the task is held by the machine under a `[resource]` reason (resumable,
5912    /// re-checked by triage), and the attempt it started is given back.
5913    #[test]
5914    fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
5915        let mut state = RunState::new(
5916            PathBuf::from("/repo"),
5917            "main".to_owned(),
5918            "abc1234".to_owned(),
5919            "task".to_owned(),
5920            Config::default(),
5921        );
5922        state.status = RunStatus::Blocked;
5923        state.resource_block = Some(crate::run::ResourceBlock {
5924            node: "graft".to_owned(),
5925            kind: "shared build cache".to_owned(),
5926            detail: "timed out".to_owned(),
5927            at: jiff::Timestamp::now(),
5928        });
5929        let mut t = task();
5930        t.start("20260902-000000-aaaa".to_owned());
5931        assert_eq!(t.attempts, 1);
5932        let verdict = Verdict {
5933            status: RunStatus::Blocked,
5934            left_pr: false,
5935            quota_hit: false,
5936            parked: false,
5937            no_viable_candidates: false,
5938        };
5939        settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
5940        assert_eq!(t.status, TaskStatus::Held);
5941        assert_eq!(t.attempts, 0, "the attempt is refunded");
5942        assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
5943        assert!(
5944            !t.operator_held(),
5945            "a machine hold, released without a human"
5946        );
5947
5948        let mut selected = task();
5949        selected.start("20260902-000000-cccc".into());
5950        selected.replacement = Some(crate::merge_decision::Replacement {
5951            question: "fixture".into(),
5952            run: "earlier".into(),
5953            pr: "https://example.invalid/pr/1".into(),
5954            agent: "selected".into(),
5955            context: "fixture".into(),
5956        });
5957        state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
5958        settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
5959        assert_eq!(selected.attempts, 0);
5960        assert!(
5961            !selected.operator_held(),
5962            "a selected agent also retains a machine resource hold"
5963        );
5964        assert!(
5965            selected
5966                .hold_reason
5967                .as_deref()
5968                .unwrap()
5969                .starts_with("[resource] ")
5970        );
5971
5972        // A park request outranks it: still the operator's doing.
5973        let mut p = task();
5974        p.start("20260902-000000-bbbb".to_owned());
5975        settle_and_diagnose(
5976            &mut p,
5977            Verdict {
5978                parked: true,
5979                ..verdict
5980            },
5981            "parked",
5982            2,
5983            &state,
5984        );
5985        assert_eq!(p.status, TaskStatus::Parked);
5986    }
5987
5988    #[test]
5989    fn record_failure_notice_links_the_task() {
5990        let dir = tempfile::tempdir().unwrap();
5991        // A regular file where the queue directory should be makes every
5992        // `put` fail, on every platform and whoever runs the test.
5993        std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
5994        let queue = Queue::at(dir.path().join("queue"));
5995        let mut t = interrupt_task("rec-fail-1");
5996        record(&queue, &mut t);
5997
5998        let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
5999        assert_eq!(found.len(), 1);
6000        assert_eq!(found[0].key, "loop:record");
6001        assert_eq!(
6002            found[0].link,
6003            Some(Link::Task {
6004                id: "rec-fail-1".to_owned()
6005            })
6006        );
6007    }
6008
6009    /// A runnable task marked to interrupt, with an id fixed for assertions
6010    /// rather than the random one [`Task::new`] mints.
6011    fn interrupt_task(id: &str) -> Task {
6012        let mut t = task();
6013        t.id = id.to_owned();
6014        t.interrupt = true;
6015        t
6016    }
6017
6018    /// An ordinary runnable task with an id fixed for assertions.
6019    fn task_with_id(id: &str) -> Task {
6020        let mut t = task();
6021        t.id = id.to_owned();
6022        t
6023    }
6024
6025    /// A runnable task marked `--urgent`, with an id fixed for assertions.
6026    fn urgent_task(id: &str) -> Task {
6027        let mut t = task();
6028        t.id = id.to_owned();
6029        t.urgent = true;
6030        t
6031    }
6032
6033    #[test]
6034    fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
6035        let dir = tempfile::tempdir().unwrap();
6036        let queue = Queue::at(dir.path().join("queue"));
6037        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
6038        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
6039        let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
6040        let mut first = task();
6041        queue.put(&mut first).unwrap();
6042        let stale_plain = queue.get(&first.id).unwrap();
6043        first.set_urgent(true).unwrap();
6044        queue.put(&mut first).unwrap();
6045        let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
6046        let mut second = urgent_task("second");
6047        queue.put(&mut second).unwrap();
6048        assert!(claim_dispatch(&queue, &second, false, &ordinary, &urgent).is_none());
6049        drop(queue.claim(&second.id).unwrap());
6050        assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
6051        drop(dispatched);
6052        let stale_urgent = queue.get(&first.id).unwrap();
6053        first.set_urgent(false).unwrap();
6054        queue.put(&mut first).unwrap();
6055        assert!(claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent).is_none());
6056        assert_eq!(urgent.available_permits(), 1);
6057        drop(queue.claim(&first.id).unwrap());
6058        drop(occupied);
6059    }
6060
6061    #[test]
6062    fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
6063        let dir = tempfile::tempdir().unwrap();
6064        let queue = Queue::at(dir.path().join("queue"));
6065        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
6066        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
6067        let mut t = task();
6068        queue.put(&mut t).unwrap();
6069        for enabled in [true, false] {
6070            let stale = queue.get(&t.id).unwrap();
6071            t.set_urgent(enabled).unwrap();
6072            queue.put(&mut t).unwrap();
6073            assert_ne!(stale.urgent, enabled);
6074            let DispatchClaim {
6075                task: fresh,
6076                claim,
6077                permit,
6078            } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
6079            assert_eq!(fresh.urgent, enabled);
6080            assert_eq!(ordinary.available_permits(), usize::from(enabled));
6081            assert_eq!(urgent.available_permits(), usize::from(!enabled));
6082            assert!(queue.claim(&t.id).is_err());
6083            assert_eq!(fresh.attempts, stale.attempts);
6084            drop((claim, permit));
6085            assert_eq!(ordinary.available_permits(), 1);
6086            assert_eq!(urgent.available_permits(), 1);
6087        }
6088        t.set_urgent(true).unwrap();
6089        queue.put(&mut t).unwrap();
6090        let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
6091        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
6092        assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
6093        drop(queue.claim(&t.id).unwrap());
6094        assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
6095        drop(occupied);
6096        assert!(claim_dispatch(&queue, &t, true, &ordinary, &urgent).is_none());
6097        drop(queue.claim(&t.id).unwrap());
6098        let held = queue.claim(&t.id).unwrap();
6099        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
6100        drop(held);
6101        t.status = TaskStatus::Held;
6102        queue.put(&mut t).unwrap();
6103        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
6104        drop(queue.claim(&t.id).unwrap());
6105        std::fs::remove_file(queue.path_of(&t.id)).unwrap();
6106        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
6107        drop(queue.claim(&t.id).unwrap());
6108        assert_eq!(urgent.available_permits(), 1);
6109    }
6110
6111    /// The land-resume exemption wins outright, whether or not the candidate
6112    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
6113    /// queue behind anything" guarantee cannot be weaker just because the
6114    /// same task was also filed with `--urgent`.
6115    #[test]
6116    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
6117        assert_eq!(permit_kind(true, false), PermitKind::None);
6118        assert_eq!(permit_kind(true, true), PermitKind::None);
6119    }
6120
6121    /// The one property this whole feature exists for: `--urgent` draws from
6122    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
6123    /// ordinary candidate draws from the ordinary pool exactly as before,
6124    /// untouched by the urgent slot's existence.
6125    #[test]
6126    fn permit_kind_separates_urgent_from_ordinary() {
6127        assert_eq!(permit_kind(false, true), PermitKind::Urgent);
6128        assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
6129    }
6130
6131    /// The exact wiring `attempt` runs before minting anything: a config's
6132    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
6133    /// Free space is injected rather than asked of the real disk - the point
6134    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
6135    /// is deterministic on every machine this test runs on, never dependent
6136    /// on how full the CI runner's own disk happens to be.
6137    #[test]
6138    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
6139        let cfg = Config::default();
6140        let repo = Path::new("/any/repo/path");
6141
6142        let reason =
6143            disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
6144        assert!(reason.contains("1024"), "{reason}");
6145        assert!(
6146            reason.contains(&cfg.disk.min_free_bytes.to_string()),
6147            "{reason}"
6148        );
6149
6150        assert_eq!(
6151            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
6152            None,
6153            "exactly at the floor is open"
6154        );
6155        assert_eq!(
6156            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
6157            None,
6158            "comfortably above the floor is open"
6159        );
6160    }
6161
6162    #[test]
6163    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
6164        let mut cfg = Config::default();
6165        cfg.disk.min_free_bytes = 0;
6166        let repo = Path::new("/any/repo/path");
6167        assert_eq!(
6168            disk_gate_with(repo, &cfg, |_| Ok(0)),
6169            None,
6170            "a zero floor never measures at all"
6171        );
6172    }
6173
6174    #[test]
6175    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
6176        let cfg = Config::default();
6177        let repo = Path::new("/any/repo/path");
6178        let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
6179            .expect("a measurement failure must close the gate, not open it");
6180        assert!(reason.contains("could not measure"), "{reason}");
6181    }
6182
6183    #[test]
6184    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
6185        let ordinary = task();
6186        let next = advance_interrupt(
6187            Interrupt::Idle,
6188            std::slice::from_ref(&ordinary.id),
6189            std::slice::from_ref(&ordinary),
6190        );
6191        assert_eq!(next, Interrupt::Idle);
6192    }
6193
6194    #[test]
6195    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
6196        // Nothing to interrupt - this is just an ordinary candidate, and the
6197        // loop's normal dispatch will pick it up like any other.
6198        let marked = interrupt_task("marked");
6199        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
6200        assert_eq!(next, Interrupt::Idle);
6201    }
6202
6203    #[test]
6204    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
6205        let marked = interrupt_task("marked");
6206        let next = advance_interrupt(
6207            Interrupt::Idle,
6208            &["running".to_owned()],
6209            std::slice::from_ref(&marked),
6210        );
6211        assert_eq!(
6212            next,
6213            Interrupt::Parking {
6214                parked: vec!["running".to_owned()],
6215                interrupt_task: "marked".to_owned(),
6216            }
6217        );
6218    }
6219
6220    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
6221    /// one run can be in flight when a task becomes runnable and marked.
6222    /// Parking all of them would mean `Resuming` later has more than one id
6223    /// to release back to ordinary dispatch, which cannot be made safe
6224    /// against that same setting's own extra concurrency slots letting two
6225    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
6226    /// The simplification the task's own constraints ask for: do not begin
6227    /// a sequence at all until the herd settles back to exactly one.
6228    #[test]
6229    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
6230        let marked = interrupt_task("marked");
6231
6232        let two = advance_interrupt(
6233            Interrupt::Idle,
6234            &["a".to_owned(), "b".to_owned()],
6235            std::slice::from_ref(&marked),
6236        );
6237        assert_eq!(two, Interrupt::Idle);
6238
6239        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
6240        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
6241    }
6242
6243    #[test]
6244    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
6245        let state = Interrupt::Parking {
6246            parked: vec!["running".to_owned()],
6247            interrupt_task: "marked".to_owned(),
6248        };
6249        // Still in flight: no change.
6250        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
6251        assert_eq!(still_going, state);
6252
6253        // Left flight, but the interrupt task has not been dispatched yet on
6254        // this tick - stays `Parking` so `interrupt_gate` can let it through,
6255        // as long as it is still runnable.
6256        let stopped_but_not_yet_dispatched =
6257            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
6258        assert_eq!(stopped_but_not_yet_dispatched, state);
6259
6260        // Left flight, and the interrupt task is now in flight itself.
6261        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
6262        assert_eq!(
6263            dispatched,
6264            Interrupt::Running {
6265                parked: vec!["running".to_owned()],
6266                interrupt_task: "marked".to_owned(),
6267            }
6268        );
6269    }
6270
6271    #[test]
6272    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
6273        let state = Interrupt::Running {
6274            parked: vec!["running".to_owned()],
6275            interrupt_task: "marked".to_owned(),
6276        };
6277        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
6278        assert_eq!(still_running, state);
6279
6280        // Whatever it ended as - merged, failed, held - is not this
6281        // function's concern: leaving flight is the only trigger, driven
6282        // straight off the same in-flight list `poll` already reaps. It does
6283        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
6284        // why that would let an unrelated task start ahead of, or alongside,
6285        // the guaranteed resume.
6286        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
6287        assert_eq!(
6288            ended,
6289            Interrupt::Resuming {
6290                parked: vec!["running".to_owned()]
6291            }
6292        );
6293    }
6294
6295    #[test]
6296    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
6297        let state = Interrupt::Resuming {
6298            parked: vec!["running".to_owned()],
6299        };
6300        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
6301        assert_eq!(still_waiting, state);
6302
6303        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
6304        assert_eq!(dispatched, Interrupt::Idle);
6305    }
6306
6307    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
6308    /// or otherwise moved on by an operator with no claim standing in the
6309    /// way - must not wedge the sequence (and so the whole loop's dispatch,
6310    /// via `interrupt_gate`) waiting forever for a dispatch that can never
6311    /// come. The parked run still gets its resume.
6312    #[test]
6313    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
6314    {
6315        let state = Interrupt::Parking {
6316            parked: vec!["running".to_owned()],
6317            interrupt_task: "marked".to_owned(),
6318        };
6319        // `marked` has been held/blocked/deleted since the sequence began:
6320        // it no longer appears in `runnable` at all.
6321        let next = advance_interrupt(state, &[], &[]);
6322        assert_eq!(
6323            next,
6324            Interrupt::Resuming {
6325                parked: vec!["running".to_owned()]
6326            },
6327            "abandoning the interrupt must not abandon the resume it owes"
6328        );
6329    }
6330
6331    /// The same abandonment, one step later: `Resuming` itself must not wait
6332    /// forever for a parked task that has since become unrunnable.
6333    #[test]
6334    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
6335        let state = Interrupt::Resuming {
6336            parked: vec!["running".to_owned()],
6337        };
6338        let next = advance_interrupt(state, &[], &[]);
6339        assert_eq!(
6340            next,
6341            Interrupt::Idle,
6342            "nothing is left to wait for; the loop must not stay wedged"
6343        );
6344    }
6345
6346    #[test]
6347    fn disabled_by_config_the_sequence_can_never_leave_idle() {
6348        let marked = interrupt_task("marked");
6349        let next = advance_interrupt_tick(
6350            false,
6351            Interrupt::Idle,
6352            &["running".to_owned()],
6353            std::slice::from_ref(&marked),
6354        );
6355        assert_eq!(
6356            next,
6357            Interrupt::Idle,
6358            "an unmarked, unconfigured daemon must behave exactly as before"
6359        );
6360    }
6361
6362    #[test]
6363    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
6364        let state = Interrupt::Parking {
6365            parked: vec!["running".to_owned()],
6366            interrupt_task: "marked".to_owned(),
6367        };
6368        let candidates = vec![interrupt_task("marked"), task()];
6369        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
6370        assert!(
6371            allowed.is_empty(),
6372            "nothing may dispatch - not even the interrupt task itself - \
6373             until the parked run has actually stopped"
6374        );
6375    }
6376
6377    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
6378    /// grow a special case for it: an urgent candidate that is not the
6379    /// interrupt task withholds exactly like an ordinary one for as long as
6380    /// the parked run it is racing has not actually left flight. A version
6381    /// of this feature once bypassed the gate for urgent candidates, on the
6382    /// theory that a genuinely separate concurrency lane could not collide
6383    /// with 75dd's own; it could, and did - the bypassed task dispatched
6384    /// alongside a run 75dd's own state machine had only *asked* to park,
6385    /// not yet confirmed gone, which is exactly the second run
6386    /// `Interrupt::Parking`'s own doc says must never happen. There is no
6387    /// tick during Parking/Running/Resuming where letting an extra
6388    /// candidate through is safe, urgent or not - the parked run may still
6389    /// be genuinely mid-call.
6390    #[test]
6391    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
6392        for state in [
6393            Interrupt::Parking {
6394                parked: vec!["running".to_owned()],
6395                interrupt_task: "marked".to_owned(),
6396            },
6397            Interrupt::Running {
6398                parked: vec!["running".to_owned()],
6399                interrupt_task: "marked".to_owned(),
6400            },
6401            Interrupt::Resuming {
6402                parked: vec!["running".to_owned()],
6403            },
6404        ] {
6405            let candidates = vec![
6406                interrupt_task("marked"),
6407                urgent_task("hot"),
6408                task_with_id("ordinary"),
6409            ];
6410            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
6411            assert!(
6412                !allowed.iter().any(|t| t.id == "hot"),
6413                "an urgent candidate must wait out the same gate as anything \
6414                 else while the run it would run alongside has not actually \
6415                 left flight, for state {state:?}: {allowed:?}"
6416            );
6417        }
6418    }
6419
6420    /// The one case where marking a task `--urgent` and `interrupt` at once
6421    /// is not redundant: once the interrupt sequence's own guaranteed
6422    /// resume/dispatch actually admits the task, it is unaffected by also
6423    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
6424    /// never on the urgent flag.
6425    #[test]
6426    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
6427        let state = Interrupt::Resuming {
6428            parked: vec!["hot".to_owned()],
6429        };
6430        let candidates = vec![urgent_task("hot"), task()];
6431        let allowed = interrupt_gate(&state, &[], candidates);
6432        assert_eq!(
6433            allowed.iter().filter(|t| t.id == "hot").count(),
6434            1,
6435            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
6436        );
6437    }
6438
6439    #[test]
6440    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
6441        let state = Interrupt::Parking {
6442            parked: vec!["running".to_owned()],
6443            interrupt_task: "marked".to_owned(),
6444        };
6445        let other = task();
6446        let candidates = vec![interrupt_task("marked"), other.clone()];
6447        let allowed = interrupt_gate(&state, &[], candidates);
6448        assert_eq!(allowed.len(), 1);
6449        assert_eq!(allowed[0].id, "marked");
6450    }
6451
6452    #[test]
6453    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
6454        let state = Interrupt::Running {
6455            parked: vec!["running".to_owned()],
6456            interrupt_task: "marked".to_owned(),
6457        };
6458        let candidates = vec![task(), task()];
6459        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
6460        assert!(allowed.is_empty());
6461    }
6462
6463    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
6464    /// sequence began (only reachable above the default
6465    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
6466    /// never both in the same tick, which is what "exactly one resume, no
6467    /// simultaneous run" actually requires structurally rather than by
6468    /// coincidence of how many ordinary slots happen to be free.
6469    #[test]
6470    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
6471        let state = Interrupt::Resuming {
6472            parked: vec!["a".to_owned(), "c".to_owned()],
6473        };
6474        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
6475        let allowed = interrupt_gate(&state, &[], candidates);
6476        assert_eq!(
6477            allowed.len(),
6478            1,
6479            "at most one candidate may be offered while resuming: {allowed:?}"
6480        );
6481        assert_eq!(allowed[0].id, "a");
6482    }
6483
6484    #[test]
6485    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
6486        let state = Interrupt::Resuming {
6487            parked: vec!["a".to_owned()],
6488        };
6489        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
6490        assert!(allowed.is_empty());
6491    }
6492
6493    /// The invariant the completion criteria ask for by name: across a whole
6494    /// simulated sequence, there is never a tick where the gate would let
6495    /// through both the parked run's resume and the interrupt task, and
6496    /// exactly one candidate resumes the instant the interrupt task's run
6497    /// ends - never zero, never more than one.
6498    #[test]
6499    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
6500        let running = task(); // id: whatever `Task::new` minted
6501        let marked = interrupt_task("marked");
6502
6503        let mut state = Interrupt::Idle;
6504        // Tick 1: `running` is in flight, `marked` becomes runnable.
6505        let in_flight = vec![running.id.clone()];
6506        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
6507        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
6508        assert!(gated.is_empty(), "still waiting on `running` to park");
6509
6510        // Tick 2: `running` parked and left flight; nothing dispatched yet.
6511        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
6512        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
6513        assert_eq!(
6514            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
6515            vec!["marked"],
6516            "only the interrupt task may be offered to the dispatcher now"
6517        );
6518
6519        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
6520        state = advance_interrupt_tick(
6521            true,
6522            state,
6523            &["marked".to_owned()],
6524            std::slice::from_ref(&running),
6525        );
6526        let gated = interrupt_gate(
6527            &state,
6528            &["marked".to_owned()],
6529            vec![marked.clone(), running.clone()],
6530        );
6531        assert!(
6532            gated.is_empty(),
6533            "the parked run must not be offered back while the interrupt \
6534             task is still running"
6535        );
6536
6537        // Tick 4: `marked`'s run reached a terminal status and left flight.
6538        // A higher-priority ordinary task `other` is also runnable now - it
6539        // must not be let through instead of, or alongside, `running`.
6540        let other = task_with_id("other");
6541        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
6542        assert_eq!(
6543            state,
6544            Interrupt::Resuming {
6545                parked: vec![running.id.clone()]
6546            }
6547        );
6548        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
6549        assert_eq!(
6550            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
6551            vec![running.id.as_str()],
6552            "exactly the parked run resumes - not the unrelated task, even \
6553             though it was offered first"
6554        );
6555
6556        // Tick 5: `running` is now in flight (dispatched from tick 4's
6557        // gate). Only now does the sequence end and ordinary dispatch fully
6558        // resume.
6559        state = advance_interrupt_tick(
6560            true,
6561            state,
6562            std::slice::from_ref(&running.id),
6563            std::slice::from_ref(&other),
6564        );
6565        assert_eq!(state, Interrupt::Idle);
6566        let gated = interrupt_gate(
6567            &state,
6568            std::slice::from_ref(&running.id),
6569            vec![other.clone()],
6570        );
6571        assert_eq!(
6572            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
6573            vec![other.id.as_str()],
6574            "ordinary dispatch is unrestricted again"
6575        );
6576    }
6577
6578    #[test]
6579    fn every_run_status_settles_the_task_it_came_from() {
6580        // run status, resulting task status, attempts still standing after one
6581        let table = [
6582            (RunStatus::Merged, TaskStatus::Done, 1),
6583            (RunStatus::Ready, TaskStatus::Done, 1),
6584            (RunStatus::Stalled, TaskStatus::Failed, 0),
6585            (RunStatus::Blocked, TaskStatus::Failed, 1),
6586            (RunStatus::Failed, TaskStatus::Failed, 1),
6587            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
6588            (RunStatus::Prep, TaskStatus::Failed, 1),
6589            (RunStatus::Implementing, TaskStatus::Failed, 1),
6590            (RunStatus::Judging, TaskStatus::Failed, 1),
6591            (RunStatus::Deliberating, TaskStatus::Failed, 1),
6592            (RunStatus::Voting, TaskStatus::Failed, 1),
6593            (RunStatus::Reviewing, TaskStatus::Failed, 1),
6594            (RunStatus::Gating, TaskStatus::Failed, 1),
6595        ];
6596        for (run, want, attempts) in table {
6597            let mut t = task();
6598            t.start("20260902-000000-aaaa".to_owned());
6599            settle(
6600                &mut t,
6601                Verdict {
6602                    status: run,
6603                    left_pr: false,
6604                    parked: false,
6605                    quota_hit: matches!(run, RunStatus::Stalled),
6606                    no_viable_candidates: false,
6607                },
6608                "why",
6609                2,
6610            );
6611            assert_eq!(t.status, want, "task status after {}", label(run));
6612            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
6613        }
6614    }
6615
6616    #[test]
6617    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
6618        let mut stalled = task();
6619        stalled.start("20260902-000000-aaaa".to_owned());
6620        settle(
6621            &mut stalled,
6622            Verdict {
6623                status: RunStatus::Stalled,
6624                left_pr: false,
6625                parked: false,
6626                quota_hit: true,
6627                no_viable_candidates: false,
6628            },
6629            "quota",
6630            1,
6631        );
6632        assert_eq!(stalled.attempts, 0);
6633        assert!(
6634            stalled.status.runnable(),
6635            "a machine problem must leave the task in line"
6636        );
6637
6638        let mut blocked = task();
6639        blocked.start("20260902-000000-aaaa".to_owned());
6640        settle(
6641            &mut blocked,
6642            Verdict {
6643                status: RunStatus::Blocked,
6644                left_pr: false,
6645                parked: false,
6646                quota_hit: false,
6647                no_viable_candidates: false,
6648            },
6649            "findings open",
6650            1,
6651        );
6652        assert_eq!(blocked.attempts, 1);
6653        assert_eq!(
6654            blocked.status,
6655            TaskStatus::Held,
6656            "the last attempt hands the task to a human"
6657        );
6658    }
6659
6660    #[test]
6661    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
6662        // Attempts to spare: without the pull request this task would go
6663        // straight back in line and run the whole competition again.
6664        let mut delivered = task();
6665        delivered.start("20260903-080619-01c2".to_owned());
6666        settle(
6667            &mut delivered,
6668            Verdict {
6669                status: RunStatus::Blocked,
6670                left_pr: true,
6671                parked: false,
6672                quota_hit: false,
6673                no_viable_candidates: false,
6674            },
6675            "no check status",
6676            4,
6677        );
6678        assert_eq!(
6679            delivered.status,
6680            TaskStatus::Held,
6681            "a pull request waiting on CI or a person is not a retryable failure"
6682        );
6683        assert!(
6684            !delivered.status.runnable(),
6685            "the loop must not pick this task up again"
6686        );
6687        assert_eq!(
6688            delivered.last_error.as_deref(),
6689            Some("no check status"),
6690            "the operator needs to be told what the gate was waiting for"
6691        );
6692
6693        // The same status without a pull request is a plain failure, and with
6694        // attempts left it is retried.
6695        let mut empty_handed = task();
6696        empty_handed.start("20260903-080619-01c2".to_owned());
6697        settle(
6698            &mut empty_handed,
6699            Verdict {
6700                status: RunStatus::Blocked,
6701                left_pr: false,
6702                parked: false,
6703                quota_hit: false,
6704                no_viable_candidates: false,
6705            },
6706            "findings open",
6707            4,
6708        );
6709        assert_eq!(empty_handed.status, TaskStatus::Failed);
6710        assert!(empty_handed.status.runnable());
6711    }
6712
6713    #[test]
6714    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
6715        // Every candidate agreed, with evidence, that nothing belonged in the
6716        // worktree. That is not a confirmed success to close automatically -
6717        // a human still has to check the claim - and it is not an ordinary
6718        // failure either, so this settles exactly like a pull request nobody
6719        // merged yet: `Held`, same as `Blocked` with a PR.
6720        let mut noop = task();
6721        noop.start("20260912-131304-391f".to_owned());
6722        settle(
6723            &mut noop,
6724            Verdict {
6725                status: RunStatus::VerifiedNoop,
6726                left_pr: false,
6727                parked: false,
6728                quota_hit: false,
6729                no_viable_candidates: true,
6730            },
6731            "candidate A: already fixed by b32cfc4, on main",
6732            4,
6733        );
6734        assert_eq!(
6735            noop.status,
6736            TaskStatus::Held,
6737            "an unverified claim is a request for a human, not a failure"
6738        );
6739        assert!(
6740            !noop.status.runnable(),
6741            "the loop must not requeue this on the same unverified claim"
6742        );
6743        // `Task::release` resets attempts to zero the moment a human looks at
6744        // the evidence and lets it run again, so it does not matter here
6745        // whether the one attempt already spent stays spent - what matters is
6746        // that nothing retries this task unattended in the meantime.
6747        assert_eq!(noop.attempts, 1);
6748    }
6749
6750    #[test]
6751    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
6752        // Parking is the operator asking for the process back - to replace the
6753        // binary, most of all. The run's work is intact on disk, so this is
6754        // not a failed attempt, and charging for it would mean a few upgrades
6755        // could exhaust a budget meant for agents that misbehaved.
6756        let mut parked = task();
6757        parked.start("20260903-183634-2d98".to_owned());
6758        settle(
6759            &mut parked,
6760            Verdict {
6761                status: RunStatus::Implementing,
6762                left_pr: false,
6763                quota_hit: false,
6764                parked: true,
6765                no_viable_candidates: false,
6766            },
6767            "parked after `implementing`",
6768            2,
6769        );
6770        assert_eq!(parked.attempts, 0, "a park is refunded");
6771        assert!(
6772            parked.status.runnable(),
6773            "and the task stays in line so the next loop resumes its run"
6774        );
6775        assert_eq!(parked.status, TaskStatus::Parked);
6776        assert_eq!(
6777            parked.park_reason.as_deref(),
6778            Some("parked after `implementing`"),
6779            "the card says where it stopped"
6780        );
6781        assert_eq!(parked.last_error, None, "nothing failed");
6782
6783        // Without the park flag the same non-terminal status is what it always
6784        // was: `execute` returning mid-flight, which is a bug and spends an
6785        // attempt so a task cannot loop on it forever.
6786        let mut broken = task();
6787        broken.start("20260903-183634-2d98".to_owned());
6788        settle(
6789            &mut broken,
6790            Verdict {
6791                status: RunStatus::Implementing,
6792                left_pr: false,
6793                quota_hit: false,
6794                parked: false,
6795                no_viable_candidates: false,
6796            },
6797            "returned mid-flight",
6798            2,
6799        );
6800        assert_eq!(broken.attempts, 1);
6801    }
6802
6803    #[test]
6804    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
6805        // Run e633: quorum lost because two judges answered with the wrong
6806        // JSON shape, `quota: []`. Refunding that takes the bound off the
6807        // retry loop, and each retry pays for a fresh hour-long implement
6808        // wave before it can fail the same way.
6809        let mut flaky = task();
6810        flaky.start("20260903-123023-e633".to_owned());
6811        settle(
6812            &mut flaky,
6813            Verdict {
6814                status: RunStatus::Stalled,
6815                left_pr: false,
6816                parked: false,
6817                quota_hit: false,
6818                no_viable_candidates: false,
6819            },
6820            "verdict rests on 1 of 3 judges",
6821            2,
6822        );
6823        assert_eq!(
6824            flaky.attempts, 1,
6825            "flakiness spends an attempt, so `max_attempts` still bounds it"
6826        );
6827        assert!(flaky.status.runnable(), "and it is still worth retrying");
6828
6829        // The same status, lost to a rate limit, is the machine's fault.
6830        let mut limited = task();
6831        limited.start("20260903-123023-e633".to_owned());
6832        settle(
6833            &mut limited,
6834            Verdict {
6835                status: RunStatus::Stalled,
6836                left_pr: false,
6837                parked: false,
6838                quota_hit: true,
6839                no_viable_candidates: false,
6840            },
6841            "judge-2, judge-3 out of quota",
6842            2,
6843        );
6844        assert_eq!(limited.attempts, 0, "a quota window is refunded");
6845        assert!(limited.status.runnable());
6846
6847        // And the bound really binds: a task that keeps stalling on flakiness
6848        // reaches a human instead of running the roster forever.
6849        let mut worn = task();
6850        for _ in 0..2 {
6851            worn.release();
6852        }
6853        worn.start("20260903-123023-e633".to_owned());
6854        worn.attempts = 2;
6855        settle(
6856            &mut worn,
6857            Verdict {
6858                status: RunStatus::Stalled,
6859                left_pr: false,
6860                parked: false,
6861                quota_hit: false,
6862                no_viable_candidates: false,
6863            },
6864            "no quorum again",
6865            2,
6866        );
6867        assert_eq!(worn.status, TaskStatus::Held);
6868        assert!(!worn.status.runnable());
6869    }
6870
6871    #[test]
6872    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
6873        // The implement wave loses every seat to the same rate limit and
6874        // `after_implement` bails with nothing viable, which surfaces as
6875        // `Failed` rather than `Stalled`. That is the same machine fact the
6876        // `Stalled`-quota row already refunds, and must be refunded the same
6877        // way, or a quota outage quietly holds every task it touches instead
6878        // of leaving them in line for the reset.
6879        let mut wiped_out = task();
6880        wiped_out.start("20260907-025000-a1b2".to_owned());
6881        settle(
6882            &mut wiped_out,
6883            Verdict {
6884                status: RunStatus::Failed,
6885                left_pr: false,
6886                parked: false,
6887                quota_hit: true,
6888                no_viable_candidates: true,
6889            },
6890            "no candidate produced a change; nothing to judge",
6891            2,
6892        );
6893        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
6894        assert!(
6895            wiped_out.status.runnable(),
6896            "a machine problem must leave the task in line"
6897        );
6898
6899        // This is the exemption that must stay narrow: a candidate that did
6900        // produce a change, and then failed for some other reason, still
6901        // spends the attempt even though a seat elsewhere hit its quota.
6902        // Otherwise every ordinary failure that happens to share a run with
6903        // an unrelated rate limit would be refunded for free.
6904        let mut partial_progress = task();
6905        partial_progress.start("20260907-025500-c3d4".to_owned());
6906        settle(
6907            &mut partial_progress,
6908            Verdict {
6909                status: RunStatus::Failed,
6910                left_pr: false,
6911                parked: false,
6912                quota_hit: true,
6913                no_viable_candidates: false,
6914            },
6915            "gate failed on the winning candidate",
6916            2,
6917        );
6918        assert_eq!(
6919            partial_progress.attempts, 1,
6920            "a candidate that actually produced a change spends the attempt \
6921             even though some other seat hit its quota"
6922        );
6923        assert!(partial_progress.status.runnable());
6924    }
6925
6926    #[test]
6927    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
6928        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
6929        // disk, and that construction must reach the same conclusion as the
6930        // one `attempt` builds from a live run, or a crash at exactly the
6931        // wrong moment gives a recovered task a different policy than one a
6932        // daemon finished settling itself.
6933        let mut t = task();
6934        t.start("20260907-025000-a1b2".to_owned());
6935        let mut state = run_state(RunStatus::Failed);
6936        state.quota.push(QuotaLoss {
6937            seat: "cand-a".to_owned(),
6938            node: "implement".to_owned(),
6939            at: Timestamp::now(),
6940            reset: None,
6941        });
6942        assert!(
6943            state.viable().is_empty(),
6944            "no candidate was added, so nothing is viable"
6945        );
6946        reclaim(&mut t, Some(state), 2, "en");
6947        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
6948        assert!(t.status.runnable());
6949    }
6950
6951    #[test]
6952    fn a_held_task_is_never_offered_to_the_loop() {
6953        let dir = tempfile::tempdir().unwrap();
6954        let queue = Queue::at(dir.path().to_path_buf());
6955        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
6956            let mut t = task();
6957            t.id = format!("2026090{n}-000000-000{n}");
6958            t.priority = priority;
6959            queue.put(&mut t).unwrap();
6960        }
6961        let mut held = task();
6962        held.id = "20260909-000000-9999".to_owned();
6963        held.priority = 99;
6964        held.hold_machine(None);
6965        queue.put(&mut held).unwrap();
6966
6967        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
6968        assert_eq!(order.len(), 3);
6969        assert!(!order.contains(&held.id));
6970        assert_eq!(
6971            order.first().cloned(),
6972            queue.next_runnable().map(|t| t.id),
6973            "the loop's first candidate is exactly what the queue offers"
6974        );
6975        assert_eq!(
6976            order,
6977            vec![
6978                "20260902-000000-0002".to_owned(),
6979                "20260903-000000-0003".to_owned(),
6980                "20260901-000000-0001".to_owned(),
6981            ],
6982            "priority first, then oldest, so nothing starves"
6983        );
6984    }
6985
6986    #[test]
6987    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
6988        let dir = tempfile::tempdir().unwrap();
6989        let queue = Queue::at(dir.path().to_path_buf());
6990        let mut old = task();
6991        old.id = "20260101-000000-old0".to_owned();
6992        queue.put(&mut old).unwrap();
6993        let mut fresh = task();
6994        fresh.id = "20260101-000000-new0".to_owned();
6995        queue.put(&mut fresh).unwrap();
6996
6997        // No parseable pid at all, so age is the only signal there is to
6998        // check - unlike a real `Queue::claim`, which always names a real,
6999        // and therefore alive, pid this test cannot fake as dead.
7000        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
7001        std::thread::sleep(Duration::from_millis(60));
7002        let live = queue.claim(&fresh.id).unwrap();
7003
7004        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
7005        assert_eq!(swept, vec![old.id.clone()]);
7006        assert!(
7007            queue.claim(&old.id).is_ok(),
7008            "an unparseable lock older than the threshold is swept"
7009        );
7010        assert!(
7011            queue.claim(&fresh.id).is_err(),
7012            "a live pid protects its lock regardless of age"
7013        );
7014        drop(live);
7015    }
7016
7017    #[test]
7018    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
7019        // The regression this guards: `sweep` now runs concurrently with
7020        // every attempt this daemon itself has spawned (see
7021        // `InFlightGuard`), not only between them the way a single
7022        // sequential loop once did. A run that legitimately outlives
7023        // `older_than` still has this very process's own live pid sitting in
7024        // its own lock file on every later sweep, and deciding by age alone
7025        // would delete that still-valid claim out from under the attempt
7026        // that holds it - which `reclaim_orphaned_running` would then read
7027        // as abandoned and hand to a second, competing attempt.
7028        let dir = tempfile::tempdir().unwrap();
7029        let queue = Queue::at(dir.path().to_path_buf());
7030        let mut t = task();
7031        t.id = "20260101-000000-live".to_owned();
7032        queue.put(&mut t).unwrap();
7033
7034        let claim = queue.claim(&t.id).unwrap();
7035        std::thread::sleep(Duration::from_millis(60));
7036
7037        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
7038        assert!(
7039            swept.is_empty(),
7040            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
7041        );
7042        assert!(
7043            queue.claim(&t.id).is_err(),
7044            "the lock still protects its task"
7045        );
7046        drop(claim);
7047    }
7048
7049    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
7050    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
7051    fn injected_dead_pid() -> u32 {
7052        std::process::id().checked_add(1).unwrap_or(1)
7053    }
7054
7055    #[test]
7056    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
7057        let dir = tempfile::tempdir().unwrap();
7058        let queue = Queue::at(dir.path().to_path_buf());
7059        let mut t = task();
7060        t.id = "20260101-000000-dead".to_owned();
7061        queue.put(&mut t).unwrap();
7062        let dead_pid = injected_dead_pid();
7063
7064        // Written directly rather than through `Queue::claim`, which would
7065        // stamp this test process's own very much alive pid and defeat the
7066        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
7067        // like moments after it died, not six hours later.
7068        std::fs::write(
7069            dir.path().join(format!("{}.lock", t.id)),
7070            dead_pid.to_string(),
7071        )
7072        .unwrap();
7073
7074        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
7075            pid != dead_pid
7076        });
7077        assert_eq!(
7078            swept,
7079            vec![t.id.clone()],
7080            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
7081        );
7082        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
7083    }
7084
7085    #[test]
7086    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
7087        let dir = tempfile::tempdir().unwrap();
7088        let queue = Queue::at(dir.path().to_path_buf());
7089        let mut t = task();
7090        t.id = "20260101-000000-late".to_owned();
7091        queue.put(&mut t).unwrap();
7092        let dead_pid = injected_dead_pid();
7093
7094        // Tick one, standing in for the sweep `poll` already runs at
7095        // startup: nothing to find yet.
7096        assert!(
7097            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
7098            "nothing has claimed the task yet"
7099        );
7100
7101        // A second daemon claims the task and dies before it ever writes
7102        // `running`, well after this loop's own startup sweep already ran.
7103        std::fs::write(
7104            dir.path().join(format!("{}.lock", t.id)),
7105            dead_pid.to_string(),
7106        )
7107        .unwrap();
7108
7109        // Tick two, standing in for a poll long into this daemon's uptime:
7110        // the same function, called again, notices what only just appeared -
7111        // proving the sweep is not a one-shot startup check.
7112        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
7113            pid != dead_pid
7114        });
7115        assert_eq!(swept, vec![t.id.clone()]);
7116    }
7117
7118    #[test]
7119    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
7120        // `reclaim_orphaned_running` looks up the task's last run, which
7121        // touches `run::home()`; the first call anywhere in this binary wins,
7122        // so this is a no-op if another test already pinned one, and either
7123        // way the run id below is never written under it.
7124        crate::run::pin_test_home();
7125        let dir = tempfile::tempdir().unwrap();
7126        let queue = Queue::at(dir.path().to_path_buf());
7127        let mut t = task();
7128        t.id = "20260101-000000-crsh".to_owned();
7129        t.status = TaskStatus::Running;
7130        t.attempts = 1;
7131        // No `run.json` behind this id: standing in for a run this test does
7132        // not need to make readable, since the point is the lock, not the
7133        // recovery table `reclaim` already has its own tests for.
7134        t.runs.push("20260904-000000-4043".to_owned());
7135        queue.put(&mut t).unwrap();
7136        let dead_pid = injected_dead_pid();
7137
7138        // The crashed daemon's own claim, naming a pid nothing on the
7139        // machine holds anymore.
7140        std::fs::write(
7141            dir.path().join(format!("{}.lock", t.id)),
7142            dead_pid.to_string(),
7143        )
7144        .unwrap();
7145
7146        // Before the lock is swept the task looks claimed, and
7147        // `reclaim_orphaned_running` must leave it alone - this is exactly
7148        // the bug: a `running` task stranded behind a dead daemon's lock,
7149        // invisible to the claim-as-proof check because the lock outlived
7150        // the process that wrote it.
7151        assert!(reclaim_orphaned_running(&queue, 2).is_empty());
7152        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
7153
7154        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
7155            pid != dead_pid
7156        });
7157        assert_eq!(swept, vec![t.id.clone()]);
7158
7159        let reclaimed = reclaim_orphaned_running(&queue, 2);
7160        assert_eq!(reclaimed, vec![t.id.clone()]);
7161        let after = queue.get(&t.id).unwrap();
7162        assert_eq!(
7163            after.status,
7164            TaskStatus::Held,
7165            "no run.json to recover from, so a human is asked"
7166        );
7167        assert_eq!(
7168            after.runs,
7169            vec!["20260904-000000-4043".to_owned()],
7170            "the crashed run's id is kept as evidence, not discarded"
7171        );
7172    }
7173
7174    #[test]
7175    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
7176        let dir = tempfile::tempdir().unwrap();
7177        let queue = Queue::at(dir.path().to_path_buf());
7178        let mut t = task();
7179        t.id = "20260101-000000-unknown".to_owned();
7180        queue.put(&mut t).unwrap();
7181        let dead_pid = injected_dead_pid();
7182        std::fs::write(
7183            dir.path().join(format!("{}.lock", t.id)),
7184            dead_pid.to_string(),
7185        )
7186        .unwrap();
7187
7188        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
7189        assert!(swept.is_empty(), "an unknown pid must keep its lock");
7190        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
7191    }
7192
7193    fn run_state_in(status: RunStatus, language: &str) -> RunState {
7194        let mut s = run_state(status);
7195        s.config.graph.language = language.to_owned();
7196        s
7197    }
7198
7199    fn unstarted_verdict(status: RunStatus) -> Verdict {
7200        Verdict {
7201            status,
7202            left_pr: false,
7203            quota_hit: false,
7204            parked: false,
7205            no_viable_candidates: false,
7206        }
7207    }
7208
7209    #[test]
7210    fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
7211        let mut t = task();
7212        t.attempts = 1;
7213        settle_in(
7214            &mut t,
7215            unstarted_verdict(RunStatus::AlreadyInBase),
7216            "already in main",
7217            1,
7218            phrases("en"),
7219        );
7220        assert_eq!(t.status, TaskStatus::Done);
7221        assert_eq!(t.attempts, 0);
7222    }
7223
7224    #[test]
7225    fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
7226        let reason = |language: &str| {
7227            let mut t = task();
7228            settle_in(
7229                &mut t,
7230                unstarted_verdict(RunStatus::Judging),
7231                "boom",
7232                1,
7233                phrases(language),
7234            );
7235            t.last_error.or(t.hold_reason).unwrap_or_default()
7236        };
7237        assert!(
7238            reason("en").starts_with("the graph stopped at `"),
7239            "{}",
7240            reason("en")
7241        );
7242        assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
7243        assert!(reason("日本語").contains("boom"));
7244        assert_eq!(reason("fr"), reason("en"));
7245    }
7246
7247    #[test]
7248    fn describe_follows_the_run_language_and_keeps_the_run_id() {
7249        let en = describe(&run_state_in(RunStatus::Stalled, "en"));
7250        assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
7251        let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
7252        assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
7253        assert!(ja.contains("[run "), "{ja}");
7254        let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
7255        assert!(ended.starts_with("run 終了: "), "{ended}");
7256        let mut de = run_state_in(RunStatus::Failed, "de");
7257        let mut en = run_state_in(RunStatus::Failed, "en");
7258        de.id = "same".to_owned();
7259        en.id = "same".to_owned();
7260        assert_eq!(describe(&de), describe(&en));
7261    }
7262
7263    #[test]
7264    fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
7265        use crate::handover::Refused;
7266        let cases = [
7267            Refused::Foreign {
7268                branch: "b".into(),
7269                path: "/w/x".into(),
7270                why: "made by hand".into(),
7271            },
7272            Refused::Unsafe {
7273                branch: "b".into(),
7274                path: "/w/x".into(),
7275                why: "its worktree has uncommitted changes (a.rs)".into(),
7276            },
7277            Refused::ReleaseFailed {
7278                branch: "b".into(),
7279                path: "/w/x".into(),
7280                run: "ab12".into(),
7281            },
7282        ];
7283        for r in &cases {
7284            let en = (phrases("en").handover_refused)(r);
7285            assert_eq!(en, r.to_string());
7286            let ja = (phrases("ja").handover_refused)(r);
7287            assert!(
7288                !ja.contains("is checked out") && !ja.contains("try again"),
7289                "{ja}"
7290            );
7291            assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
7292            if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
7293                assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
7294            }
7295        }
7296        assert!(phrases("en").handover_hint.contains("release the task"));
7297        assert!(phrases("ja").handover_hint.contains("解放"));
7298    }
7299
7300    #[test]
7301    fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
7302        let build = |lang: &str| {
7303            let mut s = run_state_in(RunStatus::Blocked, lang);
7304            s.id = "same".to_owned();
7305            s.config.graph.review_rounds = 3;
7306            let mut r = review_round(3);
7307            r.expected = 3;
7308            r.answered = 1;
7309            s.reviews.push(r);
7310            s.event(
7311                "review",
7312                "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
7313            );
7314            s
7315        };
7316        let en = describe(&build("en"));
7317        assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
7318        let ja = describe(&build("ja"));
7319        assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
7320        assert!(!ja.contains("never answered"), "{ja}");
7321        assert!(ja.contains("[run "), "{ja}");
7322
7323        // An incomplete panel whose verification failed is a different stop:
7324        // the real event must survive in ja too.
7325        let mut failed = build("ja");
7326        failed.reviews[0].e2e.push(crate::run::CommandOutcome {
7327            command: "cargo test".to_owned(),
7328            code: Some(1),
7329            output_tail: String::new(),
7330            duration_ms: 0,
7331            resource_blocked: false,
7332        });
7333        failed.event("review", "stopped; e2e failed: cargo test");
7334        let ja = describe(&failed);
7335        assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
7336        assert!(!ja.contains("席のレビュアー"), "{ja}");
7337    }
7338
7339    #[test]
7340    fn refusals_and_recovery_prose_follow_the_language() {
7341        let t = held_task_with("r1");
7342        let q = action_question(
7343            "r1",
7344            ask::ChoiceAction::Resume {
7345                run: "r1".to_owned(),
7346            },
7347        );
7348        let refuse = |p: &Phrases| match decide_action(&t, &q, p, |_: &str| bail!("gone")) {
7349            ActionDecision::Refuse(s) => s,
7350            other => panic!("{other:?}"),
7351        };
7352        assert!(refuse(phrases("en")).contains("could not be read: gone"));
7353        assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
7354        assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
7355
7356        let mut held = task();
7357        reclaim(&mut held, None, 2, "ja");
7358        assert!(held.hold_reason.unwrap().contains("保留にしました"));
7359        let mut held = task();
7360        reclaim(&mut held, None, 2, "xx");
7361        assert!(held.hold_reason.unwrap().contains("held for a human"));
7362    }
7363
7364    fn run_state(status: RunStatus) -> RunState {
7365        let mut state = RunState::new(
7366            PathBuf::from("/repo"),
7367            "main".to_owned(),
7368            "abc1234def".to_owned(),
7369            "add retries".to_owned(),
7370            Config::default(),
7371        );
7372        state.status = status;
7373        state
7374    }
7375
7376    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
7377        Candidate {
7378            index: 0,
7379            label,
7380            agent: "claude".to_owned(),
7381            branch: format!("magi/x/{label}"),
7382            worktree: PathBuf::from("/repo"),
7383            summary: summary.to_owned(),
7384            stat: String::new(),
7385            files: 0,
7386            commits: usize::from(!empty),
7387            empty,
7388            failed: failed.map(str::to_owned),
7389            verified_noop: None,
7390            duration_ms: 0,
7391            folded: false,
7392        }
7393    }
7394
7395    #[test]
7396    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
7397        let mut state = run_state(RunStatus::Blocked);
7398        state.gate = vec![
7399            CommandOutcome {
7400                command: "cargo make check".to_owned(),
7401                code: Some(0),
7402                output_tail: "ok".to_owned(),
7403                duration_ms: 0,
7404                resource_blocked: false,
7405            },
7406            CommandOutcome {
7407                command: "cargo test".to_owned(),
7408                code: Some(101),
7409                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
7410                duration_ms: 0,
7411                resource_blocked: false,
7412            },
7413        ];
7414        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
7415        assert!(d.contains("cargo test"), "{d}");
7416        assert!(
7417            !d.contains("cargo make check"),
7418            "a passing check is not a diagnostic: {d}"
7419        );
7420        assert!(d.contains("assertion failed"), "{d}");
7421    }
7422
7423    #[test]
7424    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
7425        let mut state = run_state(RunStatus::Blocked);
7426        state.event(
7427            "land",
7428            "stopped: the fixer produced no commit while 2 check(s) were failing \
7429             (build, lint); stopping instead of looping on an unchanged tree",
7430        );
7431        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
7432        assert!(d.contains("build"), "{d}");
7433        assert!(d.contains("lint"), "{d}");
7434        assert!(d.contains("fixer produced no commit"), "{d}");
7435    }
7436
7437    #[test]
7438    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
7439        // `describe`'s output becomes `Task::last_error` verbatim, and the
7440        // phone renders that in the same alarm-styled box an ordinary
7441        // failure gets. A bare `verified_noop` there would read exactly like
7442        // the failure this status exists to be told apart from.
7443        let state = run_state(RunStatus::VerifiedNoop);
7444        let d = describe(&state);
7445        assert!(
7446            d.contains("agent-verified no-op"),
7447            "expected the display label, not the wire spelling: {d}"
7448        );
7449        assert!(!d.contains("verified_noop"), "{d}");
7450    }
7451
7452    #[test]
7453    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
7454        // The whole point of the feature: a run held as "no candidate produced
7455        // a change" can mean the implementer actually finished the task and
7456        // only left a clean local tree behind - see AGENTS.md on this exact
7457        // failure mode. The diagnostic has to carry what the agent actually
7458        // said, not just the fact that nothing was there to judge.
7459        let mut state = run_state(RunStatus::Failed);
7460        state.candidates = vec![candidate(
7461            'A',
7462            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
7463            true,
7464            None,
7465        )];
7466        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
7467        assert!(d.contains("candidate A"), "{d}");
7468        assert!(d.contains("tagged v1.2.3"), "{d}");
7469    }
7470
7471    #[test]
7472    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
7473        let mut state = run_state(RunStatus::Failed);
7474        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
7475        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
7476        assert!(d.contains("candidate A"), "{d}");
7477        assert!(d.contains("agent timed out"), "{d}");
7478    }
7479
7480    #[test]
7481    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
7482        // A viable candidate existed, the gate never ran, and nothing land
7483        // said matches - `Task::last_error` is left to explain this one alone.
7484        let mut state = run_state(RunStatus::Failed);
7485        state.candidates = vec![candidate('A', "did the work", false, None)];
7486        assert!(diagnostic(&state).is_none());
7487    }
7488
7489    #[test]
7490    fn diagnostic_is_bounded_however_much_a_run_printed() {
7491        let mut state = run_state(RunStatus::Blocked);
7492        state.gate = vec![
7493            CommandOutcome {
7494                command: "cargo test".to_owned(),
7495                code: Some(101),
7496                output_tail: "x".repeat(50_000),
7497                duration_ms: 0,
7498                resource_blocked: false,
7499            },
7500            CommandOutcome {
7501                command: "cargo clippy".to_owned(),
7502                code: Some(1),
7503                output_tail: "y".repeat(50_000),
7504                duration_ms: 0,
7505                resource_blocked: false,
7506            },
7507        ];
7508        state.candidates = vec![
7509            candidate('A', &"z".repeat(50_000), true, None),
7510            candidate('B', &"w".repeat(50_000), true, None),
7511        ];
7512        let d = diagnostic(&state).expect("plenty here to diagnose");
7513        assert!(
7514            d.len() <= DIAGNOSTIC_MAX,
7515            "diagnostic grew to {} bytes, unbounded",
7516            d.len()
7517        );
7518    }
7519
7520    #[test]
7521    fn selected_delivery_guards_survive_recovery_failure_accounting() {
7522        for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
7523            let mut t = task();
7524            let mut state = run_state(status);
7525            t.pr_recovery = Some(crate::pr_recovery::Selection {
7526                url: "url".into(),
7527                branch: format!("magi/task-{}", t.id),
7528                head: "a".repeat(40),
7529                source_head: None,
7530                source_run: None,
7531                source_proof: None,
7532                disposition: Some(crate::pr_recovery::Disposition::Land),
7533                instruction: t.instruction.clone(),
7534                approved_at: Timestamp::now(),
7535            });
7536            state.pr_recovery = t.pr_recovery.clone();
7537            t.start(state.id.clone());
7538            settle_and_diagnose(
7539                &mut t,
7540                Verdict {
7541                    status,
7542                    left_pr: false,
7543                    quota_hit: false,
7544                    parked: false,
7545                    no_viable_candidates: false,
7546                },
7547                "delivery stopped",
7548                5,
7549                &state,
7550            );
7551            assert_eq!(t.status, TaskStatus::Held);
7552            let reason = t.hold_reason.as_deref().unwrap();
7553            if status == RunStatus::Ready {
7554                assert!(reason.contains("Selected PR delivery is incomplete"));
7555                assert!(t.recovery_budget.is_none());
7556            } else {
7557                assert!(reason.contains("Selected recovery stopped"));
7558                assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
7559            }
7560            assert!(t.pr_recovery.is_some());
7561        }
7562    }
7563
7564    #[test]
7565    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
7566        let mut state = run_state(RunStatus::Blocked);
7567        state.gate = vec![CommandOutcome {
7568            command: "cargo test".to_owned(),
7569            code: Some(101),
7570            output_tail: "assertion failed".to_owned(),
7571            duration_ms: 0,
7572            resource_blocked: false,
7573        }];
7574        let verdict = Verdict {
7575            status: RunStatus::Blocked,
7576            left_pr: false,
7577            quota_hit: false,
7578            parked: false,
7579            no_viable_candidates: false,
7580        };
7581
7582        // Attempt one of two still has a retry coming: no diagnostic yet, the
7583        // task is going to run again and this run's evidence would go stale.
7584        let mut t = task();
7585        t.start("run-1".to_owned());
7586        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
7587        assert_eq!(t.status, TaskStatus::Failed);
7588        assert!(t.diagnostic.is_none());
7589
7590        // Attempt two exhausts the budget: now it is held, and the
7591        // diagnostic is what `magi task show` has to say more than one line.
7592        t.start("run-2".to_owned());
7593        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
7594        assert_eq!(t.status, TaskStatus::Held);
7595        let d = t.diagnostic.expect("a held task must carry its diagnostic");
7596        assert!(d.contains("cargo test"), "{d}");
7597    }
7598
7599    #[test]
7600    fn a_held_task_names_the_open_question_it_is_waiting_on() {
7601        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
7602        // `magi ask` question settled Held with `hold_reason: null`, so the
7603        // notification said nothing actionable. `note_open_question` should
7604        // append the question id to whatever `handed_off` already wrote.
7605        crate::run::pin_test_home();
7606        let home = crate::run::home();
7607        let state = run_state(RunStatus::VerifiedNoop);
7608        let mut q = ask::Question::new(
7609            state.id.clone(),
7610            "implement".to_owned(),
7611            "impl-A".to_owned(),
7612            "is this really a no-op?".to_owned(),
7613            String::new(),
7614            Vec::new(),
7615        );
7616        Questions::at(home.join("questions")).put(&mut q).unwrap();
7617
7618        let verdict = Verdict {
7619            status: RunStatus::VerifiedNoop,
7620            left_pr: false,
7621            quota_hit: false,
7622            parked: false,
7623            no_viable_candidates: false,
7624        };
7625        let mut t = task();
7626        t.start(state.id.clone());
7627        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
7628
7629        assert_eq!(t.status, TaskStatus::Held);
7630        let reason = t.hold_reason.expect("a held task must record why");
7631        assert!(
7632            reason.starts_with("run ended agent-verified no-op"),
7633            "the original settle reason must survive unchanged: {reason}"
7634        );
7635        assert!(
7636            reason.contains(q.short()),
7637            "the open question's id must be named so the notice is actionable: {reason}"
7638        );
7639    }
7640
7641    #[test]
7642    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
7643        crate::run::pin_test_home();
7644        let state = run_state(RunStatus::VerifiedNoop);
7645
7646        let verdict = Verdict {
7647            status: RunStatus::VerifiedNoop,
7648            left_pr: false,
7649            quota_hit: false,
7650            parked: false,
7651            no_viable_candidates: false,
7652        };
7653        let mut t = task();
7654        t.start(state.id.clone());
7655        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
7656
7657        assert_eq!(t.status, TaskStatus::Held);
7658        assert_eq!(
7659            t.hold_reason.as_deref(),
7660            Some("run ended agent-verified no-op"),
7661            "nothing to append when the question was already answered or never asked"
7662        );
7663    }
7664
7665    #[test]
7666    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
7667        crate::run::pin_test_home();
7668        let mut first = run_state(RunStatus::Blocked);
7669        first.id = "20260101-000000-sup1".to_owned();
7670        first.save().unwrap();
7671        let mut second = run_state(RunStatus::Merged);
7672        second.id = "20260101-000000-sup2".to_owned();
7673        second.save().unwrap();
7674
7675        let mut t = task();
7676        t.runs = vec![first.id.clone(), second.id.clone()];
7677        t.status = TaskStatus::Done;
7678
7679        supersede_prior_runs(&t, &crate::run::home());
7680
7681        assert_eq!(
7682            RunState::load(&first.id).unwrap().status,
7683            RunStatus::Superseded,
7684            "the first attempt's Blocked no longer needs anyone's attention"
7685        );
7686        assert_eq!(
7687            RunState::load(&second.id).unwrap().status,
7688            RunStatus::Merged,
7689            "the run that actually succeeded is left exactly as it was"
7690        );
7691    }
7692
7693    #[test]
7694    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
7695        // `is_working_on` alone only proves a *daemon* claim; a `magi run
7696        // --resume` invoked by hand outside the daemon never touches
7697        // `daemon.json` at all, so it would look identical to a genuinely
7698        // idle run without also consulting `RunState::liveness`, which reads
7699        // this run's own recorded `driver_pid` instead.
7700        crate::run::pin_test_home();
7701        let mut first = run_state(RunStatus::Blocked);
7702        first.id = "20260101-000000-sup9".to_owned();
7703        // This test process's own pid: guaranteed alive without needing a
7704        // real second process or daemon.
7705        first.driver_pid = Some(std::process::id());
7706        first.driver_started_at = Some(
7707            crate::proc::process_started_at(std::process::id())
7708                .expect("this test process's own start time must be queryable"),
7709        );
7710        first.save().unwrap();
7711        let mut second = run_state(RunStatus::Merged);
7712        second.id = "20260101-000000-supa".to_owned();
7713        second.save().unwrap();
7714
7715        let mut t = task();
7716        t.runs = vec![first.id.clone(), second.id.clone()];
7717        t.status = TaskStatus::Done;
7718
7719        supersede_prior_runs(&t, &crate::run::home());
7720
7721        assert_eq!(
7722            RunState::load(&first.id).unwrap().status,
7723            RunStatus::Blocked,
7724            "a live driver_pid means something is still actually working this run, \
7725             even though no daemon claims it - rewriting under it would just be \
7726             undone the next time that process saves"
7727        );
7728    }
7729
7730    #[test]
7731    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
7732        // The first resweep must skip a still-live attempt exactly like
7733        // `supersede_prior_runs` itself does; a later resweep, once that
7734        // process is no longer actually driving it, is what closes the gap
7735        // `supersede_prior_runs` alone leaves - a task only ever reaches
7736        // `Done` once, so nothing else would ever look at this run again.
7737        let dir = tempfile::tempdir().unwrap();
7738        let home = dir.path().to_path_buf();
7739        let queue = Queue::at(dir.path().join("queue"));
7740
7741        let mut first = run_state(RunStatus::Blocked);
7742        first.id = "20260101-000000-supd".to_owned();
7743        first.driver_pid = Some(std::process::id());
7744        first.driver_started_at = Some(
7745            crate::proc::process_started_at(std::process::id())
7746                .expect("this test process's own start time must be queryable"),
7747        );
7748        first.save_under(&home).unwrap();
7749        let mut second = run_state(RunStatus::Merged);
7750        second.id = "20260101-000000-supe".to_owned();
7751        second.save_under(&home).unwrap();
7752
7753        let mut t = task();
7754        t.runs = vec![first.id.clone(), second.id.clone()];
7755        t.status = TaskStatus::Done;
7756        queue.put(&mut t).unwrap();
7757
7758        resweep_superseded_attempts(&queue, &home);
7759        assert_eq!(
7760            RunState::load_under(&first.id, &home).unwrap().status,
7761            RunStatus::Blocked,
7762            "still live on the first pass, so still untouched"
7763        );
7764
7765        // Stand in for the manual process no longer being the one driving
7766        // this run: same pid (this test process really is still alive), but
7767        // an identity marker that no longer matches it - see
7768        // `RunState::liveness`'s own doc for why a mismatched
7769        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
7770        let mut stale = RunState::load_under(&first.id, &home).unwrap();
7771        stale.driver_started_at = Some("1".to_owned());
7772        stale.save_under(&home).unwrap();
7773
7774        resweep_superseded_attempts(&queue, &home);
7775        assert_eq!(
7776            RunState::load_under(&first.id, &home).unwrap().status,
7777            RunStatus::Superseded,
7778            "the second pass catches up what the first one correctly skipped"
7779        );
7780    }
7781
7782    #[test]
7783    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
7784        crate::run::pin_test_home();
7785        let mut first = run_state(RunStatus::Blocked);
7786        first.id = "20260101-000000-sup3".to_owned();
7787        first.save().unwrap();
7788        let mut second = run_state(RunStatus::Blocked);
7789        second.id = "20260101-000000-sup4".to_owned();
7790        second.save().unwrap();
7791
7792        let mut t = task();
7793        t.runs = vec![first.id.clone(), second.id.clone()];
7794        // Still retrying: nothing about this task's story is settled yet, so
7795        // neither Blocked run may be relabelled, even though a later attempt
7796        // already exists.
7797        t.status = TaskStatus::Failed;
7798
7799        supersede_prior_runs(&t, &crate::run::home());
7800
7801        assert_eq!(
7802            RunState::load(&first.id).unwrap().status,
7803            RunStatus::Blocked
7804        );
7805        assert_eq!(
7806            RunState::load(&second.id).unwrap().status,
7807            RunStatus::Blocked
7808        );
7809    }
7810
7811    #[test]
7812    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
7813        // `magi task done` (or the API's equivalent) can close a task with no
7814        // run of its own ever having succeeded - there is nothing here that
7815        // counts as "the attempt that finished it", so nothing is rewritten.
7816        crate::run::pin_test_home();
7817        let mut first = run_state(RunStatus::Blocked);
7818        first.id = "20260101-000000-sup5".to_owned();
7819        first.save().unwrap();
7820
7821        let mut t = task();
7822        t.runs = vec![first.id.clone()];
7823        t.status = TaskStatus::Done;
7824
7825        supersede_prior_runs(&t, &crate::run::home());
7826
7827        assert_eq!(
7828            RunState::load(&first.id).unwrap().status,
7829            RunStatus::Blocked,
7830            "a single-attempt task has no earlier run to supersede"
7831        );
7832    }
7833
7834    #[test]
7835    fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
7836        // `magi task done` (or the web/conductor equivalents) can close a
7837        // task in any status, including one whose *last* recorded attempt is
7838        // itself still `Blocked`/`Failed` - a manual merge magi's own loop
7839        // never watched, say. `runs.last()` being `Done`-adjacent is not
7840        // proof it actually succeeded, so nothing earlier may be relabelled
7841        // on its say-so alone.
7842        crate::run::pin_test_home();
7843        let mut first = run_state(RunStatus::Blocked);
7844        first.id = "20260101-000000-supb".to_owned();
7845        first.save().unwrap();
7846        let mut second = run_state(RunStatus::Failed);
7847        second.id = "20260101-000000-supc".to_owned();
7848        second.save().unwrap();
7849
7850        let mut t = task();
7851        t.runs = vec![first.id.clone(), second.id.clone()];
7852        t.status = TaskStatus::Done;
7853
7854        supersede_prior_runs(&t, &crate::run::home());
7855
7856        assert_eq!(
7857            RunState::load(&first.id).unwrap().status,
7858            RunStatus::Blocked,
7859            "the task's last attempt never landed, so there is nothing here \
7860             actually superseding it"
7861        );
7862    }
7863
7864    #[test]
7865    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
7866        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
7867        // to look" - `Failed` and `VerifiedNoop` are already their own
7868        // terminal answers and must not be relabelled into a third one.
7869        crate::run::pin_test_home();
7870        let mut failed = run_state(RunStatus::Failed);
7871        failed.id = "20260101-000000-sup6".to_owned();
7872        failed.save().unwrap();
7873        let mut noop = run_state(RunStatus::VerifiedNoop);
7874        noop.id = "20260101-000000-sup7".to_owned();
7875        noop.save().unwrap();
7876        let mut winner = run_state(RunStatus::Ready);
7877        winner.id = "20260101-000000-sup8".to_owned();
7878        winner.save().unwrap();
7879
7880        let mut t = task();
7881        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
7882        t.status = TaskStatus::Done;
7883
7884        supersede_prior_runs(&t, &crate::run::home());
7885
7886        assert_eq!(
7887            RunState::load(&failed.id).unwrap().status,
7888            RunStatus::Failed
7889        );
7890        assert_eq!(
7891            RunState::load(&noop.id).unwrap().status,
7892            RunStatus::VerifiedNoop
7893        );
7894    }
7895
7896    fn approval_question(run: &str) -> ask::Question {
7897        ask::Question::new(
7898            run.to_owned(),
7899            land::APPROVAL_NODE.to_owned(),
7900            "land".to_owned(),
7901            "merge?".to_owned(),
7902            String::new(),
7903            vec!["merge".to_owned(), "hold".to_owned()],
7904        )
7905    }
7906
7907    #[test]
7908    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
7909        crate::run::pin_test_home();
7910        let mut state = run_state(RunStatus::Landing);
7911        state.id = "20260101-000000-fre1".to_owned();
7912        state.parked = true;
7913        state.save().unwrap();
7914        ask::Questions::open()
7915            .put(&mut approval_question(&state.id))
7916            .unwrap();
7917
7918        let mut t = task();
7919        t.runs.push(state.id.clone());
7920        assert_eq!(
7921            land_resume_state(&t),
7922            LandResume::StillWaiting,
7923            "nobody has answered and the timeout has not passed"
7924        );
7925    }
7926
7927    #[test]
7928    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
7929        crate::run::pin_test_home();
7930        let mut state = run_state(RunStatus::Gating);
7931        state.id = "20260101-000000-gt01".to_owned();
7932        state.parked = true;
7933        state.config.graph.answer_timeout = 60;
7934        state.github_text = Some(crate::run::GithubTextAsk {
7935            rewrite: None,
7936            fingerprint: "f".into(),
7937            title: true,
7938            body: false,
7939            categories: vec!["title-language".into()],
7940            question: None,
7941            asks: 1,
7942            resolved: false,
7943            chosen_title: None,
7944            choice: None,
7945        });
7946        state.save().unwrap();
7947        let store = ask::Questions::open();
7948        let mut q = ask::Question::new(
7949            state.id.clone(),
7950            crate::github_text::ASK_NODE.to_owned(),
7951            crate::github_text::ASK_SEAT.to_owned(),
7952            "s".into(),
7953            String::new(),
7954            vec!["use fallback".into()],
7955        );
7956        store.put(&mut q).unwrap();
7957        let mut t = task();
7958        t.runs.push(state.id.clone());
7959        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
7960        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
7961        store.put(&mut q).unwrap();
7962        assert_eq!(land_resume_state(&t), LandResume::Ready);
7963        assert!(!store.get(&q.id).unwrap().status.open());
7964        // Once decided, a parked run is an ordinary candidate again.
7965        state.github_text.as_mut().unwrap().resolved = true;
7966        state.save().unwrap();
7967        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
7968    }
7969
7970    #[test]
7971    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
7972        // `ask::ask_and_wait`'s own deadline used to retire a question
7973        // nobody answered; land's approval bypasses that wait (see
7974        // `land::approval_gate`), so this is now the only place
7975        // `graph.answer_timeout` is enforced for a land approval at all.
7976        crate::run::pin_test_home();
7977        let mut state = run_state(RunStatus::Landing);
7978        state.id = "20260101-000000-exp1".to_owned();
7979        state.parked = true;
7980        state.config.graph.answer_timeout = 60;
7981        state.save().unwrap();
7982
7983        let store = ask::Questions::open();
7984        let mut q = approval_question(&state.id);
7985        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
7986        store.put(&mut q).unwrap();
7987
7988        let mut t = task();
7989        t.runs.push(state.id.clone());
7990        assert_eq!(
7991            land_resume_state(&t),
7992            LandResume::Ready,
7993            "an expired question must not be waited on forever"
7994        );
7995
7996        let after = store.get(&q.id).unwrap();
7997        assert!(
7998            !after.status.open(),
7999            "the question is abandoned, not silently ignored"
8000        );
8001        assert!(
8002            after.resolution().is_none(),
8003            "an abandoned question is not read as a decision"
8004        );
8005    }
8006
8007    #[test]
8008    fn reclaim_settles_a_running_task_against_its_last_run() {
8009        let mut t = task();
8010        t.start("20260904-000000-4043".to_owned());
8011        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
8012        assert_eq!(
8013            t.status,
8014            TaskStatus::Done,
8015            "a run that actually finished must not stay `running` forever"
8016        );
8017    }
8018
8019    #[test]
8020    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
8021        let mut t = task();
8022        t.start("20260904-000000-4043".to_owned());
8023        t.last_error = Some("earlier trouble".to_owned());
8024        let mut state = run_state(RunStatus::Judging);
8025        state.parked = true;
8026        reclaim(&mut t, Some(state), 1, "en");
8027        assert_eq!(t.status, TaskStatus::Parked);
8028        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
8029        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
8030        assert!(t.park_reason.is_some());
8031        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
8032        assert!(!t.fresh_start);
8033        assert!(t.status.runnable());
8034    }
8035
8036    #[test]
8037    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
8038        let mut t = task();
8039        t.start("20260904-000000-4043".to_owned());
8040        t.last_error = Some("earlier trouble".to_owned());
8041        settle(
8042            &mut t,
8043            Verdict {
8044                status: RunStatus::Judging,
8045                left_pr: false,
8046                quota_hit: false,
8047                parked: true,
8048                no_viable_candidates: false,
8049            },
8050            "parked after `judging`",
8051            1,
8052        );
8053        assert_eq!(t.status, TaskStatus::Parked);
8054        assert_eq!(t.attempts, 0);
8055        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
8056        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
8057        assert_eq!(t.schema, crate::queue::SCHEMA);
8058        assert!(
8059            crate::notices::task_held(&t).is_none(),
8060            "a park is not news"
8061        );
8062        t.start("20260904-000000-4043".to_owned());
8063        assert_eq!(t.park_reason, None);
8064    }
8065
8066    #[test]
8067    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
8068        // A blocked run with attempts left goes back to `Failed`, exactly as
8069        // it would from `attempt` itself - `reclaim` must not invent a second
8070        // policy for a task a daemon merely stopped without reporting.
8071        let mut t = task();
8072        t.start("20260904-000000-4043".to_owned());
8073        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
8074        assert_eq!(t.status, TaskStatus::Failed);
8075        assert!(t.status.runnable());
8076    }
8077
8078    #[test]
8079    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
8080        let mut t = task();
8081        t.start("20260904-000000-4043".to_owned());
8082        assert_eq!(t.attempts, 1);
8083        let mut run = run_state(RunStatus::Implementing);
8084        run.id = "20260904-000000-4043".to_owned();
8085        run.begin_pass();
8086        let cause = crate::run::ParkCause::Upgrade {
8087            from: "0.121.0".to_owned(),
8088            to: Some("0.121.1".to_owned()),
8089        };
8090        run.end_pass_parked(cause.clone());
8091        run.parked = true;
8092        let verdict = Verdict {
8093            status: run.status,
8094            left_pr: false,
8095            quota_hit: false,
8096            parked: true,
8097            no_viable_candidates: false,
8098        };
8099        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
8100        assert_eq!(t.attempts, 0);
8101        assert_eq!(t.passes.len(), 1);
8102        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
8103        assert_eq!(t.passes[0].parked, Some(cause));
8104        assert_eq!(t.passes[0].pass_index, 0);
8105
8106        // A resumed pass that then fails spends its attempt, and the earlier
8107        // pass's entry is untouched.
8108        t.start("20260904-000000-4043".to_owned());
8109        run.begin_pass();
8110        run.status = RunStatus::Failed;
8111        let verdict = Verdict {
8112            status: RunStatus::Failed,
8113            left_pr: false,
8114            quota_hit: false,
8115            parked: false,
8116            no_viable_candidates: false,
8117        };
8118        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
8119        assert_eq!(t.passes.len(), 2);
8120        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
8121        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
8122        assert_eq!(t.passes[1].pass_index, 1);
8123        assert_eq!(t.attempts, 1);
8124    }
8125
8126    #[test]
8127    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
8128        let mut t = task();
8129        t.start("20260904-000000-4043".to_owned());
8130        reclaim(&mut t, None, 2, "en");
8131        assert_eq!(t.status, TaskStatus::Held);
8132        assert!(
8133            t.last_error
8134                .as_deref()
8135                .is_some_and(|e| e.contains("running")),
8136            "the operator needs to know why this task was held"
8137        );
8138    }
8139
8140    #[test]
8141    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
8142        let dir = tempfile::tempdir().unwrap();
8143        let queue = Queue::at(dir.path().to_path_buf());
8144
8145        // No run recorded, so this never has to touch `RunState::load`.
8146        let mut orphaned = task();
8147        orphaned.id = "20260904-000000-orph".to_owned();
8148        orphaned.status = TaskStatus::Running;
8149        orphaned.attempts = 1;
8150        queue.put(&mut orphaned).unwrap();
8151
8152        let mut alive = task();
8153        alive.id = "20260904-000000-live".to_owned();
8154        alive.status = TaskStatus::Running;
8155        alive.attempts = 1;
8156        queue.put(&mut alive).unwrap();
8157        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
8158
8159        let mut queued = task();
8160        queued.id = "20260904-000000-wait".to_owned();
8161        queue.put(&mut queued).unwrap();
8162
8163        let reclaimed = reclaim_orphaned_running(&queue, 2);
8164        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
8165
8166        assert_eq!(
8167            queue.get(&orphaned.id).unwrap().status,
8168            TaskStatus::Held,
8169            "nothing was driving it and there was no run to recover"
8170        );
8171        assert_eq!(
8172            queue.get(&alive.id).unwrap().status,
8173            TaskStatus::Running,
8174            "a live claim must protect the task it belongs to"
8175        );
8176        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
8177    }
8178
8179    /// Read a run.json back from an explicit `home`, the same way
8180    /// `reclaim_abandoned_runs` itself does - never through the
8181    /// process-global `RunState::load`, which this test's own `home` (an
8182    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
8183    /// use at all.
8184    fn read_run_under(home: &Path, id: &str) -> RunState {
8185        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
8186        serde_json::from_str(&body).unwrap()
8187    }
8188
8189    #[test]
8190    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
8191        let dir = tempfile::tempdir().unwrap();
8192        let home = dir.path().to_path_buf();
8193        let now = Timestamp::now();
8194        let overrun_seat = || crate::run::ActiveSeat {
8195            node: "implement".to_owned(),
8196            started_at: now - jiff::SignedDuration::new(21_000, 0),
8197            timeout_secs: 3_600,
8198            attempt: 0,
8199            task: None,
8200            command: None,
8201            index: None,
8202            total: None,
8203        };
8204
8205        let mut dead = run_state(RunStatus::Implementing);
8206        dead.id = "20260101-000000-dead".to_owned();
8207        dead.active.insert("impl-A".to_owned(), overrun_seat());
8208        // A `driver_pid` the injected query below confirms gone outright —
8209        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
8210        dead.driver_pid = Some(4242);
8211        dead.save_under(&home).unwrap();
8212
8213        // Same shape, but a live daemon's heartbeat names it: must be left
8214        // exactly alone, however far past its own timeout the seat sits.
8215        let mut alive = run_state(RunStatus::Implementing);
8216        alive.id = "20260101-000000-aliv".to_owned();
8217        alive.active.insert("impl-A".to_owned(), overrun_seat());
8218        alive.save_under(&home).unwrap();
8219        let mut status = Status::new();
8220        status.current = vec![Current {
8221            task: "20260101-000000-task".to_owned(),
8222            run: alive.id.clone(),
8223        }];
8224        write_status_to(&home.join("daemon.json"), &status).unwrap();
8225
8226        // The abandoned seat left an open question behind: nobody is left to
8227        // read an answer once the run is failed, and this must not wait for
8228        // some later daemon startup's own sweep to notice that.
8229        let questions = Questions::at(home.join("questions"));
8230        let mut q = ask::Question::new(
8231            dead.id.clone(),
8232            "implement".to_owned(),
8233            "impl-A".to_owned(),
8234            "Which storage backend?".to_owned(),
8235            String::new(),
8236            vec!["SQLite".to_owned(), "Redis".to_owned()],
8237        );
8238        questions.put(&mut q).unwrap();
8239
8240        let abandoned = reclaim_abandoned_runs_with(
8241            &home,
8242            now,
8243            |pid| if pid == 4242 { Some(false) } else { None },
8244            |_| panic!("a query answering Dead outright needs no identity corroboration"),
8245        );
8246        assert_eq!(abandoned, vec![dead.id.clone()]);
8247
8248        let reloaded = read_run_under(&home, &dead.id);
8249        assert_eq!(reloaded.status, RunStatus::Failed);
8250        assert!(reloaded.active.is_empty());
8251        assert!(
8252            !questions.get(&q.id).unwrap().status.open(),
8253            "the failed run's own open question must be settled in the same pass"
8254        );
8255
8256        let still_alive = read_run_under(&home, &alive.id);
8257        assert_eq!(
8258            still_alive.status,
8259            RunStatus::Implementing,
8260            "a live daemon's claim protects it"
8261        );
8262        assert!(!still_alive.active.is_empty());
8263    }
8264
8265    /// The exact shape a review round flagged as broken: `magi serve` running
8266    /// in this same `home` scans *every* run on disk, including a manual
8267    /// `magi review` / `magi run` this daemon never started and that
8268    /// therefore claims no heartbeat of its own. Before this scan asked
8269    /// `liveness` rather than just `is_working_on`, a manual run whose active
8270    /// seat merely ran a little past its own timeout — the CLI finishing up,
8271    /// its result still being collected — got wiped and failed by a daemon
8272    /// that had nothing to do with it, out from under a process that was
8273    /// still very much running.
8274    #[test]
8275    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
8276        let dir = tempfile::tempdir().unwrap();
8277        let home = dir.path().to_path_buf();
8278        let now = Timestamp::now();
8279
8280        let mut manual = run_state(RunStatus::Reviewing);
8281        manual.id = "20260101-000000-manl".to_owned();
8282        manual.active.insert(
8283            "review-1".to_owned(),
8284            crate::run::ActiveSeat {
8285                node: "review".to_owned(),
8286                started_at: now - jiff::SignedDuration::new(21_000, 0),
8287                timeout_secs: 3_600,
8288                attempt: 0,
8289                task: None,
8290                command: None,
8291                index: None,
8292                total: None,
8293            },
8294        );
8295        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
8296        // but a real, still-running process: `liveness` must corroborate this
8297        // as `Live`, not read the missing daemon claim as death.
8298        manual.driver_pid = Some(4242);
8299        manual.driver_started_at = Some("1790000000".to_owned());
8300        manual.save_under(&home).unwrap();
8301
8302        let abandoned = reclaim_abandoned_runs_with(
8303            &home,
8304            now,
8305            |pid| if pid == 4242 { Some(true) } else { None },
8306            |pid| {
8307                if pid == 4242 {
8308                    Some("1790000000".to_owned())
8309                } else {
8310                    None
8311                }
8312            },
8313        );
8314        assert!(
8315            abandoned.is_empty(),
8316            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
8317        );
8318
8319        let reloaded = read_run_under(&home, &manual.id);
8320        assert_eq!(reloaded.status, RunStatus::Reviewing);
8321        assert!(!reloaded.active.is_empty());
8322    }
8323
8324    #[test]
8325    fn an_already_claimed_task_is_skipped_rather_than_failed() {
8326        let dir = tempfile::tempdir().unwrap();
8327        let queue = Queue::at(dir.path().to_path_buf());
8328        let mut only = task();
8329        queue.put(&mut only).unwrap();
8330
8331        let _elsewhere = queue.claim(&only.id).unwrap();
8332        let candidates = runnable(&queue);
8333        assert_eq!(candidates.len(), 1, "the task is still runnable");
8334        assert!(
8335            queue.claim(&candidates[0].id).is_err(),
8336            "the loop cannot take a claim somebody else holds"
8337        );
8338
8339        let after = queue.get(&only.id).unwrap();
8340        assert_eq!(after.status, TaskStatus::Queued);
8341        assert_eq!(
8342            after.attempts, 0,
8343            "losing the race is not an attempt at the task"
8344        );
8345        assert_eq!(after.last_error, None);
8346    }
8347
8348    #[test]
8349    fn the_status_file_round_trips_and_its_heartbeat_advances() {
8350        let dir = tempfile::tempdir().unwrap();
8351        let path = dir.path().join("daemon.json");
8352
8353        let mut status = Status::new();
8354        status.idle = false;
8355        status.completed = 7;
8356        status.current = vec![Current {
8357            task: "20260902-000000-t111".to_owned(),
8358            run: "20260902-000001-r111".to_owned(),
8359        }];
8360        write_status_to(&path, &status).unwrap();
8361        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
8362        assert_eq!(first.schema, SCHEMA);
8363        assert_eq!(first.pid, std::process::id());
8364        assert!(!first.idle);
8365        assert_eq!(first.completed, 7);
8366        assert_eq!(first.current, status.current);
8367        assert!(
8368            !path.with_extension("json.tmp").exists(),
8369            "the temp file is renamed, not left behind"
8370        );
8371
8372        std::thread::sleep(Duration::from_millis(5));
8373        status.updated_at = Timestamp::now();
8374        status.polls = 3;
8375        write_status_to(&path, &status).unwrap();
8376        let second: Status =
8377            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
8378        assert!(
8379            second.updated_at > first.updated_at,
8380            "a reader can only detect staleness if the heartbeat moves"
8381        );
8382        assert_eq!(
8383            second.started_at, first.started_at,
8384            "the start time is not a heartbeat"
8385        );
8386        assert_eq!(second.polls, 3);
8387    }
8388
8389    #[test]
8390    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
8391        let dir = tempfile::tempdir().unwrap();
8392
8393        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
8394
8395        let mut status = Status::new();
8396        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
8397        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8398        let stale = read_status(dir.path()).unwrap();
8399        assert!(
8400            !stale.running(Timestamp::now()),
8401            "a minute without a heartbeat is a dead daemon, not a busy one"
8402        );
8403        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
8404
8405        status.updated_at = Timestamp::now();
8406        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8407        let fresh = read_status(dir.path()).unwrap();
8408        assert!(fresh.running(Timestamp::now()));
8409    }
8410
8411    #[test]
8412    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
8413        let dir = tempfile::tempdir().unwrap();
8414        let now = Timestamp::now();
8415        let mine = "20260903-080619-01c2";
8416
8417        assert!(
8418            !is_working_on(dir.path(), mine, now),
8419            "no status file means nobody is working on anything"
8420        );
8421
8422        let mut status = Status::new();
8423        status.current = vec![Current {
8424            task: "20260903-080340-0167".to_owned(),
8425            run: mine.to_owned(),
8426        }];
8427        status.updated_at = now;
8428        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8429        assert!(is_working_on(dir.path(), mine, now));
8430        assert!(
8431            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
8432            "a daemon busy with one run is not working on another"
8433        );
8434
8435        // A killed daemon stops writing heartbeats but leaves the file behind
8436        // naming the run it died in. That run must not be undeletable forever.
8437        status.updated_at = now - jiff::SignedDuration::from_secs(600);
8438        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8439        assert!(
8440            !is_working_on(dir.path(), mine, now),
8441            "a stale heartbeat is a dead daemon, so its run is a leftover"
8442        );
8443    }
8444
8445    #[test]
8446    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
8447        let dir = tempfile::tempdir().unwrap();
8448        let now = Timestamp::now();
8449
8450        assert!(
8451            !is_working_on_short(dir.path(), "01c2", now),
8452            "no status file means nobody is working on anything"
8453        );
8454
8455        let mut status = Status::new();
8456        status.current = vec![Current {
8457            task: "20260903-080340-0167".to_owned(),
8458            run: "20260903-080619-01c2".to_owned(),
8459        }];
8460        status.updated_at = now;
8461        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8462        assert!(
8463            is_working_on_short(dir.path(), "01c2", now),
8464            "the run's short id is the last block of its full id"
8465        );
8466        assert!(
8467            !is_working_on_short(dir.path(), "3cbf", now),
8468            "a daemon busy with one worktree bay is not working on another"
8469        );
8470    }
8471
8472    #[test]
8473    fn a_newer_status_file_still_yields_a_reading() {
8474        let dir = tempfile::tempdir().unwrap();
8475        // A field this build has never heard of must not turn the reading into
8476        // nothing at all; that is the whole reason the reader is permissive.
8477        std::fs::write(
8478            dir.path().join("daemon.json"),
8479            serde_json::json!({
8480                "schema": 2,
8481                "updated_at": Timestamp::now().to_string(),
8482                "idle": true,
8483                "surprise": { "nested": [1, 2, 3] },
8484            })
8485            .to_string(),
8486        )
8487        .unwrap();
8488
8489        let reading = read_status(dir.path()).expect("a forward-compatible read");
8490        assert!(reading.running(Timestamp::now()));
8491        assert!(reading.idle);
8492        assert!(reading.current.is_empty());
8493    }
8494
8495    #[test]
8496    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
8497        // A daemon started before `current` became a list keeps writing this
8498        // shape on every heartbeat until it is restarted. A rolling upgrade
8499        // - a newer `magi web` or `magi doctor` reading an older `magi
8500        // serve`'s heartbeat - must still see the run it is on, not "no
8501        // daemon" from a type mismatch failing the whole struct.
8502        let dir = tempfile::tempdir().unwrap();
8503        std::fs::write(
8504            dir.path().join("daemon.json"),
8505            serde_json::json!({
8506                "schema": 1,
8507                "pid": 4242,
8508                "updated_at": Timestamp::now().to_string(),
8509                "idle": false,
8510                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
8511                "completed": 3,
8512                "polls": 9,
8513            })
8514            .to_string(),
8515        )
8516        .unwrap();
8517
8518        let reading = read_status(dir.path()).expect("an older shape must still parse");
8519        assert!(reading.running(Timestamp::now()));
8520        assert_eq!(
8521            reading.current,
8522            vec![Current {
8523                task: "20260902-140501-aaaa".to_owned(),
8524                run: "20260902-140502-bbbb".to_owned(),
8525            }]
8526        );
8527    }
8528
8529    #[test]
8530    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
8531        let dir = tempfile::tempdir().unwrap();
8532        std::fs::write(
8533            dir.path().join("daemon.json"),
8534            serde_json::json!({
8535                "schema": 1,
8536                "updated_at": Timestamp::now().to_string(),
8537                "idle": true,
8538                "current": null,
8539            })
8540            .to_string(),
8541        )
8542        .unwrap();
8543        let with_null = read_status(dir.path()).expect("null must still parse");
8544        assert!(with_null.current.is_empty());
8545
8546        std::fs::write(
8547            dir.path().join("daemon.json"),
8548            serde_json::json!({
8549                "schema": 1,
8550                "updated_at": Timestamp::now().to_string(),
8551                "idle": true,
8552            })
8553            .to_string(),
8554        )
8555        .unwrap();
8556        let absent = read_status(dir.path()).expect("a missing field must still parse");
8557        assert!(absent.current.is_empty());
8558    }
8559
8560    #[test]
8561    fn a_task_without_a_repository_runs_in_the_daemons_default() {
8562        let fallback = Path::new("/default");
8563        let mut blank = task();
8564        blank.repo = PathBuf::new();
8565        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
8566        let mut dot = task();
8567        dot.repo = PathBuf::from(".");
8568        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
8569        assert_eq!(
8570            repo_for(&task(), fallback),
8571            PathBuf::from("/repo"),
8572            "a task that names a repository keeps it"
8573        );
8574    }
8575
8576    #[test]
8577    fn task_implementers_edit_inherits_daemon_config_and_merge() {
8578        let dir = tempfile::tempdir().unwrap();
8579        let path = dir.path().join("explicit.toml");
8580        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
8581        let opts = Opts {
8582            config: Some(path),
8583            merge: Some("none".into()),
8584            ..Default::default()
8585        };
8586        let mut t = task();
8587        t.set_implementers(
8588            2,
8589            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
8590                .unwrap(),
8591        )
8592        .unwrap();
8593        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
8594        assert_eq!(cfg.graph.implementers, 2);
8595        assert_eq!(cfg.graph.judges, 1);
8596        assert_eq!(cfg.merge.mode, MergeMode::None);
8597        t.set_implementers(1, &cfg).unwrap();
8598        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
8599        apply_task_implementers(&mut cfg, &t);
8600        assert_eq!(cfg.graph.implementers, 1);
8601        assert_eq!(cfg.graph.judges, 1);
8602        assert_eq!(cfg.merge.mode, MergeMode::None);
8603    }
8604
8605    #[test]
8606    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
8607        let dir = tempfile::tempdir().unwrap();
8608        let repo = dir.path().join("repo");
8609        std::fs::create_dir(&repo).unwrap();
8610        std::fs::write(
8611            repo.join("magi.toml"),
8612            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
8613        )
8614        .unwrap();
8615        let daemon_config = dir.path().join("daemon.toml");
8616        std::fs::write(
8617            &daemon_config,
8618            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
8619        )
8620        .unwrap();
8621        let opts = Opts {
8622            config: Some(daemon_config),
8623            merge: Some("pr".into()),
8624            ..Default::default()
8625        };
8626        let q = Queue::at(dir.path().join("queue"));
8627        let validation: Config =
8628            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
8629                .unwrap();
8630        // No provenance field on legacy direct tasks: both shapes stay isolated.
8631        for record in ["{}", r#"{"candidates":2}"#] {
8632            let overrides = serde_json::from_str(record).unwrap();
8633            let filing = crate::direct::Filing {
8634                instruction: "work".into(),
8635                title: "direct".into(),
8636                repo: repo.clone(),
8637                source: crate::queue::Source::Human,
8638                solo: false,
8639                overrides,
8640                review_of: None,
8641            };
8642            let filed =
8643                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
8644            let crate::direct::Filed::Standalone {
8645                mut task,
8646                claim: _claim,
8647            } = filed
8648            else {
8649                panic!("local filing")
8650            };
8651            let before = prepare_for(&repo, &opts, &task).unwrap();
8652            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
8653            assert_eq!(
8654                before.merge.mode,
8655                MergeMode::None,
8656                "daemon --merge must not leak"
8657            );
8658            for n in [2, 1, 2] {
8659                task.set_implementers(n, &validation).unwrap();
8660                q.put(&mut task).unwrap();
8661                task = q.get(&task.id).unwrap();
8662                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
8663                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
8664                apply_task_implementers(&mut cfg, &task);
8665                assert_eq!(cfg.graph.implementers, usize::from(n));
8666                assert_eq!(cfg.graph.judges, 2);
8667                assert_eq!(cfg.merge.mode, MergeMode::None);
8668            }
8669        }
8670    }
8671
8672    #[test]
8673    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
8674        let cfg: Config =
8675            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
8676                .unwrap();
8677        let mut t = task();
8678        t.review_of = Some("review-target".into());
8679        t.hold_manual(Some("retry".into()));
8680        let mut previous = RunState::new(
8681            PathBuf::from("/repo"),
8682            "main".into(),
8683            "abc1234".into(),
8684            "review".into(),
8685            cfg.clone(),
8686        );
8687        previous.config.graph.implementers = 2;
8688        for count in [1, 3] {
8689            t.set_implementers(count, &cfg).unwrap();
8690            t.release();
8691            assert_eq!(t.review_of.as_deref(), Some("review-target"));
8692            for proposed in [
8693                Starter::Resume(previous.id.clone()),
8694                Starter::Review("recovery-target".into()),
8695            ] {
8696                assert_eq!(
8697                    starter_with_implementers(&t, Some(&previous), proposed),
8698                    Starter::Review("review-target".into())
8699                );
8700            }
8701            let mut configured = cfg.clone();
8702            apply_task_implementers(&mut configured, &t);
8703            assert_eq!(configured.graph.implementers, usize::from(count));
8704            assert_eq!(previous.config.graph.implementers, 2);
8705        }
8706    }
8707
8708    #[test]
8709    fn task_implementers_dispatch_and_resume_agree() {
8710        let mut t = task();
8711        let cfg: crate::config::Config =
8712            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
8713                .unwrap();
8714        let mut run = RunState::new(
8715            PathBuf::from("/repo"),
8716            "main".into(),
8717            "abc1234".into(),
8718            "work".into(),
8719            cfg.clone(),
8720        );
8721        run.config.graph.implementers = 2;
8722        for n in [2, 1, 3, 2] {
8723            t.set_implementers(n, &cfg).unwrap();
8724            let mut dispatched = cfg.clone();
8725            apply_task_implementers(&mut dispatched, &t);
8726            assert_eq!(dispatched.graph.implementers, usize::from(n));
8727            assert_eq!(implementers_match(&t, &run), n == 2);
8728            for proposed in [
8729                Starter::Resume(run.id.clone()),
8730                Starter::Review("old-branch".into()),
8731            ] {
8732                let expected = if n == 2 {
8733                    proposed.clone()
8734                } else {
8735                    Starter::Start
8736                };
8737                assert_eq!(
8738                    starter_with_implementers(&t, Some(&run), proposed),
8739                    expected
8740                );
8741            }
8742            assert_eq!(
8743                run.config.graph.implementers, 2,
8744                "history must not be rewritten"
8745            );
8746        }
8747        t.solo = false;
8748        t.overrides = None;
8749        assert!(implementers_match(&t, &run));
8750    }
8751
8752    #[test]
8753    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
8754        // Three seats said out loud. What `solo` promises is one candidate
8755        // *whatever the config asks for*, so the contrast has to be a number
8756        // this test owns - it used to be `Config::default()`'s, which became
8757        // 1 when one implementation became the default and left the two
8758        // halves of this test asserting the same thing.
8759        let mut solo_cfg = Config::default();
8760        solo_cfg.graph.implementers = 3;
8761        let mut solo_task = task();
8762        solo_task.solo = true;
8763        apply_task_implementers(&mut solo_cfg, &solo_task);
8764        assert_eq!(solo_cfg.graph.implementers, 1);
8765
8766        let mut plain_cfg = Config::default();
8767        plain_cfg.graph.implementers = 3;
8768        let plain_task = task();
8769        assert!(!plain_task.solo);
8770        apply_task_implementers(&mut plain_cfg, &plain_task);
8771        assert_eq!(
8772            plain_cfg.graph.implementers, 3,
8773            "a task that did not ask to run alone keeps the config's candidates"
8774        );
8775    }
8776
8777    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
8778        QuotaLoss {
8779            seat: seat.into(),
8780            node: "judge".into(),
8781            at: at.parse().unwrap(),
8782            reset: reset.map(str::to_string),
8783        }
8784    }
8785
8786    #[test]
8787    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
8788        let old: Vec<QuotaLoss> = (1..=4)
8789            .map(|i| {
8790                loss(
8791                    &format!("judge-{i}"),
8792                    "2026-09-23T05:23:00Z",
8793                    Some("2:40pm (Asia/Tokyo)"),
8794                )
8795            })
8796            .collect();
8797        let fresh = losses_this_attempt(&old, &old);
8798        assert!(fresh.is_empty());
8799        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
8800        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
8801    }
8802
8803    #[test]
8804    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
8805        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
8806        let now = Timestamp::now();
8807        let mut after = old.clone();
8808        after.push(loss("judge-2", &now.to_string(), None));
8809        let fresh = losses_this_attempt(&old, &after);
8810        assert_eq!(fresh, vec![after[1].clone()]);
8811        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
8812        assert_eq!(
8813            until,
8814            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
8815        );
8816    }
8817
8818    #[test]
8819    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
8820        // `recover_stall` removes judge-1's loss and the retry then hits quota
8821        // again: the vector is the same length, so an index diff sees nothing.
8822        let before = vec![
8823            loss("judge-1", "2026-09-23T05:23:00Z", None),
8824            loss("judge-2", "2026-09-23T05:24:00Z", None),
8825        ];
8826        let after = vec![
8827            loss("judge-2", "2026-09-23T05:24:00Z", None),
8828            loss("judge-1", "2026-09-24T01:00:00Z", None),
8829        ];
8830        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
8831    }
8832
8833    #[test]
8834    fn merge_overrides_are_parsed_or_refused() {
8835        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
8836        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
8837        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
8838        assert!(merge_mode("squash").is_err());
8839    }
8840
8841    #[test]
8842    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
8843        let now = Timestamp::now();
8844        let fallback = Duration::from_secs(300);
8845        let cap = Duration::from_secs(1800);
8846
8847        // No reset hint at all: the fallback.
8848        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
8849
8850        // A reset ten minutes out, well inside the cap: waited for exactly.
8851        let soon = now + jiff::SignedDuration::from_secs(600);
8852        assert_eq!(
8853            quota_wait(Some(soon), now, fallback, cap),
8854            Duration::from_secs(600)
8855        );
8856
8857        // A reset already in the past is not trusted: the fallback, not a
8858        // zero or negative wait that would spin the loop right back around.
8859        let past = now - jiff::SignedDuration::from_secs(60);
8860        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
8861
8862        // A reset further out than the cap is trusted for direction but not
8863        // for magnitude: a parsing slip must not sleep the loop for a day.
8864        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
8865        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
8866    }
8867
8868    #[test]
8869    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
8870        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
8871
8872        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
8873        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
8874
8875        // Same clock reading, but it has already gone by today: read as
8876        // tomorrow's, since the CLI would not still be reporting a limit past
8877        // its own stated reset.
8878        let already_past =
8879            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
8880        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
8881
8882        assert!(
8883            parse_reset_hint("session limit reached", now, now).is_none(),
8884            "free text with no recognised shape is not guessed at"
8885        );
8886        assert!(
8887            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
8888            "an unresolvable zone name is not guessed at either"
8889        );
8890    }
8891
8892    #[test]
8893    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
8894        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
8895
8896        let at = parse_reset_hint(
8897            "You've hit your usage limit. Visit \
8898             https://chatgpt.com/codex/settings/usage to purchase more \
8899             credits or try again at Sep 19th, 2026 5:10 PM.",
8900            now,
8901            now,
8902        )
8903        .expect("the codex reset wording is a recognised shape");
8904        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
8905
8906        // The month is explicit, so a date already earlier in the same
8907        // sentence-implied year than `now` is trusted as written rather than
8908        // rolled forward a year the way the bracketed shape rolls a
8909        // same-day clock reading to tomorrow.
8910        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
8911            .expect("an explicit year needs no rollover");
8912        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
8913
8914        assert!(
8915            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
8916            "a two-digit year is not the documented shape and is not guessed at"
8917        );
8918        assert!(
8919            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
8920            "a four-letter month name is not the documented three-letter abbreviation"
8921        );
8922        assert!(
8923            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
8924            "an explicit zone on the dated shape is a format nobody has \
8925             documented, and is refused rather than guessed at as UTC"
8926        );
8927    }
8928
8929    #[test]
8930    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
8931        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
8932        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
8933
8934        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
8935        assert_eq!(at.as_second() - recorded.as_second(), 3769);
8936
8937        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
8938        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
8939
8940        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
8941            assert!(
8942                parse_reset_hint(bad, now, recorded).is_none(),
8943                "{bad:?} must not be guessed at"
8944            );
8945        }
8946    }
8947
8948    /// A loop whose queue lives in a temp tree and whose poll interval is far
8949    /// longer than the test's patience, so anything that waits out a poll
8950    /// instead of noticing the stop fails rather than merely being slow.
8951    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
8952        let config = dir.join("magi.toml");
8953        std::fs::write(
8954            &config,
8955            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
8956        )
8957        .unwrap();
8958        let opts = Opts {
8959            poll: Duration::from_secs(30),
8960            config: Some(config),
8961            // The explicit fixture config keeps startup cleanup from reading
8962            // machine configuration. This fictional repository likewise
8963            // keeps any best-effort git cleanup away from this checkout.
8964            repo: dir.join("repo"),
8965            ..Opts::default()
8966        };
8967        // The status file goes in a directory that does not exist yet, so its
8968        // creation is itself evidence the loop published one. `worktrees`
8969        // must be just as fictional: the janitor reclaims worktrees under it
8970        // for real, and a test that let it fall through to
8971        // `crate::run::default_worktree_root()` would have it reclaim
8972        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
8973        // which is exactly what happened before this function took the
8974        // parameter at all.
8975        let home = dir.join("home");
8976        let worktrees = dir.join("wt");
8977        (
8978            opts,
8979            Queue::at(dir.join("queue")),
8980            home.join("daemon.json"),
8981            home,
8982            worktrees,
8983        )
8984    }
8985
8986    #[test]
8987    fn a_stop_is_idempotent_and_once_set_stays_set() {
8988        let stop = Stop::new();
8989        assert!(!stop.stopped());
8990
8991        stop.stop();
8992        assert!(stop.stopped());
8993        stop.stop();
8994        assert!(stop.stopped(), "a second stop is not a toggle");
8995
8996        let shared = stop.clone();
8997        assert!(
8998            shared.stopped(),
8999            "a clone is the same stop; that is how the loop and its caller share one"
9000        );
9001    }
9002
9003    #[test]
9004    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
9005        let stop = Stop::new();
9006        stop.enter();
9007        assert!(
9008            !stop.finishing(),
9009            "a busy loop nobody has asked to stop is just running"
9010        );
9011
9012        stop.stop();
9013        assert!(
9014            stop.finishing(),
9015            "a stop asked for mid-run has not landed until the run is settled"
9016        );
9017
9018        stop.exit();
9019        assert!(
9020            !stop.finishing(),
9021            "once the run is settled the stop has landed and there is nothing to finish"
9022        );
9023    }
9024
9025    #[test]
9026    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
9027        let stop = Stop::new();
9028        stop.enter();
9029        stop.enter();
9030        stop.stop();
9031        assert!(stop.finishing(), "two runs still in flight");
9032
9033        stop.exit();
9034        assert!(
9035            stop.finishing(),
9036            "one run finished, but a sibling is still working"
9037        );
9038
9039        stop.exit();
9040        assert!(
9041            !stop.finishing(),
9042            "the last run out is what actually lands the stop"
9043        );
9044    }
9045
9046    #[tokio::test]
9047    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
9048        let dir = tempfile::tempdir().unwrap();
9049        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
9050        let stop = Stop::new();
9051        stop.stop();
9052
9053        let began = std::time::Instant::now();
9054        tokio::time::timeout(
9055            Duration::from_secs(2),
9056            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
9057        )
9058        .await
9059        .expect("a stopped loop must return, not sit out its poll interval")
9060        .expect("the loop's own setup and teardown must not fail");
9061        assert!(
9062            began.elapsed() < opts.poll,
9063            "returned only after {:?}, which is a poll interval, not a stop",
9064            began.elapsed()
9065        );
9066    }
9067
9068    #[tokio::test]
9069    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
9070        let dir = tempfile::tempdir().unwrap();
9071        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
9072        let stop = Stop::new();
9073
9074        // Asked for after the loop is already parked on its empty queue, which
9075        // is the case an operator tapping stop on a phone actually hits.
9076        let asker = {
9077            let stop = stop.clone();
9078            tokio::spawn(async move {
9079                tokio::time::sleep(Duration::from_millis(20)).await;
9080                stop.stop();
9081            })
9082        };
9083
9084        let began = std::time::Instant::now();
9085        tokio::time::timeout(
9086            Duration::from_secs(2),
9087            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
9088        )
9089        .await
9090        .expect("a stop asked for while idle must wake the wait")
9091        .expect("the loop's own setup and teardown must not fail");
9092        asker.await.unwrap();
9093        assert!(
9094            began.elapsed() < opts.poll,
9095            "returned only after {:?}, so the stop waited on the sleep",
9096            began.elapsed()
9097        );
9098    }
9099
9100    #[tokio::test]
9101    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
9102        let dir = tempfile::tempdir().unwrap();
9103        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
9104        let stop = Stop::new();
9105        stop.stop();
9106
9107        tokio::time::timeout(
9108            Duration::from_secs(2),
9109            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
9110        )
9111        .await
9112        .expect("a stopped loop must return")
9113        .expect("the loop's own setup and teardown must not fail");
9114
9115        assert!(
9116            home.is_dir(),
9117            "the loop did publish a status file, so its removal is the teardown and not an absence"
9118        );
9119        assert!(
9120            !status_file.exists(),
9121            "a stopped loop clears its status file"
9122        );
9123        assert!(
9124            read_status(&home).is_none(),
9125            "a reader must see no daemon at all, not a heartbeat that merely stopped"
9126        );
9127    }
9128
9129    #[tokio::test]
9130    async fn once_runs_startup_housekeeping_before_an_empty_queue_exits() {
9131        let dir = tempfile::tempdir().unwrap();
9132        let (mut opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
9133        opts.once = true;
9134
9135        let mut settled = RunState::new(
9136            dir.path().join("repo"),
9137            "main".to_owned(),
9138            "abc1234".to_owned(),
9139            "fixture".to_owned(),
9140            Config::default(),
9141        );
9142        settled.status = RunStatus::Ready;
9143        let run_dir = home.join("runs").join(&settled.id);
9144        std::fs::create_dir_all(&run_dir).unwrap();
9145        std::fs::write(
9146            run_dir.join("run.json"),
9147            serde_json::to_string_pretty(&settled).unwrap(),
9148        )
9149        .unwrap();
9150        let questions = Questions::at(home.join("questions"));
9151        let mut question = ask::Question::new(
9152            settled.id.clone(),
9153            "review".to_owned(),
9154            "reviewer-1".to_owned(),
9155            "Continue?".to_owned(),
9156            String::new(),
9157            Vec::new(),
9158        );
9159        questions.put(&mut question).unwrap();
9160
9161        drive(&opts, &queue, &status_file, &home, &worktrees, &Stop::new())
9162            .await
9163            .unwrap();
9164
9165        assert_eq!(
9166            questions.get(&question.id).unwrap().status,
9167            ask::QuestionStatus::Abandoned,
9168            "an empty --once drain still performs startup question cleanup"
9169        );
9170    }
9171
9172    #[test]
9173    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
9174        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
9175
9176        assert!(
9177            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
9178            "never checked before: due at once"
9179        );
9180
9181        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
9182        assert!(
9183            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
9184            "well inside the interval: not due yet"
9185        );
9186
9187        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
9188        assert!(
9189            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
9190            "exactly at the edge: not yet due, same convention as `clean::due`"
9191        );
9192
9193        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
9194        assert!(
9195            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
9196            "past the interval: due again"
9197        );
9198    }
9199
9200    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
9201    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
9202    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
9203    /// and the congestion test below both need, and must not drift apart.
9204    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
9205        let config = dir.join("magi.toml");
9206        // A literal (single-quoted) TOML string, not a basic one: the cache
9207        // path is a Windows path full of backslashes, and a basic string
9208        // would have TOML try to interpret `\U` (from `\Users\...`) as a
9209        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
9210        // `{{ vars.cache }}` rendering documents.
9211        std::fs::write(
9212            &config,
9213            format!(
9214                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
9215                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
9216                cache_dir.display()
9217            ),
9218        )
9219        .unwrap();
9220        Opts {
9221            config: Some(config),
9222            repo: dir.join("repo"),
9223            ..Opts::default()
9224        }
9225    }
9226
9227    #[tokio::test]
9228    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
9229        let dir = tempfile::tempdir().unwrap();
9230        let home = dir.path().join("home");
9231        let cache_dir = dir.path().join("cache");
9232        std::fs::create_dir_all(&cache_dir).unwrap();
9233        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
9234        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
9235
9236        // Nobody has asked this daemon to stop, which is the ordinary case;
9237        // the skip that a stop buys is asserted by its own test below.
9238        let running = Stop::new();
9239        let mut last_checked = None;
9240        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
9241        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
9242            .await;
9243        assert_eq!(
9244            crate::disk::dir_size(&cache_dir),
9245            0,
9246            "over the cap on the first check ever: pruned at once, no idle queue required"
9247        );
9248        assert_eq!(last_checked, Some(t0));
9249
9250        // A fresh oversized file lands, but the next check is not due yet.
9251        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
9252        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
9253        maybe_prune_cache_between_runs(
9254            &opts.repo,
9255            &opts,
9256            &home,
9257            &running,
9258            &mut last_checked,
9259            too_soon,
9260        )
9261        .await;
9262        assert_eq!(
9263            crate::disk::dir_size(&cache_dir),
9264            10,
9265            "too soon since the last check: left alone rather than rescanned every call"
9266        );
9267        assert_eq!(
9268            last_checked,
9269            Some(t0),
9270            "an idle check does not reset the clock"
9271        );
9272
9273        // Once the interval elapses, the same oversized cache is caught again.
9274        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
9275        maybe_prune_cache_between_runs(
9276            &opts.repo,
9277            &opts,
9278            &home,
9279            &running,
9280            &mut last_checked,
9281            due_again,
9282        )
9283        .await;
9284        assert_eq!(
9285            crate::disk::dir_size(&cache_dir),
9286            0,
9287            "due again: pruned back under the cap"
9288        );
9289    }
9290
9291    /// A stop must not queue behind housekeeping. The prune below is a
9292    /// synchronous walk of the whole cache with no await point in it, so a
9293    /// loop that entered it could not get back to its own `stopped()` test
9294    /// until the walk finished - and because no run is in flight at this
9295    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
9296    /// the stop had already landed. The idle branch has always made this same
9297    /// check before reaching `janitor`; the between-runs path makes it too.
9298    #[tokio::test]
9299    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
9300        let dir = tempfile::tempdir().unwrap();
9301        let home = dir.path().join("home");
9302        let cache_dir = dir.path().join("cache");
9303        std::fs::create_dir_all(&cache_dir).unwrap();
9304        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
9305        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
9306
9307        let stop = Stop::new();
9308        stop.stop();
9309        assert!(
9310            !stop.finishing(),
9311            "no run is in flight at a between-runs boundary, so nothing else \
9312             would tell the operator this stop had not taken effect yet"
9313        );
9314
9315        let mut last_checked = None;
9316        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
9317        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
9318            .await;
9319        assert_eq!(
9320            crate::disk::dir_size(&cache_dir),
9321            10,
9322            "over its cap, and due for the first check ever, but a stop outranks \
9323             it: the cap is a standing policy the next start measures again"
9324        );
9325        assert_eq!(
9326            last_checked, None,
9327            "a check that never happened must not claim the interval"
9328        );
9329    }
9330
9331    /// The regression this whole change exists for: gate timeouts on runs
9332    /// 52da/2f7f/5991/0915 traced back to the shared cache sitting at 81.8
9333    /// GiB against a 10 GiB cap, because the operator's queue never had a
9334    /// quiet moment for `poll`'s fully-idle branch to reach the ordinary
9335    /// `janitor` pass.
9336    ///
9337    /// Reproduced with a backlog whose repository is never created:
9338    /// `Runner::start` fails at `git::toplevel`, spawning no agent CLI.
9339    /// Each task is held after one startup failure, but the remaining tasks
9340    /// keep the queue busy until an external stop ends the loop.
9341    #[tokio::test]
9342    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
9343        let dir = tempfile::tempdir().unwrap();
9344        let cache_dir = dir.path().join("cache");
9345        std::fs::create_dir_all(&cache_dir).unwrap();
9346        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
9347
9348        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
9349        opts.poll = Duration::from_millis(20);
9350        opts.max_attempts = 1_000;
9351
9352        let queue = Queue::at(dir.path().join("queue"));
9353        for i in 0..128 {
9354            let mut task = Task::new(
9355                format!("queued work {i}"),
9356                format!("queued work {i}"),
9357                opts.repo.clone(),
9358                Source::Human,
9359            );
9360            queue.put(&mut task).unwrap();
9361        }
9362
9363        let home = dir.path().join("home");
9364        let worktrees = dir.path().join("wt");
9365        let status_file = home.join("daemon.json");
9366        let stop = Stop::new();
9367        let stopper = {
9368            let stop = stop.clone();
9369            let queue = Queue::at(dir.path().join("queue"));
9370            tokio::spawn(async move {
9371                // Observe completed work rather than rely on a wall-clock
9372                // delay. Every startup failure holds only its own task; the
9373                // backlog keeps offering work at the next boundary.
9374                for _ in 0..2_000 {
9375                    if queue.list().iter().filter(|t| t.attempts == 1).count() >= 2 {
9376                        break;
9377                    }
9378                    tokio::time::sleep(Duration::from_millis(5)).await;
9379                }
9380                stop.stop();
9381            })
9382        };
9383
9384        tokio::time::timeout(
9385            Duration::from_secs(20),
9386            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
9387        )
9388        .await
9389        .expect("the loop must not hang on a queue that keeps producing failing work")
9390        .expect("the loop's own setup and teardown must not fail");
9391        stopper.await.unwrap();
9392
9393        let after = queue.list();
9394        let completed = after.iter().filter(|t| t.attempts == 1).count();
9395        assert!(
9396            completed >= 2,
9397            "the harness must have processed multiple tasks to exercise a busy queue \
9398             (got {completed} completed task(s))"
9399        );
9400        assert!(
9401            after.iter().any(|t| t.status.runnable()),
9402            "unprocessed tasks must remain: the external stop, rather than an \
9403             exhausted backlog, must end the test"
9404        );
9405        assert!(
9406            after
9407                .iter()
9408                .filter(|t| t.attempts > 0)
9409                .all(|t| { t.attempts == 1 && t.status == TaskStatus::Held }),
9410            "a busy backlog must not retry a task's unchanged startup failure"
9411        );
9412
9413        assert_eq!(
9414            crate::disk::dir_size(&cache_dir),
9415            0,
9416            "an oversized cache must not be left to grow unboundedly just because the \
9417             queue kept the loop busy the whole time"
9418        );
9419    }
9420
9421    #[test]
9422    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
9423        let dir = tempfile::tempdir().unwrap();
9424        let queue = Queue::at(dir.path().join("queue"));
9425        let questions = Questions::at(dir.path().join("questions"));
9426        let mut task = task();
9427        queue.put(&mut task).unwrap();
9428
9429        let mut task_question = ask::Question::new(
9430            task.id.clone(),
9431            crate::conduct::NODE.to_owned(),
9432            "conduct".to_owned(),
9433            "Which backend?".to_owned(),
9434            String::new(),
9435            Vec::new(),
9436        );
9437        questions.put(&mut task_question).unwrap();
9438        task.block(vec![task_question.id.clone()], None);
9439        queue.put(&mut task).unwrap();
9440
9441        let mut run_question = ask::Question::new(
9442            "20260101-000000-run1".to_owned(),
9443            "review".to_owned(),
9444            "reviewer-1".to_owned(),
9445            "Run question".to_owned(),
9446            String::new(),
9447            Vec::new(),
9448        );
9449        questions.put(&mut run_question).unwrap();
9450
9451        // A question from another node whose `run` happens to equal this
9452        // task's id — the same field, filled in for an unrelated reason. Only
9453        // `crate::conduct::NODE` questions use `run` as a task id; this one
9454        // must never be touched by this reconciliation, even after release.
9455        let mut coincidental = ask::Question::new(
9456            task.id.clone(),
9457            "review".to_owned(),
9458            "reviewer-1".to_owned(),
9459            "Unrelated review question".to_owned(),
9460            String::new(),
9461            Vec::new(),
9462        );
9463        questions.put(&mut coincidental).unwrap();
9464
9465        reconcile_task_questions(&queue, &questions);
9466        assert!(questions.get(&task_question.id).unwrap().status.open());
9467        assert!(questions.get(&run_question.id).unwrap().status.open());
9468        assert!(questions.get(&coincidental.id).unwrap().status.open());
9469
9470        task.release();
9471        queue.put(&mut task).unwrap();
9472        reconcile_task_questions(&queue, &questions);
9473        assert_eq!(
9474            questions.get(&task_question.id).unwrap().status,
9475            ask::QuestionStatus::Abandoned
9476        );
9477        assert!(
9478            questions.get(&run_question.id).unwrap().status.open(),
9479            "run questions remain the run janitor's responsibility"
9480        );
9481        assert!(
9482            questions.get(&coincidental.id).unwrap().status.open(),
9483            "a non-conductor question must not be abandoned just because its \
9484             run id coincides with a task id"
9485        );
9486    }
9487
9488    #[test]
9489    fn a_freshly_started_running_task_is_never_stalled() {
9490        let dir = tempfile::tempdir().unwrap();
9491        let mut t = task();
9492        t.start("run-1".to_owned());
9493        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
9494        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
9495        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
9496    }
9497
9498    #[test]
9499    fn a_long_running_task_with_no_live_daemon_is_stalled() {
9500        let dir = tempfile::tempdir().unwrap();
9501        let mut t = task();
9502        t.start("run-1".to_owned());
9503        t.updated_at = Timestamp::now()
9504            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
9505        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
9506        assert_eq!(
9507            stalled_tasks(
9508                &Queue::at(dir.path().join("q")),
9509                dir.path(),
9510                Timestamp::now()
9511            )
9512            .len(),
9513            0,
9514            "the task was never written to this queue"
9515        );
9516    }
9517
9518    #[test]
9519    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
9520        let dir = tempfile::tempdir().unwrap();
9521        let mut t = task();
9522        t.id = "20260903-080340-0167".to_owned();
9523        t.start("20260903-080619-01c2".to_owned());
9524        t.updated_at = Timestamp::now()
9525            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
9526
9527        let mut status = Status::new();
9528        status.current = vec![Current {
9529            task: t.id.clone(),
9530            run: "20260903-080619-01c2".to_owned(),
9531        }];
9532        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9533
9534        assert!(
9535            !is_stalled(&t, dir.path(), Timestamp::now()),
9536            "a live daemon's own heartbeat rules out stalled, however long the task has run"
9537        );
9538    }
9539
9540    /// Rewrite a task's `updated_at` on disk directly, bypassing
9541    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
9542    /// a fixture look like it has genuinely been `running` for a while.
9543    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
9544        let path = queue.path_of(id);
9545        let body = std::fs::read_to_string(&path).unwrap();
9546        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
9547        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
9548        v["updated_at"] = serde_json::Value::String(old.to_string());
9549        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
9550    }
9551
9552    #[test]
9553    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
9554        // The realistic `poll()` ordering, not `is_stalled` in isolation:
9555        // `reclaim_orphaned_running` runs first, on every poll, and settles
9556        // any `running` task whose claim it can actually take. For most
9557        // crashes that is immediate - a dead pid is proof enough for
9558        // `sweep_stale_claims` to drop the lock the same tick, and the very
9559        // next claim attempt succeeds. But a lock whose pid cannot be parsed
9560        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
9561        // `sweep_stale_claims`'s own doc), so the lock - and the claim
9562        // failure behind it - can legitimately outlive many polls. This is
9563        // exactly the gap `stalled_tasks` exists to surface well before that
9564        // six-hour sweep would: reclaim leaves the task `running`, and it
9565        // must still reach the conductor as stalled.
9566        let dir = tempfile::tempdir().unwrap();
9567        let queue = Queue::at(dir.path().join("queue"));
9568        let home = dir.path().join("home");
9569
9570        let mut t = task();
9571        t.id = "20260101-000001-lock".to_owned();
9572        t.start("run-1".to_owned());
9573        queue.put(&mut t).unwrap();
9574        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
9575        std::fs::write(
9576            dir.path().join("queue").join(format!("{}.lock", t.id)),
9577            "not a pid",
9578        )
9579        .unwrap();
9580
9581        let now = Timestamp::now();
9582        assert!(
9583            reclaim_orphaned_running(&queue, 2).is_empty(),
9584            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
9585             and reclaim must leave the task alone"
9586        );
9587        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
9588
9589        let stalled = stalled_tasks(&queue, &home, now);
9590        assert_eq!(
9591            stalled.len(),
9592            1,
9593            "reclaim's inability to claim it yet must not hide it from the conductor"
9594        );
9595        assert_eq!(stalled[0].id, t.id);
9596    }
9597
9598    #[test]
9599    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
9600        let dir = tempfile::tempdir().unwrap();
9601        crate::run::set_home(dir.path().join("run-home"));
9602        let queue = Queue::at(dir.path().join("queue"));
9603        let home = dir.path().join("home");
9604        let questions = Questions::at(dir.path().join("questions"));
9605
9606        let mut t = task();
9607        t.id = "20260101-000003-dead".to_owned();
9608        t.start("missing-run".to_owned());
9609        queue.put(&mut t).unwrap();
9610        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
9611
9612        // This is the real poll ordering: retain the deterministic stalled
9613        // input before a claim proves the owner is gone and reclaims it.
9614        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
9615        assert_eq!(
9616            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
9617            [&t.id]
9618        );
9619        assert_eq!(reclaim_orphaned_running(&queue, 2), [t.id.clone()]);
9620        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
9621
9622        // Reclaim drops its guard before conductor decisions are applied, so
9623        // the decision for the captured stalled input has a real write path.
9624        crate::conduct::apply(
9625            &queue,
9626            &questions,
9627            &crate::conduct::Verdict {
9628                decisions: vec![crate::conduct::Decision {
9629                    id: t.id.clone(),
9630                    recovery: Some(crate::conduct::Recovery::Requeue),
9631                    ..crate::conduct::Decision::default()
9632                }],
9633            },
9634        )
9635        .unwrap();
9636        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
9637    }
9638
9639    #[test]
9640    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
9641        let dir = tempfile::tempdir().unwrap();
9642        let queue = Queue::at(dir.path().join("queue"));
9643        let home = dir.path().join("home");
9644
9645        let mut fresh = task();
9646        fresh.id = "20260101-000001-aaaa".to_owned();
9647        fresh.start("run-1".to_owned());
9648        queue.put(&mut fresh).unwrap();
9649
9650        let mut old = task();
9651        old.id = "20260101-000002-bbbb".to_owned();
9652        old.start("run-2".to_owned());
9653        queue.put(&mut old).unwrap();
9654        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
9655
9656        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
9657        assert_eq!(stalled.len(), 1);
9658        assert_eq!(stalled[0].id, old.id);
9659    }
9660
9661    #[test]
9662    fn queued_and_finished_task_views_partition_by_status() {
9663        let dir = tempfile::tempdir().unwrap();
9664        let queue = Queue::at(dir.path().join("queue"));
9665
9666        let mut queued = task();
9667        queued.id = "20260101-000001-aaaa".to_owned();
9668        queue.put(&mut queued).unwrap();
9669
9670        let mut failed = task();
9671        failed.id = "20260101-000002-bbbb".to_owned();
9672        failed.start("run-1".to_owned());
9673        failed.fail("gate red", 5);
9674        queue.put(&mut failed).unwrap();
9675
9676        let mut held = task();
9677        held.id = "20260101-000003-cccc".to_owned();
9678        held.hold_machine(None);
9679        queue.put(&mut held).unwrap();
9680
9681        let mut running = task();
9682        running.id = "20260101-000004-dddd".to_owned();
9683        running.start("run-2".to_owned());
9684        queue.put(&mut running).unwrap();
9685
9686        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
9687        assert_eq!(queued_ids, [queued.id.clone()]);
9688
9689        let mut finished_ids: Vec<String> =
9690            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
9691        finished_ids.sort_unstable();
9692        let mut want = vec![failed.id.clone(), held.id.clone()];
9693        want.sort_unstable();
9694        assert_eq!(finished_ids, want);
9695    }
9696
9697    #[test]
9698    fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
9699        for short in [false, true] {
9700            let dir = tempfile::tempdir().unwrap();
9701            let queue = Queue::at(dir.path().join("queue"));
9702            let questions = ask::Questions::at(dir.path().join("questions"));
9703            let mut running = task();
9704            running.id = "20261013-192213-feb2".into();
9705            running.start("existing-run".into());
9706            queue.put(&mut running).unwrap();
9707            let mut middle = task();
9708            middle.id = "20261013-193611-ca5b".into();
9709            middle.block(
9710                vec![if short {
9711                    "feb2".into()
9712                } else {
9713                    running.id.clone()
9714                }],
9715                None,
9716            );
9717            queue.put(&mut middle).unwrap();
9718            let mut waiting = task();
9719            waiting.id = "20261013-202849-ee37".into();
9720            waiting.block(
9721                vec![if short {
9722                    "ca5b".into()
9723                } else {
9724                    middle.id.clone()
9725                }],
9726                Some("wait for implementation".into()),
9727            );
9728            queue.put(&mut waiting).unwrap();
9729            assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
9730            let inv = crate::blockers::Inventory::load(&queue, &questions);
9731            assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
9732            assert!(inv.stuck().is_empty());
9733            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
9734            assert!(report.quarantined.is_empty());
9735            assert!(report.asked.is_empty());
9736            resolve_blockers(&queue, &questions);
9737            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9738            assert!(questions.list().is_empty());
9739            // Finishing the transitive prerequisite alone does not satisfy
9740            // the task's direct dependency.
9741            running.succeed();
9742            queue.put(&mut running).unwrap();
9743            resolve_blockers(&queue, &questions);
9744            assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
9745            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9746            middle = queue.get(&middle.id).unwrap();
9747            middle.succeed();
9748            queue.put(&mut middle).unwrap();
9749            resolve_blockers(&queue, &questions);
9750            let after = queue.get(&waiting.id).unwrap();
9751            assert_eq!(after.status, TaskStatus::Queued);
9752            assert!(after.blocked_by.is_empty());
9753            assert_eq!(after.instruction, waiting.instruction);
9754        }
9755    }
9756
9757    #[test]
9758    fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
9759        for future_schema in [false, true] {
9760            let name = "20261013-193611-ca5b";
9761            let mut future = task();
9762            future.id = name.into();
9763            future.schema = crate::queue::SCHEMA + 1;
9764            let contents = if future_schema {
9765                serde_json::to_string(&future).unwrap()
9766            } else {
9767                "corrupt".into()
9768            };
9769            let dir = tempfile::tempdir().unwrap();
9770            let queue = Queue::at(dir.path().join("queue"));
9771            let questions = ask::Questions::at(dir.path().join("questions"));
9772            let mut waiting = task();
9773            waiting.id = "20261013-202849-ee37".into();
9774            waiting.block(vec!["ca5b".into()], None);
9775            queue.put(&mut waiting).unwrap();
9776            std::fs::write(queue.path_of(name), contents).unwrap();
9777            assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
9778            assert!(
9779                crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
9780            );
9781            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
9782            assert!(report.asked.is_empty());
9783            resolve_blockers(&queue, &questions);
9784            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9785            assert!(questions.list().is_empty());
9786        }
9787        let dir = tempfile::tempdir().unwrap();
9788        let queue = Queue::at(dir.path().join("queue"));
9789        let questions = ask::Questions::at(dir.path().join("questions"));
9790        let mut waiting = task();
9791        waiting.id = "20261013-202849-ee37".into();
9792        waiting.block(vec!["ca5b".into()], None);
9793        queue.put(&mut waiting).unwrap();
9794        let mut done = task();
9795        done.id = "20261013-193611-ca5b".into();
9796        done.succeed();
9797        queue.put(&mut done).unwrap();
9798        // An unreadable second match must not disappear from uniqueness
9799        // checks just because Queue::list skips it.
9800        std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
9801        assert!(queue.get("ca5b").is_err());
9802        assert_eq!(
9803            crate::queue::dependency(&queue, &questions, "ca5b"),
9804            crate::queue::Dependency::Ambiguous
9805        );
9806        resolve_blockers(&queue, &questions);
9807        let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
9808        assert!(report.asked.is_empty());
9809        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9810        assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
9811    }
9812
9813    #[test]
9814    fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
9815        for held in [false, true] {
9816            for question in [false, true] {
9817                for reference in ["ca5b", "20261013-193611-ca5b"] {
9818                    let dir = tempfile::tempdir().unwrap();
9819                    let queue = Queue::at(dir.path().join("queue"));
9820                    let questions = ask::Questions::at(dir.path().join("questions"));
9821                    let mut prerequisite = task();
9822                    prerequisite.id = "20261013-193611-ca5b".into();
9823                    prerequisite.start("existing-run".into());
9824                    queue.put(&mut prerequisite).unwrap();
9825                    let mut waiting = task();
9826                    waiting.id = "20261013-202849-ee37".into();
9827                    if held {
9828                        waiting.hold_machine(Some("waiting for separate consent".into()));
9829                    }
9830                    queue.put(&mut waiting).unwrap();
9831                    let reason = "Deleting saved data requires separate owner consent";
9832                    crate::conduct::apply(
9833                        &queue,
9834                        &questions,
9835                        &crate::conduct::Verdict {
9836                            decisions: vec![crate::conduct::Decision {
9837                                id: waiting.id.clone(),
9838                                blocked_by: vec![reference.into()],
9839                                question: question.then(|| "May the saved data be deleted?".into()),
9840                                recovery: (!question).then_some(crate::conduct::Recovery::Hold),
9841                                reason: Some(reason.into()),
9842                                ..crate::conduct::Decision::default()
9843                            }],
9844                        },
9845                    )
9846                    .unwrap();
9847                    let before = queue.get(&waiting.id).unwrap();
9848                    if question {
9849                        assert_eq!(before.status, TaskStatus::Blocked);
9850                        let q = questions.get(&before.blocked_by[0]).unwrap();
9851                        assert_eq!(q.summary, "May the saved data be deleted?");
9852                        assert!(q.status.open());
9853                    } else {
9854                        assert_eq!(before.status, TaskStatus::Held);
9855                        let recorded_reason = before.hold_reason.as_deref().unwrap();
9856                        assert!(recorded_reason.starts_with(reason));
9857                        if held {
9858                            assert!(recorded_reason.contains("waiting for separate consent"));
9859                        }
9860                    }
9861                    prerequisite.succeed();
9862                    queue.put(&mut prerequisite).unwrap();
9863                    resolve_blockers(&queue, &questions);
9864                    let after = queue.get(&waiting.id).unwrap();
9865                    assert_eq!(after.status, before.status);
9866                    assert_eq!(after.blocked_by, before.blocked_by);
9867                    assert_eq!(after.hold_reason, before.hold_reason);
9868                    assert_eq!(after.instruction, waiting.instruction);
9869                    if question {
9870                        assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
9871                    }
9872                    assert!(
9873                        queue.next_runnable().is_none(),
9874                        "dependency completion is not consent"
9875                    );
9876                }
9877            }
9878        }
9879    }
9880
9881    #[test]
9882    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
9883        let dir = tempfile::tempdir().unwrap();
9884        let queue = Queue::at(dir.path().join("queue"));
9885        let questions = ask::Questions::at(dir.path().join("questions"));
9886
9887        let mut dep = task();
9888        dep.id = "20260101-000001-dep0".to_owned();
9889        dep.succeed();
9890        queue.put(&mut dep).unwrap();
9891
9892        let mut still_going = task();
9893        still_going.id = "20260101-000002-dep1".to_owned();
9894        queue.put(&mut still_going).unwrap();
9895
9896        let mut blocked = task();
9897        blocked.id = "20260101-000003-main".to_owned();
9898        blocked.block(
9899            vec![dep.id.clone(), still_going.id.clone()],
9900            Some("waits on both".to_owned()),
9901        );
9902        queue.put(&mut blocked).unwrap();
9903
9904        resolve_blockers(&queue, &questions);
9905
9906        let after = queue.get(&blocked.id).unwrap();
9907        assert_eq!(
9908            after.status,
9909            TaskStatus::Blocked,
9910            "one dependency is still outstanding"
9911        );
9912        assert_eq!(after.blocked_by, [still_going.id.clone()]);
9913    }
9914
9915    #[test]
9916    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
9917        let dir = tempfile::tempdir().unwrap();
9918        let queue = Queue::at(dir.path().join("queue"));
9919        let questions = ask::Questions::at(dir.path().join("questions"));
9920
9921        let mut q = crate::ask::Question::new(
9922            "20260101-000001-main".to_owned(),
9923            crate::conduct::NODE.to_owned(),
9924            "conduct".to_owned(),
9925            "Which backend?".to_owned(),
9926            String::new(),
9927            Vec::new(),
9928        );
9929        questions.put(&mut q).unwrap();
9930        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
9931            .unwrap();
9932        questions.put(&mut q).unwrap();
9933
9934        let mut blocked = task();
9935        blocked.id = "20260101-000001-main".to_owned();
9936        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
9937        queue.put(&mut blocked).unwrap();
9938
9939        resolve_blockers(&queue, &questions);
9940
9941        let after = queue.get(&blocked.id).unwrap();
9942        assert_eq!(
9943            after.status,
9944            TaskStatus::Queued,
9945            "the only blocker resolved"
9946        );
9947        assert_eq!(after.answers.len(), 1);
9948        assert_eq!(after.answers[0].question, "Which backend?");
9949        assert_eq!(after.answers[0].answer, "SQLite");
9950
9951        // And the run this task starts next is told about it.
9952        let instruction = instruction_for(&after);
9953        assert!(instruction.contains("Which backend?"));
9954        assert!(instruction.contains("SQLite"));
9955    }
9956
9957    #[test]
9958    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
9959        let dir = tempfile::tempdir().unwrap();
9960        let queue = Queue::at(dir.path().join("queue"));
9961        let questions = ask::Questions::at(dir.path().join("questions"));
9962
9963        let mut q = crate::ask::Question::new(
9964            "20260101-000001-main".to_owned(),
9965            crate::conduct::NODE.to_owned(),
9966            "conduct".to_owned(),
9967            "Is the setup done?".to_owned(),
9968            String::new(),
9969            Vec::new(),
9970        );
9971        q.abandon("no answer within 60s of asking");
9972        questions.put(&mut q).unwrap();
9973
9974        let mut blocked = task();
9975        blocked.id = "20260101-000001-main".to_owned();
9976        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
9977        queue.put(&mut blocked).unwrap();
9978
9979        resolve_blockers(&queue, &questions);
9980
9981        let after = queue.get(&blocked.id).unwrap();
9982        assert_eq!(
9983            after.status,
9984            TaskStatus::Held,
9985            "never left blocked on nothing"
9986        );
9987        assert!(!after.operator_held(), "a machine hold, for triage");
9988        assert!(
9989            after
9990                .hold_reason
9991                .as_deref()
9992                .unwrap_or_default()
9993                .contains("went unanswered")
9994        );
9995    }
9996
9997    #[test]
9998    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
9999        // Reproduces the reported bug (task 3958): a task held out of
10000        // attempts, blocked on a `crate::conduct` follow-up question, must
10001        // come back `held` once that question is answered - never `queued`,
10002        // whatever the answer said - or it silently re-enters the
10003        // competition queue with its attempts already exhausted.
10004        let dir = tempfile::tempdir().unwrap();
10005        let queue = Queue::at(dir.path().join("queue"));
10006        let questions = ask::Questions::at(dir.path().join("questions"));
10007
10008        let mut q = crate::ask::Question::new(
10009            "20260101-000001-main".to_owned(),
10010            crate::conduct::NODE.to_owned(),
10011            "conduct".to_owned(),
10012            "How should this be handled?".to_owned(),
10013            String::new(),
10014            Vec::new(),
10015        );
10016        questions.put(&mut q).unwrap();
10017        q.answer(crate::ask::Answer::Text(
10018            "leave it held, a human will look at it later".to_owned(),
10019        ))
10020        .unwrap();
10021        questions.put(&mut q).unwrap();
10022
10023        let mut held = task();
10024        held.id = "20260101-000001-main".to_owned();
10025        held.hold_machine(Some("out of attempts".to_owned()));
10026        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
10027        queue.put(&mut held).unwrap();
10028
10029        resolve_blockers(&queue, &questions);
10030
10031        let after = queue.get(&held.id).unwrap();
10032        assert_eq!(after.status, TaskStatus::Held);
10033        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
10034        assert_eq!(
10035            after.answers[0].answer,
10036            "leave it held, a human will look at it later"
10037        );
10038    }
10039
10040    #[test]
10041    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
10042        let dir = tempfile::tempdir().unwrap();
10043        let queue = Queue::at(dir.path().join("queue"));
10044        let questions = ask::Questions::at(dir.path().join("questions"));
10045        let mut dep = task();
10046        dep.id = "20260101-000001-gone".to_owned();
10047        queue.put(&mut dep).unwrap();
10048        let mut blocked = task();
10049        blocked.id = "20260101-000003-main".to_owned();
10050        blocked.block(vec![dep.id.clone()], None);
10051        queue.put(&mut blocked).unwrap();
10052
10053        // Claimed, so `remove` cannot rewrite it and the resolver must.
10054        let claim = queue.claim(&blocked.id).unwrap();
10055        queue.remove(&dep.id, false, &questions).unwrap();
10056        drop(claim);
10057        resolve_blockers(&queue, &questions);
10058
10059        let after = queue.get(&blocked.id).unwrap();
10060        assert_eq!(after.status, TaskStatus::Queued);
10061        assert!(after.blocked_by.is_empty());
10062    }
10063
10064    #[test]
10065    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
10066        // Reproduces the reported bug: a task blocked on a task id that was
10067        // removed (`magi task rm`, or deleted by hand) can never see that id
10068        // reach `Done`, so the ordinary per-id loop has nothing to notice and
10069        // would otherwise leave the task `blocked` forever with no way for an
10070        // operator to find out why.
10071        let dir = tempfile::tempdir().unwrap();
10072        let queue = Queue::at(dir.path().join("queue"));
10073        let questions = ask::Questions::at(dir.path().join("questions"));
10074
10075        let mut still_going = task();
10076        still_going.id = "20260101-000002-dep1".to_owned();
10077        queue.put(&mut still_going).unwrap();
10078
10079        let mut blocked = task();
10080        blocked.id = "20260101-000003-main".to_owned();
10081        blocked.block(
10082            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
10083            Some("waits on both".to_owned()),
10084        );
10085        queue.put(&mut blocked).unwrap();
10086
10087        resolve_blockers(&queue, &questions);
10088
10089        let after = queue.get(&blocked.id).unwrap();
10090        assert_eq!(
10091            after.status,
10092            TaskStatus::Held,
10093            "a missing dependency must not leave the task blocked forever"
10094        );
10095        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
10096        assert!(after.blocked_by.is_empty());
10097        let reason = after.hold_reason.as_deref().unwrap_or_default();
10098        assert!(
10099            reason.contains("20260101-000001-gone"),
10100            "the missing id must be named so an operator can tell what happened: {reason}"
10101        );
10102        assert!(
10103            reason.contains(&still_going.id),
10104            "the still-valid dependency must not silently vanish from the record: {reason}"
10105        );
10106    }
10107
10108    #[test]
10109    fn instruction_for_is_unchanged_without_any_answers() {
10110        let t = task();
10111        assert_eq!(instruction_for(&t), t.instruction);
10112    }
10113
10114    #[test]
10115    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
10116        let dir = tempfile::tempdir().unwrap();
10117        let q = Queue::at(dir.path().join("queue"));
10118        let src = dir.path().join("shot.png");
10119        std::fs::write(&src, "x").unwrap();
10120        let mut t = task();
10121        q.attach(&mut t, &[src]).unwrap();
10122        let paths = task_attachments(&q, &t).unwrap();
10123        assert_eq!(paths.len(), 1);
10124        assert!(paths[0].is_absolute() && paths[0].is_file());
10125        std::fs::remove_file(&paths[0]).unwrap();
10126        let err = task_attachments(&q, &t).unwrap_err().to_string();
10127        assert!(err.contains("shot.png"), "{err}");
10128    }
10129
10130    #[tokio::test]
10131    async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
10132        let dir = tempfile::tempdir().unwrap();
10133        let queue_path = dir.path().join("queue");
10134        let queue = Queue::at(queue_path.clone());
10135        let mut t = task();
10136        t.source = Source::Agent {
10137            run: "originating-chat".into(),
10138            node: crate::queue::CHAT_NODE.into(),
10139        };
10140        let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
10141            stage: "config-fetch",
10142            target: "origin/main".into(),
10143        });
10144        record_config_failure(&mut t, &fetch);
10145        t.hold_machine(Some(format!("{fetch:#}")));
10146        let fetch_key = t.chat_notice_due().unwrap();
10147        t.chat_notices.push(fetch_key.clone());
10148        queue.put(&mut t).unwrap();
10149
10150        let queue = Queue::at(queue_path);
10151        let mut t = queue.get(&t.id).unwrap();
10152        let a = dir.path().join("a.toml");
10153        let b = dir.path().join("b.toml");
10154        for (path, text, new_cause) in [
10155            (&a, "[graph", true),
10156            (&a, "[verify", false),
10157            (&a, "[graph]\nimplementers = 'invalid-type'", true),
10158            (&b, "[graph]\nimplementers = 'invalid-type'", true),
10159        ] {
10160            t.release_operator("test", None);
10161            std::fs::write(path, text).unwrap();
10162            let error = Config::discover_fetched(dir.path(), Some(path))
10163                .await
10164                .unwrap_err();
10165            record_config_failure(&mut t, &error);
10166            t.hold_machine(Some(format!("{error:#}")));
10167            let due = t.chat_notice_due();
10168            assert_eq!(due.is_some(), new_cause, "{error:#}");
10169            if let Some(key) = due {
10170                assert_ne!(key, fetch_key);
10171                t.chat_notices.push(key);
10172            }
10173        }
10174        t.succeed();
10175        assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
10176    }
10177
10178    #[test]
10179    fn different_missing_attachments_have_distinct_persisted_notice_causes() {
10180        let dir = tempfile::tempdir().unwrap();
10181        let queue_path = dir.path().join("queue");
10182        let queue = Queue::at(queue_path.clone());
10183        let mut t = task();
10184        t.source = crate::queue::Source::Agent {
10185            run: "originating-chat".into(),
10186            node: crate::queue::CHAT_NODE.into(),
10187        };
10188        let a = dir.path().join("a.png");
10189        let b = dir.path().join("b.png");
10190        std::fs::write(&a, "a").unwrap();
10191        std::fs::write(&b, "b").unwrap();
10192        queue.attach(&mut t, &[a, b]).unwrap();
10193        let paths = task_attachments(&queue, &t).unwrap();
10194        for path in &paths {
10195            std::fs::remove_file(path).unwrap();
10196        }
10197        let missing = task_attachments(&queue, &t).unwrap_err();
10198        t.attempts += 1;
10199        let reason = missing.to_string();
10200        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
10201        let first = t.chat_notice_due().expect("first attachment notice");
10202        t.chat_notices.push(first.clone());
10203        queue.put(&mut t).unwrap();
10204
10205        let queue = Queue::at(queue_path.clone());
10206        let mut t = queue.get(&t.id).unwrap();
10207        assert!(t.chat_notice_due().is_none(), "restart does not replay");
10208        t.release_operator("test", None);
10209        t.attempts += 1;
10210        let missing = task_attachments(&queue, &t).unwrap_err();
10211        t.fail_startup_target(
10212            "startup-attachments",
10213            missing.name,
10214            "same missing attachment with regenerated wording",
10215            1,
10216        );
10217        assert!(t.chat_notice_due().is_none(), "same object stays quiet");
10218
10219        std::fs::write(&paths[0], "restored").unwrap();
10220        t.release_operator("test", None);
10221        t.attempts += 1;
10222        let missing = task_attachments(&queue, &t).unwrap_err();
10223        let reason = missing.to_string();
10224        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
10225        let second = t
10226            .chat_notice_due()
10227            .expect("different attachment must notify");
10228        assert_ne!(first, second);
10229        assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
10230    }
10231
10232    #[test]
10233    fn resumed_instruction_is_unchanged_without_any_answers() {
10234        let t = task();
10235        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
10236    }
10237
10238    #[test]
10239    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
10240        let mut t = task();
10241        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
10242        // The run's own instruction on disk predates the answer: it is the
10243        // plain original text `Runner::start` saved before the operator was
10244        // ever asked anything.
10245        let old = t.instruction.clone();
10246
10247        let refreshed = resumed_instruction(&old, &t);
10248        assert!(refreshed.starts_with(&old), "the original text is kept");
10249        assert!(refreshed.contains("Which backend?"));
10250        assert!(refreshed.contains("SQLite"));
10251    }
10252
10253    #[test]
10254    fn resumed_instruction_keeps_an_original_answers_heading() {
10255        let mut t = task();
10256        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
10257        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
10258
10259        let refreshed = resumed_instruction(&t.instruction, &t);
10260
10261        assert!(
10262            refreshed.starts_with(&t.instruction),
10263            "an answers heading in the original instruction is not the appended block"
10264        );
10265        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
10266        assert!(refreshed.contains("Which backend?"));
10267        assert!(refreshed.contains("SQLite"));
10268
10269        let repeated = resumed_instruction(&refreshed, &t);
10270        assert_eq!(
10271            repeated, refreshed,
10272            "only the final appended block is refreshed"
10273        );
10274    }
10275
10276    #[test]
10277    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
10278        let mut t = task();
10279        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
10280
10281        // A first resume appends the block; a second resume of the same run,
10282        // with no new answer in between, must reproduce exactly the same
10283        // text rather than appending the block a second time.
10284        let once = resumed_instruction(&t.instruction, &t);
10285        let twice = resumed_instruction(&once, &t);
10286        assert_eq!(once, twice);
10287        assert_eq!(once.matches("Which backend?").count(), 1);
10288
10289        // A later answer replaces the block wholesale rather than growing it.
10290        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
10291        let refreshed = resumed_instruction(&once, &t);
10292        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
10293        assert!(refreshed.contains("Which backend?"));
10294        assert!(refreshed.contains("Which cache?"));
10295    }
10296
10297    #[test]
10298    fn prepare_instruction_covers_all_three_starters() {
10299        let mut t = task();
10300        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
10301
10302        // Start: a fresh run gets the task text plus every answer so far —
10303        // exactly `instruction_for`.
10304        assert_eq!(
10305            prepare_instruction(&Starter::Start, None, &t),
10306            Some(instruction_for(&t))
10307        );
10308
10309        // Resume: the run's prior instruction is refreshed with the answer,
10310        // not discarded and not left stale.
10311        let old = t.instruction.clone();
10312        assert_eq!(
10313            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
10314            Some(resumed_instruction(&old, &t))
10315        );
10316
10317        // Review: a review-only pass builds its own instruction from the
10318        // branch's history in `crate::graph`, with no task statement at all -
10319        // this boundary must leave it alone.
10320        assert_eq!(
10321            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
10322            None
10323        );
10324    }
10325
10326    #[test]
10327    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
10328        assert_eq!(
10329            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
10330            Starter::Review("magi/eba2/A".to_owned())
10331        );
10332    }
10333
10334    #[test]
10335    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
10336        assert_eq!(
10337            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
10338            Starter::Start,
10339            "a vanished review branch must not fall back to resuming the old run either"
10340        );
10341    }
10342
10343    #[test]
10344    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
10345        let mut t = task();
10346        t.start("old-run".to_owned());
10347        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
10348        t.release();
10349        let branch = t.review_branch.take();
10350        assert_eq!(
10351            choose_starter(branch.as_deref(), true, Some("old-run")),
10352            Starter::Review("magi/eba2/A".to_owned()),
10353            "a review wins over resuming the old run"
10354        );
10355    }
10356
10357    #[test]
10358    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
10359        assert_eq!(
10360            choose_starter(None, false, Some("some-run")),
10361            Starter::Resume("some-run".to_owned())
10362        );
10363        assert_eq!(choose_starter(None, false, None), Starter::Start);
10364    }
10365
10366    #[test]
10367    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
10368        let mut released = task();
10369        released.start("stalled-run".to_owned());
10370        released.requeue();
10371        let unfinished = (!released.fresh_start)
10372            .then(|| Some("stalled-run".to_owned()))
10373            .flatten();
10374        assert_eq!(
10375            choose_starter(None, false, unfinished.as_deref()),
10376            Starter::Start,
10377            "release keeps run history but must not resume it"
10378        );
10379        assert_eq!(released.runs, ["stalled-run"]);
10380    }
10381
10382    #[test]
10383    fn an_ordinary_release_keeps_a_resumable_run_available() {
10384        let mut released = task();
10385        released.start("stalled-run".to_owned());
10386        released.release();
10387        let unfinished = (!released.fresh_start)
10388            .then(|| Some("stalled-run".to_owned()))
10389            .flatten();
10390        assert_eq!(
10391            choose_starter(None, false, unfinished.as_deref()),
10392            Starter::Resume("stalled-run".to_owned()),
10393            "manual release must preserve the normal resume path"
10394        );
10395    }
10396
10397    #[test]
10398    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
10399        let mut state = run_state(RunStatus::Blocked);
10400        state.config.graph.review_rounds = 3;
10401        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
10402        assert!(exhausted_review_budget(&state));
10403
10404        // One round still unused: resuming can still ask a reviewer something.
10405        state.reviews.pop();
10406        assert!(!exhausted_review_budget(&state));
10407
10408        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
10409        // count: only a `Blocked` run re-enters the review loop on resume.
10410        let mut stalled = run_state(RunStatus::Stalled);
10411        stalled.config.graph.review_rounds = 1;
10412        stalled.reviews = vec![review_round(1)];
10413        assert!(!exhausted_review_budget(&stalled));
10414    }
10415
10416    fn review_round(round: usize) -> crate::run::ReviewRound {
10417        crate::run::ReviewRound {
10418            round,
10419            head: "deadbeef".to_owned(),
10420            verified_head: None,
10421            verified_at: None,
10422            reviews: Vec::new(),
10423            e2e: Vec::new(),
10424            verify_retried: false,
10425            e2e_deferred: false,
10426            e2e_defer_reason: None,
10427            fix: None,
10428            blocking: 0,
10429            answered: 1,
10430            expected: 1,
10431            clean: false,
10432            progressed: true,
10433            vote_split: false,
10434            reconsideration: Vec::new(),
10435            verdict: None,
10436        }
10437    }
10438
10439    #[test]
10440    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
10441        let mut run = RunState::new(
10442            PathBuf::from("/repo"),
10443            "main".to_owned(),
10444            "abc1234def".to_owned(),
10445            "add retries".to_owned(),
10446            Config::default(),
10447        );
10448        run.status = RunStatus::Judging;
10449        run.parked = true;
10450        let mut task = Task::new(
10451            "add retries".to_owned(),
10452            "add retries".to_owned(),
10453            PathBuf::from("/repo"),
10454            crate::queue::Source::Human,
10455        );
10456        task.status = TaskStatus::Failed;
10457        task.runs = vec![run.id.clone()];
10458        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
10459        assert!(with(&task, &run), "parked after judging is the case");
10460        let mut parked_task = task.clone();
10461        parked_task.status = TaskStatus::Parked;
10462        assert!(with(&parked_task, &run), "the Parked status is the case");
10463
10464        let mut not_parked = run.clone();
10465        not_parked.parked = false;
10466        not_parked.status = RunStatus::Stalled;
10467        assert!(!with(&task, &not_parked), "a stall is the conductor's");
10468
10469        let mut fresh = task.clone();
10470        fresh.fresh_start = true;
10471        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
10472
10473        let mut review = task.clone();
10474        review.review_branch = Some("magi/x/A".to_owned());
10475        assert!(!with(&review, &run), "review is ranked before resume");
10476
10477        let mut held = task.clone();
10478        held.status = TaskStatus::Held;
10479        assert!(!with(&held, &run), "a hold stays visible to the conductor");
10480
10481        let mut released = run.clone();
10482        released.released_to = Some("20260901-000000-new1".to_owned());
10483        assert!(!with(&task, &released), "nothing left to resume into");
10484
10485        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
10486            "unreadable"
10487        )));
10488    }
10489
10490    #[test]
10491    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
10492        let mut released = RunState::new(
10493            PathBuf::from("/repo"),
10494            "main".to_owned(),
10495            "abc1234def".to_owned(),
10496            "add retries".to_owned(),
10497            Config::default(),
10498        );
10499        released.status = RunStatus::Blocked;
10500        assert_eq!(
10501            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
10502            Some(released.id.clone())
10503        );
10504        released.released_to = Some("20260901-000000-new1".to_owned());
10505        assert_eq!(
10506            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
10507            None,
10508            "there is nothing left to resume it into"
10509        );
10510    }
10511
10512    #[test]
10513    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
10514        // Mirrors the failure this exists to close: a task's last run ended
10515        // `Blocked` with the review budget spent, `crate::conduct` chose
10516        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
10517        // evidence), and without this check `attempt` would go on treating
10518        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
10519        // review loop iterates zero times over an already-spent budget, so
10520        // the resumed run settles right back to `Blocked` having asked nobody
10521        // anything, and `Requeue`'s promised fresh competition never happens.
10522        let mut exhausted = RunState::new(
10523            PathBuf::from("/repo"),
10524            "main".to_owned(),
10525            "abc1234def".to_owned(),
10526            "add retries".to_owned(),
10527            Config::default(),
10528        );
10529        exhausted.status = RunStatus::Blocked;
10530        exhausted.config.graph.review_rounds = 1;
10531        exhausted.reviews = vec![review_round(1)];
10532
10533        assert_eq!(
10534            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
10535            None,
10536            "an exhausted `Blocked` run must not be offered as resumable"
10537        );
10538
10539        // A `Blocked` run with rounds still unused is genuinely worth
10540        // resuming, and must still be found.
10541        let mut has_budget_left = RunState::new(
10542            PathBuf::from("/repo"),
10543            "main".to_owned(),
10544            "abc1234def".to_owned(),
10545            "add retries".to_owned(),
10546            Config::default(),
10547        );
10548        has_budget_left.status = RunStatus::Blocked;
10549        has_budget_left.config.graph.review_rounds = 3;
10550        has_budget_left.reviews = vec![review_round(1)];
10551
10552        assert_eq!(
10553            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
10554                Ok(has_budget_left.clone())
10555            }),
10556            Some(has_budget_left.id.clone())
10557        );
10558    }
10559
10560    #[test]
10561    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
10562        let mut run = RunState::new(
10563            PathBuf::from("/repo"),
10564            "main".to_owned(),
10565            "abc1234def".to_owned(),
10566            "add retries".to_owned(),
10567            Config::default(),
10568        );
10569        run.status = RunStatus::Blocked;
10570        run.config.graph.review_rounds = 1;
10571        run.reviews = vec![review_round(1)];
10572        run.pr_publication_pending = true;
10573        assert_eq!(
10574            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
10575            Some(run.id.clone()),
10576            "a spent review budget must not turn a failed publication into a re-competition"
10577        );
10578    }
10579
10580    #[test]
10581    fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
10582        let mut task = Task::new(
10583            "recover work".into(),
10584            "recover work".into(),
10585            PathBuf::from("/repo"),
10586            crate::queue::Source::Human,
10587        );
10588        let mut history = std::collections::BTreeMap::new();
10589        for index in 0..8 {
10590            let mut run = run_state(RunStatus::Blocked);
10591            run.id = format!("20260101-000000-{index:04}");
10592            run.base_commit = format!("upstream-{index}");
10593            // Seven empty newer attempts must not erase the old recovery owner.
10594            if index > 0 {
10595                run.candidates.clear();
10596            }
10597            task.runs.extend([run.id.clone(), run.id.clone()]);
10598            history.insert(run.id.clone(), run);
10599            task.requeue();
10600        }
10601        let check = |task: &Task, starter: &Starter, limit| {
10602            retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
10603        };
10604        assert!(
10605            check(&task, &Starter::Start, 8)
10606                .unwrap()
10607                .contains("8 unretired")
10608        );
10609        assert!(check(&task, &Starter::Start, 9).is_none());
10610        assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
10611        task.release_operator("owner", None);
10612        assert_eq!(task.attempts, 0);
10613        let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
10614        assert!(check(&restored, &Starter::Start, 8).is_some());
10615        assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
10616        assert!(check(&restored, &Starter::Start, 0).is_none());
10617    }
10618
10619    #[test]
10620    fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
10621        let mut task = Task::new(
10622            "recover work".into(),
10623            "recover work".into(),
10624            PathBuf::from("/repo"),
10625            crate::queue::Source::Human,
10626        );
10627        let mut run = run_state(RunStatus::Superseded);
10628        run.candidates.clear();
10629        task.runs.push(run.id.clone());
10630        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
10631        run.retired_to = Some("authority".into());
10632        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
10633        run.retired_to = None;
10634        run.released_to = Some("authority".into());
10635        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
10636        assert!(
10637            retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
10638                .unwrap()
10639                .contains("Cannot verify")
10640        );
10641        // Resuming an existing owner needs no new inventory or worktree budget.
10642        assert!(
10643            retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
10644                panic!("resume must not load historical attempts")
10645            })
10646            .is_none()
10647        );
10648    }
10649
10650    #[test]
10651    fn retired_resume_requires_a_valid_same_repository_authority() {
10652        let mut source = run_state(RunStatus::Blocked);
10653        let mut empty = run_state(RunStatus::Blocked);
10654        empty.retired_to = Some(source.id.clone());
10655        let runs = vec![source.id.clone(), empty.id.clone()];
10656        let resolve = |source: &RunState, empty: &RunState| {
10657            unfinished_run_with(&runs, "fixture", |id| {
10658                if id == source.id {
10659                    Ok(source.clone())
10660                } else if id == empty.id {
10661                    Ok(empty.clone())
10662                } else {
10663                    bail!("unreadable authority")
10664                }
10665            })
10666        };
10667        assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
10668        assert_eq!(
10669            choose_starter(None, false, resolve(&source, &empty).as_deref()),
10670            Starter::Resume(source.id.clone())
10671        );
10672        source.retired_to = Some(empty.id.clone());
10673        assert!(
10674            resolve(&source, &empty).is_none(),
10675            "cycles do not revive obsolete runs"
10676        );
10677        source.retired_to = None;
10678        source.repo = PathBuf::from("/another-repository");
10679        assert!(resolve(&source, &empty).is_none());
10680        source.repo = empty.repo.clone();
10681        source.released_to = Some("later".into());
10682        assert!(resolve(&source, &empty).is_none());
10683        empty.retired_to = Some("unlisted-run".into());
10684        assert!(resolve(&source, &empty).is_none());
10685    }
10686
10687    #[test]
10688    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
10689        // A task whose history holds an *older* run that still looks
10690        // resumable (say, a competition `Runner::review` was started
10691        // alongside after that older run went `Stalled`) and a *newest* run
10692        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
10693        // on this task must mean a fresh competition — falling back to the
10694        // stale, superseded `Stalled` run instead would resurrect history
10695        // nothing asked to revisit and silently defeat the requeue.
10696        let mut older_stalled = RunState::new(
10697            PathBuf::from("/repo"),
10698            "main".to_owned(),
10699            "abc1234def".to_owned(),
10700            "add retries".to_owned(),
10701            Config::default(),
10702        );
10703        older_stalled.status = RunStatus::Stalled;
10704
10705        let mut newest_exhausted = RunState::new(
10706            PathBuf::from("/repo"),
10707            "main".to_owned(),
10708            "abc1234def".to_owned(),
10709            "add retries".to_owned(),
10710            Config::default(),
10711        );
10712        newest_exhausted.status = RunStatus::Blocked;
10713        newest_exhausted.config.graph.review_rounds = 1;
10714        newest_exhausted.reviews = vec![review_round(1)];
10715
10716        assert_eq!(
10717            unfinished_run_with(
10718                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
10719                "t",
10720                |_| Ok(newest_exhausted.clone())
10721            ),
10722            None,
10723            "the newest run is exhausted, so nothing here is worth resuming - \
10724             least of all the older, already-superseded run"
10725        );
10726    }
10727
10728    #[test]
10729    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
10730        assert_eq!(
10731            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
10732                Err(anyhow::anyhow!("fixture is absent"))
10733            }),
10734            None
10735        );
10736    }
10737
10738    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
10739        let mut q = ask::Question::new(
10740            run.to_owned(),
10741            "implement".to_owned(),
10742            "impl-A".to_owned(),
10743            "continue?".to_owned(),
10744            String::new(),
10745            vec!["resume で続行する".to_owned(), "other".to_owned()],
10746        );
10747        q.actions.insert("resume で続行する".to_owned(), action);
10748        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
10749            .unwrap();
10750        q
10751    }
10752
10753    fn held_task_with(run: &str) -> Task {
10754        let mut t = task();
10755        t.runs = vec![run.to_owned()];
10756        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
10757        t
10758    }
10759
10760    fn resume_action(run: &str) -> ask::ChoiceAction {
10761        ask::ChoiceAction::Resume { run: run.into() }
10762    }
10763
10764    #[test]
10765    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
10766        for parked in [false, true] {
10767            let mut t = task();
10768            t.start("A".into());
10769            t.start("B".into());
10770            assert_eq!(t.runs, vec!["A", "B"]);
10771            t.start("A".into());
10772            let mut resumed = run_state(RunStatus::Blocked);
10773            resumed.id = "A".into();
10774            resumed.parked = parked;
10775            resumed.driver_exited = true;
10776            t.hold_machine(Some("resumed run stopped".into()));
10777            let q = action_question("A", resume_action("A"));
10778            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
10779            assert_eq!(
10780                decide_action(&t, &q, &PHRASES_EN, |id| {
10781                    assert_eq!(id, "A");
10782                    Ok(resumed.clone())
10783                }),
10784                ActionDecision::Resume("A".into())
10785            );
10786            assert_eq!(
10787                action_standing(&t, &action_question("B", resume_action("B"))),
10788                ActionStanding::Stale
10789            );
10790            t.release_operator("cli", None);
10791            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
10792                assert_eq!(id, "A");
10793                Ok(resumed.clone())
10794            });
10795            assert_eq!(
10796                choose_starter(None, false, unfinished.as_deref()),
10797                Starter::Resume("A".into())
10798            );
10799            assert_eq!(t.runs, vec!["B", "A"]);
10800        }
10801    }
10802
10803    #[test]
10804    fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
10805        let mut state = crate::land::tests::repair_state(true, true);
10806        state.status = RunStatus::Landing;
10807        state.parked = true;
10808        state.driver_exited = true;
10809        let mut q = ask::Question::new(
10810            state.id.clone(),
10811            land::APPROVAL_NODE.into(),
10812            "land".into(),
10813            "Merge?".into(),
10814            String::new(),
10815            vec![land::APPROVE.into(), land::HOLD.into()],
10816        );
10817        q.id = state.id.clone();
10818        state.land_approval = Some(crate::run::LandApproval {
10819            question: q.id.clone(),
10820            head: "current-head".into(),
10821        });
10822        assert!(land::upgrade_repair_choice(&mut q, &state));
10823        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
10824        let mut task = held_task_with(&state.id);
10825        task.status = TaskStatus::Parked;
10826        assert_eq!(
10827            decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
10828            ActionDecision::Resume(state.id.clone())
10829        );
10830        q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
10831        q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
10832        task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
10833        assert_eq!(
10834            decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
10835            ActionDecision::Resume(state.id.clone()),
10836            "a repair answer newer than the manual hold resumes the existing owner"
10837        );
10838        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
10839        for answered_at in [q.answered_at, None] {
10840            let mut older = q.clone();
10841            older.answered_at = answered_at;
10842            let refused = decide_action(&task, &older, &PHRASES_EN, |_| {
10843                panic!("a later manual hold must prevent dispatch")
10844            });
10845            let ActionDecision::Refuse(reason) = refused else {
10846                panic!("expected an actionable refusal, got {refused:?}");
10847            };
10848            assert!(reason.contains("later operator decision"));
10849            assert!(reason.contains(&format!("magi task release {}", task.id)));
10850        }
10851        task.operator_decided_at = None;
10852        let mut superseded = state.clone();
10853        superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
10854        assert_eq!(
10855            decide_action(&task, &q, &PHRASES_EN, |_| Ok(superseded)),
10856            ActionDecision::Stale
10857        );
10858        for case in 1..4 {
10859            let mut changed = state.clone();
10860            match case {
10861                1 => changed.status = RunStatus::Blocked,
10862                2 => changed.released_to = Some("new-owner".into()),
10863                _ => changed.land_approval.as_mut().unwrap().head.clear(),
10864            }
10865            assert!(matches!(
10866                decide_action(&task, &q, &PHRASES_EN, |_| Ok(changed)),
10867                ActionDecision::Refuse(_)
10868            ));
10869        }
10870        assert!(matches!(
10871            decide_action(&task, &q, &PHRASES_EN, |_| anyhow::bail!("missing owner")),
10872            ActionDecision::Refuse(_)
10873        ));
10874        task.runs.push("replacement".into());
10875        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
10876        assert_eq!(
10877            decide_action(&task, &q, &PHRASES_EN, |_| panic!(
10878                "old owner must not load"
10879            )),
10880            ActionDecision::Stale
10881        );
10882    }
10883
10884    #[test]
10885    fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
10886        let mut state = crate::land::tests::repair_state(true, true);
10887        state.status = RunStatus::Landing;
10888        state.parked = true;
10889        state.driver_exited = true;
10890        let mut q = ask::Question::new(
10891            state.id.clone(),
10892            land::APPROVAL_NODE.into(),
10893            "land".into(),
10894            "Merge?".into(),
10895            String::new(),
10896            vec![land::APPROVE.into(), land::HOLD.into()],
10897        );
10898        q.id = state.id.clone();
10899        state.land_approval = Some(crate::run::LandApproval {
10900            question: q.id.clone(),
10901            head: "current-head".into(),
10902        });
10903        state.save().unwrap();
10904        land::upgrade_repair_choice(&mut q, &state);
10905        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
10906        Questions::open().put(&mut q).unwrap();
10907        let tmp = tempfile::tempdir().unwrap();
10908        let queue = Queue::at(tmp.path().join("queue"));
10909        let mut task = held_task_with(&state.id);
10910        task.status = TaskStatus::Parked;
10911        queue.put(&mut task).unwrap();
10912        let empty = Arc::new(tokio::sync::Semaphore::new(0));
10913        let free = Arc::new(tokio::sync::Semaphore::new(1));
10914        assert!(claim_dispatch(&queue, &task, false, &empty, &free).is_none());
10915        assert!(claim_dispatch(&queue, &task, true, &free, &free).is_none());
10916        let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
10917        assert!(claim.permit.is_some());
10918        assert!(claim_dispatch(&queue, &task, false, &free, &free).is_none());
10919        drop(claim);
10920        Questions::open()
10921            .update(&q.id, |q| {
10922                q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
10923                Ok(())
10924            })
10925            .unwrap();
10926        let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
10927        assert!(claim.permit.is_none());
10928        assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
10929    }
10930
10931    #[test]
10932    fn decide_action_resumes_only_the_latest_resumable_run() {
10933        let t = held_task_with("r1");
10934        let q = action_question("r1", resume_action("r1"));
10935        let load = |s: RunState| move |_: &str| Ok(s);
10936        assert_eq!(
10937            decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Blocked))),
10938            ActionDecision::Resume("r1".into())
10939        );
10940        // Not the latest run of the task.
10941        let q_other = action_question("r1", resume_action("r0"));
10942        assert!(matches!(
10943            decide_action(
10944                &t,
10945                &q_other,
10946                &PHRASES_EN,
10947                load(run_state(RunStatus::Blocked))
10948            ),
10949            ActionDecision::Refuse(_)
10950        ));
10951        // A finished run cannot make progress.
10952        assert!(matches!(
10953            decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Ready))),
10954            ActionDecision::Refuse(_)
10955        ));
10956        // A released one either.
10957        let mut released = run_state(RunStatus::Blocked);
10958        released.released_to = Some("elsewhere".into());
10959        assert!(matches!(
10960            decide_action(&t, &q, &PHRASES_EN, load(released)),
10961            ActionDecision::Refuse(_)
10962        ));
10963        // Unreadable state is a refusal, never a fresh competition.
10964        assert!(matches!(
10965            decide_action(&t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
10966            ActionDecision::Refuse(_)
10967        ));
10968    }
10969
10970    #[test]
10971    fn decide_action_ignores_a_question_about_an_earlier_run() {
10972        let mut t = held_task_with("r1");
10973        t.runs.push("r2".to_owned());
10974        let never = |_: &str| -> Result<RunState> { bail!("not read") };
10975        assert_eq!(
10976            decide_action(
10977                &t,
10978                &action_question("r1", ask::ChoiceAction::Done),
10979                &PHRASES_EN,
10980                never
10981            ),
10982            ActionDecision::Stale
10983        );
10984    }
10985
10986    #[test]
10987    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
10988        let mut t = held_task_with("r1");
10989        let never = |_: &str| -> Result<RunState> { bail!("not read") };
10990        assert_eq!(
10991            decide_action(
10992                &t,
10993                &action_question("r1", ask::ChoiceAction::Requeue),
10994                &PHRASES_EN,
10995                never
10996            ),
10997            ActionDecision::Requeue
10998        );
10999        let done_q = action_question("r1", ask::ChoiceAction::Done);
11000        assert_eq!(
11001            decide_action(&t, &done_q, &PHRASES_EN, never),
11002            ActionDecision::Done
11003        );
11004        t.mark_action_applied(&done_q.id);
11005        assert_eq!(
11006            decide_action(&t, &done_q, &PHRASES_EN, never),
11007            ActionDecision::Skip
11008        );
11009
11010        // A plain answer (no action for that label) does nothing.
11011        let mut plain = action_question("r1", ask::ChoiceAction::Done);
11012        plain.actions.clear();
11013        assert_eq!(
11014            decide_action(&held_task_with("r1"), &plain, &PHRASES_EN, never),
11015            ActionDecision::Skip
11016        );
11017        // A running task is left alone.
11018        let mut running = held_task_with("r1");
11019        running.status = TaskStatus::Running;
11020        assert_eq!(
11021            decide_action(
11022                &running,
11023                &action_question("r1", ask::ChoiceAction::Done),
11024                &PHRASES_EN,
11025                never
11026            ),
11027            ActionDecision::Skip
11028        );
11029    }
11030
11031    #[test]
11032    fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
11033        crate::run::pin_test_home();
11034        for legacy in [false, true] {
11035            let dir = tempfile::tempdir().unwrap();
11036            let queue = Queue::at(dir.path().join("queue"));
11037            let questions = Questions::at(dir.path().join("questions"));
11038            let run = "20260101-000000-hold";
11039            let mut task = held_task_with(run);
11040            task.status = TaskStatus::Parked;
11041            let mut q = ask::Question::new(
11042                run.into(),
11043                land::APPROVAL_NODE.into(),
11044                "land".into(),
11045                "Repair?".into(),
11046                String::new(),
11047                vec![land::REPAIR.into()],
11048            );
11049            q.actions.insert(land::REPAIR.into(), resume_action(run));
11050            q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
11051            // Deterministically order the answer before the actual manual hold.
11052            q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
11053            q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
11054            questions.put(&mut q).unwrap();
11055            task.hold_manual(Some("Keep this PR paused".into()));
11056            if legacy {
11057                task.hold_source = None;
11058            }
11059            queue.put(&mut task).unwrap();
11060
11061            apply_task_choice_actions(&queue, &questions, dir.path());
11062            let after = queue.get(&task.id).unwrap();
11063            assert!(after.operator_held());
11064            assert_eq!(after.hold_source, task.hold_source);
11065            assert_eq!(after.operator_decided_at, task.operator_decided_at);
11066            assert_eq!(after.runs, task.runs);
11067            assert_eq!(after.instruction, task.instruction);
11068            assert!(after.resume_override.is_none());
11069            assert!(after.action_applied(&q.id));
11070            let reason = after.hold_reason.as_deref().unwrap();
11071            assert!(reason.starts_with("Keep this PR paused"));
11072            assert!(reason.contains("later operator decision"));
11073            assert!(reason.contains(&format!("magi task release {}", task.id)));
11074
11075            for recovery in [
11076                crate::conduct::Recovery::Review,
11077                crate::conduct::Recovery::Requeue,
11078            ] {
11079                crate::conduct::apply(
11080                    &queue,
11081                    &questions,
11082                    &crate::conduct::Verdict {
11083                        decisions: vec![crate::conduct::Decision {
11084                            id: task.id.clone(),
11085                            recovery: Some(recovery),
11086                            ..Default::default()
11087                        }],
11088                    },
11089                )
11090                .unwrap();
11091            }
11092            // Reconciliation is idempotent, and automatic recovery cannot
11093            // reopen this owner after it observes the rejected repair answer.
11094            apply_task_choice_actions(&queue, &questions, dir.path());
11095            let still_held = queue.get(&task.id).unwrap();
11096            assert!(still_held.operator_held());
11097            assert_eq!(still_held.hold_reason, after.hold_reason);
11098            assert_eq!(still_held.runs, task.runs);
11099            assert!(still_held.review_branch.is_none());
11100            assert!(!still_held.fresh_start);
11101            assert!(queue.next_runnable().is_none());
11102        }
11103    }
11104
11105    #[test]
11106    fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
11107        for held in [false, true] {
11108            for retry in [false, true] {
11109                let dir = tempfile::tempdir().unwrap();
11110                let queue = Queue::at(dir.path().join("queue"));
11111                let questions = Questions::at(dir.path().join("questions"));
11112                let home = dir.path().join("home");
11113                let mut t = task();
11114                if held {
11115                    t.hold_machine(Some("driver state unknown".into()));
11116                }
11117                queue.put(&mut t).unwrap();
11118                let verdict = serde_json::from_value(serde_json::json!({
11119                    "decisions": [{
11120                        "id": t.id,
11121                        "question": "Driver state unknown; retry the checks or hold?",
11122                        "choices": ["daemon: recheck and retry", "daemon: hold the task"],
11123                        "actions": {
11124                            "daemon: recheck and retry": {"do": "requeue"},
11125                            "daemon: hold the task": {"do": "hold"}
11126                        }
11127                    }]
11128                }))
11129                .unwrap();
11130                crate::conduct::apply(&queue, &questions, &verdict).unwrap();
11131                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
11132                let mut q = questions.list().pop().unwrap();
11133                let choice = if retry {
11134                    "daemon: recheck and retry"
11135                } else {
11136                    "daemon: hold the task"
11137                };
11138                assert_eq!(q.actions.len(), 2);
11139                q.answer(ask::Answer::Choice(choice.into())).unwrap();
11140                questions.put(&mut q).unwrap();
11141
11142                // A Web answer does not remove the deputy's fresh lease.
11143                questions.beat(&q.id, ask::WaiterKind::Deputy);
11144                for _ in 0..2 {
11145                    resolve_blockers(&queue, &questions);
11146                    apply_task_choice_actions(&queue, &questions, &home);
11147                    let waiting = queue.get(&t.id).unwrap();
11148                    assert_eq!(waiting.status, TaskStatus::Blocked);
11149                    assert_eq!(waiting.blocked_by, [q.id.clone()]);
11150                    assert!(waiting.answers.is_empty());
11151                    assert!(!waiting.action_applied(&q.id));
11152                    assert!(runnable(&queue).is_empty());
11153                    let free = Arc::new(tokio::sync::Semaphore::new(1));
11154                    assert!(claim_dispatch(&queue, &t, false, &free, &free).is_none());
11155                }
11156                std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
11157
11158                // Releasing the blocker and applying the operation share one save.
11159                resolve_blockers(&queue, &questions);
11160                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
11161                apply_task_choice_actions(&queue, &questions, &home);
11162                let after = queue.get(&t.id).unwrap();
11163                assert_eq!(
11164                    after.status,
11165                    if retry {
11166                        TaskStatus::Queued
11167                    } else {
11168                        TaskStatus::Held
11169                    }
11170                );
11171                assert!(after.action_applied(&q.id));
11172                assert_eq!(after.operator_held(), !retry);
11173                assert_eq!(after.answers.len(), 1);
11174
11175                // A later operator decision must not replay this answer.
11176                let mut changed = after;
11177                if retry {
11178                    changed.hold_manual(Some("later hold".into()));
11179                } else {
11180                    changed.release_operator("test", None);
11181                }
11182                let expected = changed.status;
11183                queue.put(&mut changed).unwrap();
11184                apply_task_choice_actions(&queue, &questions, &home);
11185                assert_eq!(queue.get(&t.id).unwrap().status, expected);
11186            }
11187        }
11188    }
11189
11190    #[test]
11191    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
11192        let dir = tempfile::tempdir().unwrap();
11193        let queue = Queue::at(dir.path().join("queue"));
11194        let questions = Questions::at(dir.path().join("questions"));
11195        let home = dir.path().join("home");
11196        let mut state = run_state(RunStatus::Blocked);
11197        state.id = "20260101-000000-act1".to_owned();
11198        state.save_under(&home).unwrap();
11199
11200        let mut t = held_task_with(&state.id);
11201        queue.put(&mut t).unwrap();
11202        let mut q = action_question(&state.id, resume_action(&state.id));
11203        questions.put(&mut q).unwrap();
11204
11205        apply_task_choice_actions(&queue, &questions, &home);
11206        let after = queue.get(&t.id).unwrap();
11207        assert_eq!(after.status, TaskStatus::Queued);
11208        assert!(!after.fresh_start);
11209        assert!(after.action_applied(&q.id));
11210        let pin = after.resume_override.clone().unwrap();
11211        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
11212        assert!(pin.forced);
11213
11214        // Held again later: the same answer does not release it a second time.
11215        let mut again = queue.get(&t.id).unwrap();
11216        again.hold_machine(Some("later".into()));
11217        queue.put(&mut again).unwrap();
11218        apply_task_choice_actions(&queue, &questions, &home);
11219        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
11220    }
11221
11222    #[test]
11223    fn a_delivered_answer_is_still_acted_on_exactly_once() {
11224        let dir = tempfile::tempdir().unwrap();
11225        let queue = Queue::at(dir.path().join("queue"));
11226        let questions = Questions::at(dir.path().join("questions"));
11227        let home = dir.path().join("home");
11228        let mut state = run_state(RunStatus::Blocked);
11229        state.id = "20260101-000000-act2".to_owned();
11230        state.save_under(&home).unwrap();
11231
11232        let mut t = held_task_with(&state.id);
11233        queue.put(&mut t).unwrap();
11234        let mut q = action_question(&state.id, resume_action(&state.id));
11235        q.answer_delivered = true;
11236        questions.put(&mut q).unwrap();
11237
11238        // Delivered, and the agent then died: the task is still held, so the
11239        // chosen action applies.
11240        apply_task_choice_actions(&queue, &questions, &home);
11241        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
11242        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
11243
11244        // Held again: the same answer does nothing a second time.
11245        let mut again = queue.get(&t.id).unwrap();
11246        again.hold_machine(Some("later".into()));
11247        queue.put(&mut again).unwrap();
11248        apply_task_choice_actions(&queue, &questions, &home);
11249        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
11250    }
11251
11252    #[test]
11253    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
11254        let dir = tempfile::tempdir().unwrap();
11255        let queue = Queue::at(dir.path().join("queue"));
11256        let questions = Questions::at(dir.path().join("questions"));
11257        let home = dir.path().join("home");
11258        let mut state = run_state(RunStatus::Blocked);
11259        state.id = "20260101-000000-act3".to_owned();
11260        state.save_under(&home).unwrap();
11261        let mut t = held_task_with(&state.id);
11262        queue.put(&mut t).unwrap();
11263        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
11264        questions.put(&mut q).unwrap();
11265
11266        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
11267        apply_task_choice_actions(&queue, &questions, &home);
11268        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
11269
11270        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
11271        apply_task_choice_actions(&queue, &questions, &home);
11272        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
11273    }
11274
11275    #[test]
11276    fn action_standing_tells_the_reasons_apart() {
11277        let mut t = held_task_with("r1");
11278        let q = action_question("r1", ask::ChoiceAction::Requeue);
11279        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
11280        let mut plain = q.clone();
11281        plain.actions.clear();
11282        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
11283
11284        // Applied wins over everything, even a running task.
11285        t.mark_action_applied(&q.id);
11286        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
11287
11288        // A newer attempt running: the old question is Stale, not Busy.
11289        let mut t = held_task_with("r1");
11290        t.start("r2".to_owned());
11291        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
11292        // The same question about the latest run just waits.
11293        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
11294        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
11295        t.status = TaskStatus::Blocked;
11296        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
11297
11298        // A conductor question is keyed by the task, never stale.
11299        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
11300        c.node = crate::conduct::NODE.to_owned();
11301        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
11302        assert!(!ActionStanding::Busy.daemon_owns());
11303    }
11304
11305    #[test]
11306    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
11307        let dir = tempfile::tempdir().unwrap();
11308        let queue = Queue::at(dir.path().join("queue"));
11309        let questions = Questions::at(dir.path().join("questions"));
11310        let home = dir.path().join("home");
11311        let mut state = run_state(RunStatus::Blocked);
11312        state.id = "20260101-000000-act4".to_owned();
11313        state.save_under(&home).unwrap();
11314        let mut t = held_task_with(&state.id);
11315        t.status = TaskStatus::Running;
11316        queue.put(&mut t).unwrap();
11317        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
11318        q.cwd = Some(dir.path().display().to_string());
11319        questions.put(&mut q).unwrap();
11320
11321        // While the task runs the daemon will not act, so the waiter still
11322        // delivers the word to the dead asker's seat ...
11323        let running = queue.get(&t.id).unwrap();
11324        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
11325        assert!(matches!(
11326            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
11327            crate::waiter::Action::Deliver(_)
11328        ));
11329        // ... and the daemon waits while the task runs, then applies once.
11330        apply_task_choice_actions(&queue, &questions, &home);
11331        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
11332        let mut back = queue.get(&t.id).unwrap();
11333        back.hold_machine(Some("later".into()));
11334        queue.put(&mut back).unwrap();
11335        apply_task_choice_actions(&queue, &questions, &home);
11336        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
11337        let mut again = queue.get(&t.id).unwrap();
11338        again.hold_machine(Some("again".into()));
11339        queue.put(&mut again).unwrap();
11340        apply_task_choice_actions(&queue, &questions, &home);
11341        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
11342    }
11343}