Skip to main content

magi/
daemon.rs

1//! The unattended scheduler and independently leased task workers.
2//!
3//! The scheduler chooses tasks and execution lanes; a detached worker owns each
4//! queue claim, graph driver and outcome settlement. Replacing the scheduler
5//! reconstructs occupied slots from live worker jobs, without touching their
6//! attempts, passes or paid agent calls. Finite maintenance jobs follow the same
7//! lifetime rule. Explicit parking is durable control, never an upgrade step.
8//!
9//! # A crashed worker is legible
10//!
11//! A task is written `Running`, with its run id, before graph execution. The
12//! worker keeps its claim until the outcome is recorded. Recovery requires both
13//! no live worker reservation and an obtainable task claim, and settles the
14//! saved run through the same policy as a live finish. A scheduler's missing
15//! heartbeat alone is never evidence that a run died.
16//!
17//! # Retries are bounded
18//!
19//! Every attempt at a task consumes one of [`Opts::max_attempts`], after which
20//! the task is [`crate::queue::TaskStatus::Held`] for a human. The one
21//! exception is a run that ended `Stalled`: the panel collapsed because the
22//! agent CLIs hit their quota, which is a fact about the machine and not about
23//! the task, so it must not spend an attempt. Without that exception a quota
24//! outage would quietly hold the entire backlog, and the operator would come
25//! back to a reset quota and nothing left that the loop is willing to run.
26
27use std::path::{Path, PathBuf};
28use std::sync::Arc;
29use std::sync::atomic::{AtomicBool, Ordering};
30use std::sync::{Mutex, MutexGuard};
31use std::time::Duration;
32
33use anyhow::{Context, Result, bail};
34use jiff::Timestamp;
35use serde::{Deserialize, Serialize};
36use tokio::sync::Notify;
37
38use crate::ask::{self, Questions};
39use crate::clean;
40use crate::conduct::Conductor;
41use crate::config::{Config, MergeMode};
42use crate::graph::Runner;
43use crate::land;
44use crate::notices::{self, Link, Notice};
45use crate::queue::{Queue, Task, TaskStatus};
46use crate::run::{Liveness, QuotaLoss, RunState, RunStatus};
47use crate::triage;
48
49/// On-disk format for [`Status`]. Bumped when a field's meaning changes.
50pub const SCHEMA: u32 = 1;
51
52/// How often the status file is refreshed. A reader treats a status file older
53/// than [`STALE_SECS`] as "no daemon", so the heartbeat has to be brisk enough
54/// that a busy daemon is never mistaken for a dead one.
55pub const HEARTBEAT: Duration = Duration::from_secs(5);
56
57/// How old a heartbeat may be before a reader calls the daemon dead. Six
58/// missed beats: long enough to survive a slow filesystem, short enough that
59/// a crashed daemon is not still reported as running a task.
60///
61/// The single threshold every reader shares — the web UI's `/api/health` and
62/// `magi doctor` both call [`Reading::running`] rather than each comparing
63/// against their own copy of this number, so a crashed daemon cannot look
64/// alive on one screen and dead on another.
65pub const STALE_SECS: i64 = 30;
66
67/// Default queue poll interval.
68pub const POLL: Duration = Duration::from_secs(5);
69
70/// How old a claim has to be before startup sweeps it. Longer than any run
71/// this graph plausibly takes, so a sweep cannot pull a task out from under a
72/// daemon that is merely slow.
73pub const STALE_CLAIM: Duration = Duration::from_secs(6 * 60 * 60);
74
75/// How long a task may sit [`TaskStatus::Running`] with no live daemon's
76/// heartbeat naming it before [`crate::conduct`] is shown it as stalled.
77///
78/// [`reclaim_orphaned_running`] settles most crashes immediately, on every
79/// poll, by attempting the task's own claim: a dead pid is proof enough for
80/// [`sweep_stale_claims`] to drop the lock the same tick, and the very next
81/// claim attempt succeeds. But a lock whose pid cannot be parsed at all — an
82/// empty or corrupt `.lock` file — falls back to [`STALE_CLAIM`]'s six-hour
83/// age instead, since there is nothing else to check (see
84/// [`sweep_stale_claims`]'s own doc). For as long as that lock survives, the
85/// claim keeps failing and `reclaim_orphaned_running` correctly leaves the
86/// task `running` — see
87/// `stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet` for
88/// exactly this ordering. `stalled_tasks` is what surfaces that task to the
89/// conductor well before the mechanical six-hour sweep would, and thirty
90/// minutes is comfortably below `STALE_CLAIM` while still being generous
91/// enough that a task merely late to publish its first [`HEARTBEAT`] is
92/// never mistaken for abandoned.
93pub const STALLED_RUNNING: Duration = Duration::from_secs(30 * 60);
94
95/// What the loop is working on, for the status file.
96#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
97#[serde(default)]
98pub struct Current {
99    /// Worker reservation that produced this claim; absent on legacy drivers.
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub worker: Option<String>,
102    /// Task id being run.
103    pub task: String,
104    /// Run id the task produced.
105    pub run: String,
106}
107
108/// The daemon's liveness, published to `<home>/daemon.json`.
109///
110/// This is the only interface between the loop and the web UI, which is why it
111/// carries `updated_at` as well as `started_at`: a reader cannot tell a
112/// running daemon from a `SIGKILL`ed one by the file's existence alone, but it
113/// can compare the heartbeat against the clock.
114#[derive(Debug, Clone, Serialize, Deserialize)]
115pub struct Status {
116    /// On-disk format version.
117    pub schema: u32,
118    /// Process id, so a human can find or kill the daemon.
119    pub pid: u32,
120    /// When this process started.
121    pub started_at: Timestamp,
122    /// Last heartbeat.
123    pub updated_at: Timestamp,
124    /// True when the queue has nothing runnable.
125    pub idle: bool,
126    /// Every task and run currently in flight. More than one entry means the
127    /// loop is driving more than one run at once — see
128    /// [`crate::config::Daemon::max_concurrent_runs`]. Empty, not absent, when
129    /// nothing is running, so a reader never has to treat "no field" and "an
130    /// empty list" as two different kinds of idle.
131    pub current: Vec<Current>,
132    /// Tasks that reached a terminal status in this process.
133    pub completed: usize,
134    /// Queue polls since start, so a wedged loop shows up as a frozen count.
135    pub polls: u64,
136    /// Effective startup capabilities of the question recovery loops.
137    #[serde(default)]
138    pub question_recovery: Option<crate::question_delivery::Recovery>,
139    /// Independent-worker control protocol supported by this scheduler.
140    #[serde(default)]
141    pub worker_protocol: Option<u32>,
142}
143
144impl Status {
145    /// A fresh, idle status for this process.
146    #[must_use]
147    pub fn new() -> Self {
148        let now = Timestamp::now();
149        Self {
150            schema: SCHEMA,
151            pid: std::process::id(),
152            started_at: now,
153            updated_at: now,
154            idle: true,
155            current: Vec::new(),
156            completed: 0,
157            polls: 0,
158            question_recovery: None,
159            worker_protocol: Some(1),
160        }
161    }
162}
163
164impl Default for Status {
165    fn default() -> Self {
166        Self::new()
167    }
168}
169
170/// How the loop should behave.
171#[derive(Debug, Clone, Serialize, Deserialize)]
172#[serde(default)]
173pub struct Opts {
174    /// Repository used by tasks that name none.
175    pub repo: PathBuf,
176    /// Explicit `magi.toml`, instead of the discovered layer stack.
177    pub config: Option<PathBuf>,
178    /// Queue poll interval.
179    pub poll: Duration,
180    /// Attempts a task gets before it is held for a human.
181    pub max_attempts: usize,
182    /// Drain what is runnable now, then return, instead of waiting for more.
183    pub once: bool,
184    /// Merge mode override (`none`, `local`, `pr`); `None` keeps the config's.
185    pub merge: Option<String>,
186    /// Where the janitor's [`crate::clean::fold_orphaned_worktrees`] and
187    /// [`crate::git::worktree_prune`] look for and reclaim worktrees.
188    /// `None` resolves to [`crate::run::default_worktree_root`] - the
189    /// operator's real `~/wt/<repo>` - the same way a run with no
190    /// [`crate::config::Graph::worktree_root`] resolves its own. A caller
191    /// that does not own that directory (a test, an embedding that manages
192    /// worktrees itself) must set this, or every idle tick reclaims worktrees
193    /// out from under whoever actually does.
194    pub worktrees_root: Option<PathBuf>,
195}
196
197impl Default for Opts {
198    fn default() -> Self {
199        Self {
200            repo: PathBuf::from("."),
201            config: None,
202            poll: POLL,
203            max_attempts: 2,
204            once: false,
205            merge: None,
206            worktrees_root: None,
207        }
208    }
209}
210
211impl Opts {
212    fn absolute(&self) -> Result<Self> {
213        let mut opts = self.clone();
214        opts.repo = std::path::absolute(&opts.repo)?;
215        opts.config = opts
216            .config
217            .as_deref()
218            .map(std::path::absolute)
219            .transpose()?;
220        opts.worktrees_root = opts
221            .worktrees_root
222            .as_deref()
223            .map(std::path::absolute)
224            .transpose()?;
225        Ok(opts)
226    }
227}
228
229/// How many runs a plain `usize` from config may drive concurrently, floored
230/// at one. A `0` in a config file would otherwise stall the loop entirely -
231/// no runnable task could ever start - which is never what an operator who
232/// wrote `0` meant.
233fn max_concurrent(n: usize) -> usize {
234    n.max(1)
235}
236
237/// Where the status file lives.
238#[must_use]
239pub fn status_path() -> PathBuf {
240    crate::run::home().join("daemon.json")
241}
242
243/// Publish the status file for this process.
244pub fn write_status(status: &Status) -> Result<()> {
245    write_status_to(&status_path(), status)
246}
247
248/// Publish a status to an explicit path.
249///
250/// Written to a sibling `.tmp` and renamed, because the web UI reads this file
251/// on every health poll and must never see a half-written one.
252pub fn write_status_to(path: &Path, status: &Status) -> Result<()> {
253    if let Some(parent) = path.parent() {
254        std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
255    }
256    let body = serde_json::to_string_pretty(status).context("serialize daemon status")?;
257    let tmp = path.with_extension("json.tmp");
258    std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
259    std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
260    Ok(())
261}
262
263/// Delete the status file. Called on the way out so a clean exit reads as
264/// "no daemon" rather than as a daemon whose heartbeat merely stopped.
265pub fn clear_status() {
266    clear_status_at(&status_path());
267}
268
269/// Delete a status file at an explicit path, so the loop's teardown and
270/// [`clear_status`] cannot drift apart: the loop is handed the path it
271/// published to, and a test can watch a temp file disappear.
272fn clear_status_at(path: &Path) {
273    let _ = std::fs::remove_file(path);
274}
275
276/// A cooperative stop, shared with whoever asked the loop to run.
277///
278/// Cloning is how the request travels: [`serve_until`] keeps one handle, the
279/// Ctrl-C listener and the web UI keep others, and every clone points at the
280/// same flag. There is no channel because there is nothing to send — the only
281/// message is "stop", it is idempotent, and a flag cannot be missed by a
282/// receiver that was not listening yet.
283///
284/// A stop ends scheduler dispatch promptly. Its busy snapshot is observational:
285/// detached task workers keep their own lifetimes and ownership after this
286/// handle's scheduler exits.
287#[derive(Debug, Clone, Default)]
288pub struct Stop {
289    /// Set once, never cleared: a stop is not something an operator takes back
290    /// half way through, and a clearable flag would let a start racing a stop
291    /// resurrect a loop that is already unwinding.
292    stopped: Arc<AtomicBool>,
293    /// Live task workers observed by the scheduler's latest dispatch snapshot.
294    busy: Arc<std::sync::atomic::AtomicUsize>,
295    /// Wakes the idle wait. Without this a stop would not be seen until the
296    /// poll interval elapsed, and an operator tapping stop on a phone would
297    /// watch a button do nothing for five seconds.
298    wake: Arc<Notify>,
299    /// Handed to the run in flight, so a stop can also mean "park at the next
300    /// node boundary" instead of "finish the whole competition first".
301    pause: crate::graph::Pause,
302}
303
304impl Stop {
305    /// A stop nobody has asked for yet.
306    #[must_use]
307    pub fn new() -> Self {
308        Self::default()
309    }
310
311    /// Ask the loop to stop. Idempotent, and safe to call before the loop
312    /// starts: the flag is checked before the first poll.
313    pub fn stop(&self) {
314        self.stopped.store(true, Ordering::SeqCst);
315        // `notify_one` rather than `notify_waiters` because the loop may not be
316        // parked yet: this stores a permit, so a wait that registers a moment
317        // later returns at once instead of sleeping out the whole interval.
318        self.wake.notify_one();
319    }
320
321    /// Has a stop been asked for?
322    #[must_use]
323    pub fn stopped(&self) -> bool {
324        self.stopped.load(Ordering::SeqCst)
325    }
326
327    /// Whether a requested scheduler retirement still has an active snapshot.
328    /// Workers continue independently after the scheduler has retired.
329    #[must_use]
330    pub fn finishing(&self) -> bool {
331        self.stopped() && self.busy_now()
332    }
333
334    /// Ask the loop to stop *and* the run in flight to park at its next node
335    /// boundary.
336    ///
337    /// Unlike plain stop, explicit park asks workers to checkpoint at their
338    /// existing safe boundaries. Binary replacement never needs a park.
339    pub fn park(&self, cause: crate::run::ParkCause) {
340        self.pause.park_for(cause);
341        self.stop();
342    }
343
344    /// Has a park been asked for?
345    #[must_use]
346    pub fn parking(&self) -> bool {
347        self.pause.parked()
348    }
349
350    /// The pause handle to give a runner.
351    #[must_use]
352    pub fn pause(&self) -> crate::graph::Pause {
353        self.pause.clone()
354    }
355
356    /// Whether the scheduler's latest snapshot contains active task workers.
357    #[must_use]
358    pub fn busy_now(&self) -> bool {
359        self.busy.load(Ordering::SeqCst) > 0
360    }
361
362    /// Wait out one poll interval, returning early once a stop is asked for.
363    async fn idle(&self, poll: Duration) {
364        tokio::select! {
365            () = tokio::time::sleep(poll) => {}
366            () = self.wake.notified() => {}
367        }
368    }
369}
370
371/// The daemon's published state, read permissively.
372///
373/// This mirrors [`Status`], but is a separate declaration on purpose: every
374/// field defaults, so a status file from an older or newer magi still yields
375/// a usable reading — one this build has never heard of — instead of a parse
376/// error that hides the daemon entirely.
377#[derive(Debug, Clone, Default, Deserialize)]
378#[serde(default)]
379pub struct Reading {
380    /// Format version the daemon claims.
381    pub schema: u32,
382    /// Daemon process id, for an operator who wants to stop it.
383    pub pid: Option<u32>,
384    /// When that process started.
385    pub started_at: Option<Timestamp>,
386    /// Last heartbeat. Absent means the file is unusable, hence not running.
387    pub updated_at: Option<Timestamp>,
388    /// True when the queue had nothing runnable at the last poll.
389    pub idle: bool,
390    /// What the daemon is working on. Empty means idle; more than one entry
391    /// means more than one run is in flight at once.
392    ///
393    /// `deserialize_with` rather than the plain derive: a daemon started
394    /// before this field became a list is still out there writing the old
395    /// shape — a single `{"task":...,"run":...}` object, or its absence —
396    /// on every heartbeat until it is restarted, and a live process reading
397    /// that file during the rollout must still see it as running rather than
398    /// as absent. A bare type change here would fail the whole struct's
399    /// deserialization on a type mismatch, defeating the permissiveness this
400    /// type exists for.
401    #[serde(deserialize_with = "de_current")]
402    pub current: Vec<Current>,
403    /// Tasks this daemon process has finished.
404    pub completed: u64,
405    /// Queue polls this daemon process has made.
406    pub polls: u64,
407    /// Effective startup capabilities of the question recovery loops.
408    #[serde(default)]
409    pub question_recovery: Option<crate::question_delivery::Recovery>,
410    /// Independent-worker control protocol, absent on legacy embedded loops.
411    pub worker_protocol: Option<u32>,
412}
413
414/// Accept the old single-`Current`-or-absent shape as well as the current
415/// list, so a reader never has to know which build wrote the file.
416fn de_current<'de, D>(deserializer: D) -> std::result::Result<Vec<Current>, D::Error>
417where
418    D: serde::Deserializer<'de>,
419{
420    #[derive(Deserialize)]
421    #[serde(untagged)]
422    enum Shape {
423        Many(Vec<Current>),
424        One(Current),
425    }
426    Ok(
427        Option::<Shape>::deserialize(deserializer)?.map_or_else(Vec::new, |shape| match shape {
428            Shape::Many(v) => v,
429            Shape::One(c) => vec![c],
430        }),
431    )
432}
433
434impl Reading {
435    /// Seconds since the last heartbeat, or `None` when there has never been
436    /// one.
437    #[must_use]
438    pub fn age_secs(&self, now: Timestamp) -> Option<i64> {
439        self.updated_at
440            .map(|at| (now.as_second() - at.as_second()).max(0))
441    }
442
443    /// Whether the loop counts as running: a heartbeat no older than
444    /// [`STALE_SECS`]. The alternative is a reader that claims a task is in
445    /// progress hours after the daemon that owned it was killed.
446    #[must_use]
447    pub fn running(&self, now: Timestamp) -> bool {
448        self.age_secs(now).is_some_and(|secs| secs <= STALE_SECS)
449    }
450}
451
452/// Read `<home>/daemon.json` permissively, or `None` when there is nothing
453/// usable there.
454///
455/// Missing, half-written and unparseable all collapse to `None`, because the
456/// only question a reader asks is whether a daemon is alive, and a file it
457/// cannot read is not evidence that one is.
458#[must_use]
459pub fn read_status(home: &Path) -> Option<Reading> {
460    let body = std::fs::read_to_string(home.join("daemon.json")).ok()?;
461    serde_json::from_str(&body).ok()
462}
463
464/// Read-only evidence of runs owned by a live daemon or independent worker.
465///
466/// CLI, sandboxed conversation controls and Web cleanup share this observation.
467/// A stale daemon heartbeat does not invalidate a worker's OS-held lease.
468/// Starting reservations and unknown worker state remain protected; observing
469/// them never creates, reconciles or archives files in the worker store.
470/// Callers interested in one identity use [`is_working_on`] or
471/// [`is_working_on_task`].
472#[must_use]
473pub fn current_work(home: &Path, now: Timestamp) -> Vec<Current> {
474    let mut current = read_status(home)
475        .filter(|reading| reading.running(now))
476        .map(|reading| reading.current)
477        .unwrap_or_default();
478    let workers = crate::worker::observe_active(home).and_then(|jobs| {
479        jobs.into_iter()
480            .filter(|job| job.kind == "task")
481            .map(|job| {
482                let request: TaskWorker = serde_json::from_value(job.payload)?;
483                let run = Queue::at(request.queue)
484                    .get(&request.task)
485                    .ok()
486                    .and_then(|task| task.runs.last().cloned())
487                    .unwrap_or_default();
488                Ok(Current {
489                    worker: Some(job.id),
490                    task: request.task,
491                    run,
492                })
493            })
494            .collect::<Result<Vec<_>>>()
495    });
496    match workers {
497        Ok(workers) => {
498            for worker in workers {
499                if !current.iter().any(|claim| {
500                    claim.task == worker.task
501                        && claim.run == worker.run
502                        && claim.worker == worker.worker
503                }) {
504                    current.push(worker);
505                }
506            }
507        }
508        Err(error) => {
509            // This API gates destructive cleanup. Unknown worker ownership
510            // protects every known task/run instead of pretending it is idle.
511            tracing::error!("cannot determine active workers: {error:#}");
512            current.extend(
513                Queue::at(home.join("queue"))
514                    .list()
515                    .into_iter()
516                    .map(|task| Current {
517                        worker: None,
518                        task: task.id,
519                        run: task.runs.last().cloned().unwrap_or_default(),
520                    }),
521            );
522            current.extend(
523                crate::run::list_ids_in(&home.join("runs"))
524                    .into_iter()
525                    .map(|run| Current {
526                        worker: None,
527                        task: String::new(),
528                        run,
529                    }),
530            );
531        }
532    }
533    current
534}
535
536/// Whether a live daemon is working on this run at this moment.
537#[must_use]
538pub fn is_working_on(home: &Path, run: &str, now: Timestamp) -> bool {
539    current_work(home, now).iter().any(|c| c.run == run)
540}
541
542/// Admission may ignore only this process's confirmed worker reservation.
543/// Keep anonymous/legacy daemon claims and every other worker, even for the
544/// same task. The run's execution lease and process identity are checked by
545/// the caller under the owner lock as well.
546pub(crate) fn is_working_on_other(home: &Path, run: &str, now: Timestamp) -> Result<bool> {
547    // A helper or test may inherit an identity from a different run store.
548    // That identity grants no exception here; retain all ownership evidence.
549    let same_home = std::env::var_os("MAGI_WORKER_HOME")
550        .is_some_and(|worker_home| Path::new(&worker_home) == home);
551    let caller = if same_home {
552        crate::worker::current_job(home)?
553    } else {
554        None
555    }
556    .filter(|job| {
557        job.kind == "task"
558            && job.status == crate::worker::Status::Running
559            && job.pid == Some(std::process::id())
560    });
561    Ok(other_claims_run(
562        &current_work(home, now),
563        run,
564        caller.as_ref().map(|job| job.id.as_str()),
565    ))
566}
567
568fn other_claims_run(claims: &[Current], run: &str, caller: Option<&str>) -> bool {
569    claims
570        .iter()
571        .any(|claim| claim.run == run && !(caller.is_some() && claim.worker.as_deref() == caller))
572}
573
574/// Whether a live daemon is working on a run whose short id is this one.
575///
576/// For a worktree that has no run record to compare against at all -
577/// [`crate::clean::fold_orphaned_worktrees`]'s whole reason to exist - a full
578/// id is not available to hand to [`is_working_on`]. The short id is: a run's
579/// worktree bay is named after it (see [`crate::run::RunState::worktree_root`]),
580/// and it is exactly the gap between the daemon claiming a task and
581/// `RunState::new` saving the first `run.json` that this exists to protect -
582/// a run genuinely in flight but invisible to a scan of `runs/`.
583#[must_use]
584pub fn is_working_on_short(home: &Path, short: &str, now: Timestamp) -> bool {
585    current_work(home, now)
586        .iter()
587        .any(|c| crate::run::short_of(&c.run) == short)
588}
589
590/// Whether a live daemon is working on this task at this moment.
591#[must_use]
592pub fn is_working_on_task(home: &Path, task: &str, now: Timestamp) -> bool {
593    current_work(home, now).iter().any(|c| c.task == task)
594}
595
596/// Remove claim files whose owner is provably dead, or that have simply
597/// outlived `older_than`, and return the task ids swept.
598///
599/// A daemon killed with `SIGKILL` never runs [`crate::queue::Claim`]'s
600/// destructor, and the orphaned `.lock` file would make its task permanently
601/// unclaimable — the backlog would stop for good at exactly the task that was
602/// in flight when the machine went down.
603///
604/// The pid recorded in the lock is the authority whenever it can be read at
605/// all; age is only a fallback for when it cannot be.
606///
607/// - **A parseable pid wins outright.** [`crate::proc::pid_alive`] decides,
608///   full stop — dead sweeps the lock immediately, regardless of age; alive
609///   protects it, regardless of age. This is what lets a lock be reclaimed in
610///   seconds instead of waiting out [`STALE_CLAIM`]: a lock made 33 minutes
611///   before this daemon even started, next to a `queued` task, no longer has
612///   to sit for six hours before anything notices its owner is gone.
613/// - **A pid that cannot be parsed at all** — an empty or corrupt lock file —
614///   falls back to `older_than`, since there is nothing else to check.
615///
616/// Age must never override a *positive* liveness confirmation. `sweep`
617/// polls concurrently with independently running task workers. A worker may
618/// legitimately run longer than `older_than`; its live pid must still protect
619/// its claim. Age alone must never turn that claim into a second task attempt,
620/// which [`reclaim_orphaned_running`] would then read as abandoned and hand
621/// to a second attempt — two `Runner`s writing the same `run.json` and the
622/// same worktree at once. `pid_alive` answering "alive" for anything it
623/// cannot determine (a live process, a pid this build cannot check, one
624/// under another account) is exactly what keeps that path from ever
625/// firing on a guess.
626///
627/// [`STALE_CLAIM`] itself stays large: a helper program missing or its
628/// output unreadable must not be license to guess, and the risk of an
629/// unparseable lock outliving a genuinely dead owner is bounded by an order
630/// of magnitude above any plausible run rather than by a positive check.
631///
632/// Runs on every poll, not only at startup — a daemon up for days must keep
633/// noticing a lock some other, now-dead, daemon left behind just as readily
634/// as one it trips over on the way up.
635pub fn sweep_stale_claims(queue: &Queue, older_than: Duration) -> Vec<String> {
636    sweep_stale_claims_with(queue, older_than, crate::proc::pid_alive)
637}
638
639/// [`sweep_stale_claims`] with its process-query boundary supplied by the
640/// caller. This keeps the lock policy testable where process listing is
641/// unavailable, while production still uses the platform query above.
642fn sweep_stale_claims_with<F>(queue: &Queue, older_than: Duration, pid_alive: F) -> Vec<String>
643where
644    F: Fn(u32) -> bool,
645{
646    let this_process = std::process::id();
647    let mut swept: Vec<String> = std::fs::read_dir(queue.root())
648        .into_iter()
649        .flatten()
650        .flatten()
651        .map(|e| e.path())
652        .filter(|p| p.extension().is_some_and(|x| x == "lock"))
653        .filter(|p| {
654            match std::fs::read_to_string(p)
655                .ok()
656                .and_then(|body| body.trim().parse::<u32>().ok())
657            {
658                // This process wrote it and is asking the question right
659                // now, so it is definitionally still alive - settled without
660                // spawning a helper process at all.
661                Some(pid) if pid == this_process => false,
662                Some(pid) => !pid_alive(pid),
663                None => p
664                    .metadata()
665                    .and_then(|m| m.modified())
666                    .and_then(|t| t.elapsed().map_err(std::io::Error::other))
667                    .is_ok_and(|age| age >= older_than),
668            }
669        })
670        .filter(|p| std::fs::remove_file(p).is_ok())
671        .filter_map(|p| {
672            p.file_stem()
673                .and_then(|s| s.to_str())
674                .map(std::borrow::ToOwned::to_owned)
675        })
676        .collect();
677    swept.sort_unstable();
678    swept
679}
680
681/// Is `task` stalled: [`TaskStatus::Running`], past [`STALLED_RUNNING`], with
682/// no live daemon's heartbeat naming it? Deterministic — no model call, and
683/// the exact test [`stalled_tasks`] uses to decide what `crate::conduct` is
684/// shown.
685fn is_stalled(task: &Task, home: &Path, now: Timestamp) -> bool {
686    task.status == TaskStatus::Running
687        && (now.as_second() - task.updated_at.as_second()) >= STALLED_RUNNING.as_secs() as i64
688        && !is_working_on_task(home, &task.id, now)
689}
690
691/// Every task [`is_stalled`] right now — "止まったタスク" in
692/// `crate::conduct`'s vocabulary.
693fn stalled_tasks(queue: &Queue, home: &Path, now: Timestamp) -> Vec<Task> {
694    queue
695        .list()
696        .into_iter()
697        .filter(|t| is_stalled(t, home, now))
698        .collect()
699}
700
701/// Runnable tasks a dependency can still be set on — "runnable なタスク" in
702/// `crate::conduct`'s vocabulary. Deliberately `Queued` only, not
703/// `Failed`-and-so-also-runnable: a task that already attempted and lost
704/// belongs in [`finished_tasks`], where the question is a recovery, not a
705/// dependency.
706fn queued_tasks(queue: &Queue) -> Vec<Task> {
707    queue
708        .list()
709        .into_iter()
710        .filter(|t| t.status == TaskStatus::Queued)
711        .collect()
712}
713
714/// `Failed`/`Held` tasks nobody has decided a recovery for yet — "終わった
715/// タスク" in `crate::conduct`'s vocabulary.
716fn finished_tasks(queue: &Queue) -> Vec<Task> {
717    queue
718        .list()
719        .into_iter()
720        .filter(|t| matches!(t.status, TaskStatus::Failed | TaskStatus::Held))
721        .collect()
722}
723
724/// Deterministically resolve `Task::blocked_by`: a dependency task that
725/// reached `Done`, or a question that was answered, is removed — no model
726/// involved, on every poll. An answered question's content is copied onto
727/// the task ([`Task::record_answer`]) before its id is dropped, so it
728/// reaches the next `crate::conduct` prompt and the next run's instruction
729/// (see [`instruction_for`]) rather than only clearing the block.
730///
731/// A `blocked_by` id that names neither an existing task nor an existing
732/// question - `magi task rm` (or an operator by hand) deleted it while this
733/// task was still waiting - is caught before any of that: it can never
734/// become `Done` or `Answered`, so the ordinary loop below would otherwise
735/// leave the task `blocked` forever with nothing to notice. Such a task is
736/// quarantined to a machine hold instead ([`crate::queue::missing_blocker_hold_reason`]),
737/// which puts it in front of `crate::triage::run_once`'s own walk the next
738/// time it runs - see that module's doc for why the choice is "ask a human",
739/// never "assume the missing dependency was satisfied and unblock anyway".
740fn resolve_blockers(queue: &Queue, questions: &Questions) {
741    for listed in queue.list() {
742        if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
743            continue;
744        }
745        let Ok(_claim) = queue.claim(&listed.id) else {
746            continue;
747        };
748        let Ok(mut task) = queue.get(&listed.id) else {
749            continue;
750        };
751        if task.status != TaskStatus::Blocked {
752            continue;
753        }
754        // A dependency deleted on purpose is released, not held - and before
755        // the missing check, so a pass that races the delete (or a claim that
756        // made `Queue::remove` skip this task) settles it quietly.
757        let deleted = queue.apply_deleted_blockers(&mut task, questions);
758        if !deleted.is_empty() {
759            record(queue, &mut task);
760            for id in &deleted {
761                queue.note_dependency_deleted(&task, id);
762            }
763            if task.status != TaskStatus::Blocked {
764                continue;
765            }
766        }
767        let missing = crate::queue::missing_blockers(queue, questions, &task.blocked_by);
768        if !missing.is_empty() {
769            let language = language_of(&task, Path::new("."));
770            let mut cause = missing.clone();
771            cause.sort();
772            cause.dedup();
773            task.notice_cause(&format!("missing-blockers:{}", cause.join(",")), None, None);
774            task.hold_machine(Some(crate::queue::missing_blocker_hold_reason_in(
775                &task.blocked_by,
776                &missing,
777                &language,
778            )));
779            record(queue, &mut task);
780            continue;
781        }
782        // A conductor question nobody answered in time is retired by the
783        // waiter, and nothing else would ever move the task it blocks.
784        if let Some(q) = task.blocked_by.iter().find_map(|id| {
785            let crate::queue::Dependency::Question(full) =
786                crate::queue::dependency(queue, questions, id)
787            else {
788                return None;
789            };
790            questions.get(&full).ok().filter(|q| {
791                q.node == crate::conduct::NODE && q.status == ask::QuestionStatus::Abandoned
792            })
793        }) {
794            let language = language_of(&task, Path::new("."));
795            task.notice_cause(&format!("unanswered-question:{}", q.id), None, None);
796            task.hold_machine(Some(unanswered_question_hold_reason(&q, &language)));
797            record(queue, &mut task);
798            continue;
799        }
800        let mut changed = false;
801        for id in task.blocked_by.clone() {
802            let resolved = crate::queue::dependency(queue, questions, &id);
803            if let crate::queue::Dependency::Task(full) = &resolved {
804                if queue
805                    .get(full)
806                    .is_ok_and(|dep| dep.status == TaskStatus::Done)
807                {
808                    task.unblock(&id);
809                    changed = true;
810                }
811                continue;
812            }
813            if let crate::queue::Dependency::Question(full) = resolved
814                && let Ok(q) = questions.get(&full)
815                && q.status == ask::QuestionStatus::Answered
816            {
817                // The action sweep releases conductor blockers atomically
818                // with their selected operation. A fresh deputy lease must
819                // never leave an answered hold temporarily runnable.
820                if q.node == crate::conduct::NODE
821                    && q.chosen_action().is_some()
822                    && !task.action_applied(&q.id)
823                {
824                    continue;
825                }
826                let answer = match &q.answer {
827                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
828                    None => String::new(),
829                };
830                task.record_answer(q.summary.clone(), answer);
831                task.unblock(&id);
832                changed = true;
833            }
834        }
835        if changed {
836            record(queue, &mut task);
837        }
838    }
839}
840
841/// The `hold_reason` of a task whose conductor question went unanswered.
842fn unanswered_question_hold_reason(q: &ask::Question, language: &str) -> String {
843    if crate::lang::is_japanese(language) {
844        format!(
845            "質問 {} 「{}」 に期限内の回答がなく、取り下げられました - `magi task triage` を参照",
846            q.short(),
847            q.summary
848        )
849    } else {
850        format!(
851            "question {} \"{}\" went unanswered and was abandoned - see `magi task triage`",
852            q.short(),
853            q.summary
854        )
855    }
856}
857
858/// Where `q`'s chosen action stands for `task`. `daemon_will_act` is false
859/// for several unrelated reasons, and the waiter must not read them alike.
860#[derive(Debug, Clone, Copy, PartialEq, Eq)]
861pub(crate) enum ActionStanding {
862    /// The answer carries no action: the waiter delivers it as before.
863    NoAction,
864    /// The daemon will apply it (not applied, task idle, current attempt).
865    Pending,
866    /// Already applied (`Task::actions_applied`): the daemon has acted, so
867    /// delivering the word to the old seat would run it beside the new work.
868    Applied,
869    /// The question is about an earlier attempt than the task's latest.
870    Stale,
871    /// The task is running / blocked / done: the daemon defers for now.
872    Busy,
873}
874
875impl ActionStanding {
876    /// The daemon has acted or will act: the waiter must not deliver.
877    pub(crate) fn daemon_owns(self) -> bool {
878        matches!(self, Self::Pending | Self::Applied | Self::Stale)
879    }
880}
881
882/// Classify `q`'s chosen action against `task`. `Stale` is judged before
883/// `Busy`: a question about an earlier attempt must be stopped even while a
884/// newer competition is running.
885pub(crate) fn action_standing(task: &Task, q: &ask::Question) -> ActionStanding {
886    if q.chosen_action().is_none() {
887        ActionStanding::NoAction
888    } else if task.action_applied(&q.id) {
889        ActionStanding::Applied
890    } else if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
891        ActionStanding::Stale
892    } else if matches!(
893        task.status,
894        TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
895    ) {
896        ActionStanding::Busy
897    } else {
898        ActionStanding::Pending
899    }
900}
901
902/// What [`decide_action`] concluded about one answered question.
903#[derive(Debug, Clone, PartialEq, Eq)]
904enum ActionDecision {
905    /// Nothing to do now (no action, already applied, or the task is busy).
906    Skip,
907    /// Continue the named run instead of competing again.
908    Resume(String),
909    /// Requeue as a fresh competition.
910    Requeue,
911    /// Hold the task by explicit operator choice.
912    Hold,
913    /// Close the task as done.
914    Done,
915    /// The question is about an earlier attempt than the task's latest; it
916    /// is recorded as handled and changes nothing.
917    Stale,
918    /// The action cannot be carried out; hold the task and say why. Never
919    /// falls back to something else, because the operator chose this one.
920    Refuse(String),
921}
922
923/// Decide what the choice answered on `q` means for `task`. Pure: `load`
924/// reads a run's state, as with [`unfinished_run_with`].
925///
926/// `Resume` only fires on the task's *latest* run, and only while that run
927/// could actually make progress ([`RunStatus::resumable`], not released, review
928/// budget left); an answer naming anything else is refused rather than
929/// reinterpreted as a fresh competition.
930fn decide_action<F>(task: &Task, q: &ask::Question, p: &Phrases, load: F) -> ActionDecision
931where
932    F: FnOnce(&str) -> Result<RunState>,
933{
934    let Some(action) = q.chosen_action() else {
935        return ActionDecision::Skip;
936    };
937    if task.action_applied(&q.id)
938        || matches!(
939            task.status,
940            TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
941        )
942    {
943        return ActionDecision::Skip;
944    }
945    // A question about an earlier attempt must not act on a newer one. A
946    // conductor question is keyed by the task id, not a run, so it is exempt.
947    if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
948        return ActionDecision::Stale;
949    }
950    let repair = q.node == land::APPROVAL_NODE && q.resolution().as_deref() == Some(land::REPAIR);
951    let stopping = q.node == land::APPROVAL_NODE
952        && q.resolution()
953            .as_deref()
954            .is_some_and(crate::merge_decision::stops);
955    // An answer is the owner's decision as of when it was given: a manual hold
956    // placed before it (even after the question was asked) was seen and
957    // overruled by it, while a hold or release after it supersedes it.
958    let decision_at = q.answered_at.unwrap_or(q.asked_at);
959    if task.operator_decided_at.is_some_and(|at| at > decision_at) {
960        return if repair || stopping {
961            ActionDecision::Refuse(format!(
962                "{} 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 {}`",
963                if repair { "repair" } else { "stop" },
964                q.id,
965                q.run,
966                task.id
967            ))
968        } else {
969            ActionDecision::Stale
970        };
971    }
972    match action {
973        a if a.maintenance() => ActionDecision::Skip,
974        ask::ChoiceAction::ResumeRun { .. }
975        | ask::ChoiceAction::ReleaseTask { .. }
976        | ask::ChoiceAction::RerunChecks { .. }
977        | ask::ChoiceAction::AbandonRun { .. } => unreachable!(),
978        ask::ChoiceAction::Requeue => ActionDecision::Requeue,
979        ask::ChoiceAction::Hold => ActionDecision::Hold,
980        ask::ChoiceAction::Done => ActionDecision::Done,
981        ask::ChoiceAction::Resume { run } => {
982            if task.runs.last() != Some(run) {
983                return ActionDecision::Refuse((p.resume_not_latest)(
984                    q.short(),
985                    ask::short_id(run),
986                ));
987            }
988            match load(run) {
989                Ok(s) if stopping => {
990                    if s.merge_decision.as_ref().is_some_and(|d| d.closed)
991                        || !s
992                            .land_approval
993                            .as_ref()
994                            .is_some_and(|binding| binding.question == q.id)
995                    {
996                        ActionDecision::Stale
997                    } else if s.liveness(false) == Liveness::Live {
998                        ActionDecision::Skip
999                    } else if s.status == RunStatus::Landing
1000                        && !s.released()
1001                        && s.retired_to.is_none()
1002                    {
1003                        ActionDecision::Resume(run.clone())
1004                    } else {
1005                        ActionDecision::Refuse("Owner stop decision cannot resume its original landing execution; inspect the existing run. No replacement or merge was started.".into())
1006                    }
1007                }
1008                Ok(s)
1009                    if q.node == land::APPROVAL_NODE
1010                        && q.resolution().as_deref() == Some(land::REPAIR) =>
1011                {
1012                    if s.merge_repairs.iter().any(|r| r.question == q.id)
1013                        || s.land_approval.as_ref().is_some_and(|a| a.question != q.id)
1014                    {
1015                        // A live/manual driver already consumed or superseded
1016                        // this answer. Do not hold its fresh approval wait.
1017                        ActionDecision::Stale
1018                    } else if s.liveness(false) == Liveness::Live {
1019                        ActionDecision::Skip
1020                    } else if s.status != RunStatus::Landing
1021                        || s.released()
1022                        || s.reviews.is_empty()
1023                        || !implementers_match(task, &s)
1024                        || !s
1025                            .land_approval
1026                            .as_ref()
1027                            .is_some_and(|a| a.question == q.id && !a.head.is_empty())
1028                    {
1029                        ActionDecision::Refuse(format!(
1030                            "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",
1031                            q.id, run, run
1032                        ))
1033                    } else {
1034                        ActionDecision::Resume(run.clone())
1035                    }
1036                }
1037                Ok(s) if s.liveness(false) == Liveness::Live => {
1038                    ActionDecision::Refuse("run already has a live driver".into())
1039                }
1040                Ok(s) => match crate::handover::resume_refusal(&s) {
1041                    None => ActionDecision::Resume(run.clone()),
1042                    Some(reason) => ActionDecision::Refuse((p.resume_cannot_progress)(
1043                        q.short(),
1044                        ask::short_id(run),
1045                        &reason.diagnostic(&s),
1046                    )),
1047                },
1048                Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
1049                    q.short(),
1050                    ask::short_id(run),
1051                    &format!("{e:#}"),
1052                )),
1053            }
1054        }
1055    }
1056}
1057
1058/// The fixed prose the daemon writes into [`Task::last_error`] and
1059/// [`Task::hold_reason`], in the language of `[graph] language`. Same shape as
1060/// `triage::Wording` and `land::Words`: only English and Japanese are
1061/// translated, anything else falls back to English.
1062///
1063/// Rendered when the reason is *generated*, so a reason keeps the language it
1064/// was written in if the setting changes later. The notification frame
1065/// (`Task <id> is held:`) is not here and stays English.
1066///
1067/// Deliberately **not** translated, because other code reads them back by
1068/// string: the disk gate prefixes (`triage::is_disk_hold`), `out of attempts`
1069/// and `gate red`. IDs, node names, paths and external error text are embedded
1070/// as they are.
1071struct Phrases {
1072    /// `{}` = status label, then the detail.
1073    graph_stopped: fn(&str, &str) -> String,
1074    quorum_lost: &'static str,
1075    /// Followed by the seats' names.
1076    quota_took_out: &'static str,
1077    /// Followed by the status label.
1078    run_ended: &'static str,
1079    /// Followed by the question's short id.
1080    waiting_for_answer: &'static str,
1081    recovered_running: &'static str,
1082    no_run_to_recover: &'static str,
1083    could_not_start: &'static str,
1084    resume_not_latest: fn(&str, &str) -> String,
1085    resume_cannot_progress: fn(&str, &str, &str) -> String,
1086    resume_unreadable: fn(&str, &str, &str) -> String,
1087    /// A takeover refusal: the operator-facing text. English is the error's own
1088    /// `Display`; a translation keeps the machine detail apart in parentheses.
1089    handover_refused: fn(&crate::handover::Refused) -> String,
1090    /// Appended to a refused handover's hold reason (leading space included).
1091    handover_hint: &'static str,
1092    /// (seats that never answered, review rounds) for the review loop's
1093    /// "refusing to call it clean" stop.
1094    reviewers_never_answered: fn(usize, usize) -> String,
1095}
1096
1097const PHRASES_EN: Phrases = Phrases {
1098    graph_stopped: |status, detail| {
1099        format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
1100    },
1101    quorum_lost: "the judging panel lost its quorum",
1102    quota_took_out: "; quota took out ",
1103    run_ended: "run ended ",
1104    waiting_for_answer: " - waiting for operator answer to question ",
1105    recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
1106    no_run_to_recover: "task was `running` with no live daemon and no readable \
1107                        run to recover; held for a human to check what happened",
1108    could_not_start: "could not start the run: ",
1109    resume_not_latest: |q, run| {
1110        format!("question {q} asked to resume run {run}, which is not this task's latest run")
1111    },
1112    resume_cannot_progress: |q, run, reason| {
1113        format!("question {q} asked to resume run {run}, which cannot make progress: {reason}")
1114    },
1115    resume_unreadable: |q, run, e| {
1116        format!("question {q} asked to resume run {run}, which could not be read: {e}")
1117    },
1118    handover_refused: |r| r.to_string(),
1119    handover_hint: " (clean up the other worktree, then release the task from the queue)",
1120    reviewers_never_answered: |missing, rounds| {
1121        format!(
1122            "{missing} reviewer seat(s) never answered after {rounds} rounds; \
1123             refusing to call it clean"
1124        )
1125    },
1126};
1127
1128const PHRASES_JA: Phrases = Phrases {
1129    graph_stopped: |status, detail| {
1130        format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
1131    },
1132    quorum_lost: "審査パネルが定足数を失いました",
1133    quota_took_out: "。クォータで脱落: ",
1134    run_ended: "run 終了: ",
1135    waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
1136    recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
1137    no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
1138                        何が起きたか人が確認するため保留にしました",
1139    could_not_start: "run を開始できませんでした: ",
1140    resume_not_latest: |q, run| {
1141        format!(
1142            "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
1143        )
1144    },
1145    resume_cannot_progress: |q, run, reason| {
1146        format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません: {reason}")
1147    },
1148    resume_unreadable: |q, run, e| {
1149        format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
1150    },
1151    handover_refused: |r| {
1152        use crate::handover::Refused;
1153        match r {
1154            Refused::Foreign { branch, path, why } => format!(
1155                "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
1156                 削除しません。不要なら `git worktree remove` でその worktree を削除して\
1157                 から、やり直してください(詳細: {why})"
1158            ),
1159            Refused::Unsafe { branch, path, why } => format!(
1160                "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
1161                 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
1162                 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
1163            ),
1164            Refused::ReleaseFailed { branch, path, run } => format!(
1165                "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
1166                 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1167                 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1168            ),
1169        }
1170    },
1171    handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1172    reviewers_never_answered: |missing, rounds| {
1173        format!(
1174            "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1175             クリーンとは認めません"
1176        )
1177    },
1178};
1179
1180fn phrases(language: &str) -> &'static Phrases {
1181    if crate::lang::is_japanese(language) {
1182        &PHRASES_JA
1183    } else {
1184        &PHRASES_EN
1185    }
1186}
1187
1188/// The language of the repository a task belongs to, read best-effort for the
1189/// paths that have no run (and so no config of their own) to ask. An unreadable
1190/// config is English, not an error: a hold reason must still get written.
1191fn language_of(task: &Task, fallback: &Path) -> String {
1192    crate::lang::of_repo(&repo_for(task, fallback))
1193}
1194
1195/// The task an answered question speaks for: the one whose runs include the
1196/// question's run, or - for a conductor question, filed under the task's own
1197/// id - the task with that id.
1198pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1199    if q.node == crate::conduct::NODE {
1200        return tasks.iter().find(|t| t.id == q.run);
1201    }
1202    tasks.iter().find(|t| t.runs.contains(&q.run))
1203}
1204
1205/// Legacy conductor prose never becomes a maintenance command by inference.
1206/// Replace unsupported open labels under the question lock before dispatch.
1207fn repair_choice_offers(questions: &Questions) {
1208    for q in questions.list().into_iter().filter(|q| {
1209        q.status.open()
1210            && q.node == crate::conduct::NODE
1211            && q.choices
1212                .iter()
1213                .any(|c| crate::choice_effect::describe(q, c).is_none())
1214    }) {
1215        let _ = questions.update(&q.id, |current| {
1216            if current.status.open() {
1217                crate::choice_effect::executable_conductor(current);
1218                if let Some(deputy) = &mut current.deputy {
1219                    deputy.brief = crate::deputy::brief(
1220                        &current.run,
1221                        &current.detail,
1222                        &current.choices,
1223                        &current.actions,
1224                    );
1225                }
1226            }
1227            Ok(())
1228        });
1229    }
1230}
1231
1232/// Apply answered typed choices. Only the daemon calls this in production;
1233/// deputies settle the question and never execute its actions.
1234pub async fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1235    apply_maintenance_choices(queue, questions, home).await;
1236    apply_task_choice_actions(queue, questions, home);
1237}
1238
1239/// Apply bounded maintenance effects independently of question ownership: a
1240/// release watcher need not have a queue task, and a predecessor is another run.
1241async fn apply_maintenance_choices(queue: &Queue, questions: &Questions, home: &Path) {
1242    for q in questions.list() {
1243        let Some(action) = q.chosen_action().filter(|a| a.maintenance()) else {
1244            continue;
1245        };
1246        // Receipt paths use question IDs, whose format is independent of run
1247        // IDs. Apply the question store's filename safety rule to both eras.
1248        if asker_may_still_read(questions, &q, home) || !ask::valid_asset_name(&q.id) {
1249            continue;
1250        }
1251        let dir = home.join("choice-actions");
1252        if std::fs::create_dir_all(&dir).is_err() {
1253            continue;
1254        }
1255        let Ok(lock) = std::fs::OpenOptions::new()
1256            .create(true)
1257            .truncate(false)
1258            .write(true)
1259            .open(dir.join(format!("{}.lock", q.id)))
1260        else {
1261            continue;
1262        };
1263        if crate::pr_head::try_lock_file(&lock).is_err() {
1264            continue;
1265        }
1266        let fresh = !home
1267            .join("choice-actions")
1268            .join(format!("{}.json", q.id))
1269            .exists();
1270        let result = async {
1271            let receipt = dir.join(format!("{}.json", q.id));
1272            if receipt.exists() {
1273                let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&receipt)?)?;
1274                anyhow::ensure!(
1275                    prior.get("status").and_then(|s| s.as_str()) == Some("applied"),
1276                    "previous maintenance attempt did not confirm completion; inspect its receipt"
1277                );
1278                return Ok::<_, anyhow::Error>(());
1279            }
1280            // Never retry an uncertain external effect. The receipt is written
1281            // before calling gh, exactly like release_watch's rerun record.
1282            let record = |status: &str| -> anyhow::Result<()> {
1283                let tmp = receipt.with_extension("tmp");
1284                std::fs::write(
1285                    &tmp,
1286                    serde_json::to_vec(&serde_json::json!({
1287                        "action": action, "status": status,
1288                    }))?,
1289                )?;
1290                std::fs::rename(tmp, &receipt)?;
1291                Ok(())
1292            };
1293            let applied = async {
1294                match action {
1295                    ask::ChoiceAction::ResumeRun { run } => {
1296                        crate::resume::validate(home, run)?;
1297                        record("started")?;
1298                        let decided = q.answered_at.unwrap_or(q.asked_at);
1299                        if !crate::resume::pin_queued(queue, run, Some(decided), Some(&q.id))? {
1300                            crate::resume::validate_unqueued(home, run)?;
1301                            crate::resume::start(home, run.clone()).await?;
1302                        }
1303                    }
1304                    ask::ChoiceAction::ReleaseTask {
1305                        task,
1306                        held_at,
1307                        reason,
1308                    } => {
1309                        anyhow::ensure!(
1310                            queue.resolve_id(task)? == *task,
1311                            "task action requires an exact task ID"
1312                        );
1313                        let _claim = queue.claim(task)?;
1314                        let mut task = queue.get(task)?;
1315                        if task.action_applied(&q.id) {
1316                            return Ok(());
1317                        }
1318                        // Filing this conductor question temporarily wraps the
1319                        // original hold in a Blocked state. Restore only that
1320                        // exact blocker on the local copy before checking the
1321                        // hold binding; unrelated waits never authorize release.
1322                        if q.node == crate::conduct::NODE
1323                            && q.run == task.id
1324                            && task.status == TaskStatus::Blocked
1325                            && task.blocked_from == Some(TaskStatus::Held)
1326                            && task.blocked_by.as_slice() == [q.id.as_str()]
1327                        {
1328                            task.unblock(&q.id);
1329                        }
1330                        anyhow::ensure!(
1331                            task.status == TaskStatus::Held
1332                                && task.held_at == Some(*held_at)
1333                                && task.hold_reason.as_deref() == reason.as_deref()
1334                                && task
1335                                    .operator_decided_at
1336                                    .is_none_or(|at| at <= q.answered_at.unwrap_or(q.asked_at)),
1337                            "task no longer has the hold this question names"
1338                        );
1339                        task.release_operator("choice", Some(&q.id));
1340                        task.mark_action_applied(&q.id);
1341                        queue.put(&mut task)?;
1342                    }
1343                    ask::ChoiceAction::AbandonRun { run } => {
1344                        record("started")?;
1345                        crate::driver::abandon_proven_dead(home, run)?;
1346                    }
1347                    ask::ChoiceAction::RerunChecks {
1348                        repo,
1349                        pr,
1350                        head,
1351                        runs,
1352                    } => {
1353                        rerun_checks_once(home, &q.id, repo, pr, head, runs, || record("started"))
1354                            .await?;
1355                    }
1356                    _ => unreachable!(),
1357                }
1358                Ok::<_, anyhow::Error>(())
1359            }
1360            .await;
1361            match applied {
1362                Ok(()) => record("applied"),
1363                Err(e) => {
1364                    record(&format!("refused or failed: {e:#}"))?;
1365                    Err(e)
1366                }
1367            }
1368        }
1369        .await;
1370        // Retire the originating blocker as well as the target operation.
1371        // A foreign resume leaves its issuer held instead of competing beside
1372        // the execution just started. Other successful maintenance lets the
1373        // original task retry its normal, guarded path.
1374        if home
1375            .join("choice-actions")
1376            .join(format!("{}.json", q.id))
1377            .exists()
1378            && let Some(listed) = task_of_question(&queue.list(), &q)
1379            && !listed.action_applied(&q.id)
1380            && let Ok(_claim) = queue.claim(&listed.id)
1381            && let Ok(mut origin) = queue.get(&listed.id)
1382        {
1383            if !origin.operator_held()
1384                && origin.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1385                && !matches!(origin.status, TaskStatus::Running | TaskStatus::Done)
1386            {
1387                if result.is_err() || matches!(action, ask::ChoiceAction::ResumeRun { .. }) {
1388                    origin.hold_machine(Some(format!(
1389                        "Maintenance choice {} settled; inspect its target before releasing this task",
1390                        q.id
1391                    )));
1392                } else {
1393                    origin.unblock(&q.id);
1394                }
1395            }
1396            origin.mark_action_applied(&q.id);
1397            let _ = queue.put(&mut origin);
1398        }
1399        if let Err(e) = result
1400            && fresh
1401        {
1402            notices::raise_in(
1403                home,
1404                Notice::warn(
1405                    &format!("action:{}", q.id),
1406                    format!("Choice action {} was not completed: {e:#}", q.id),
1407                )
1408                .link(if q.run_names_task() {
1409                    Link::Task { id: q.run.clone() }
1410                } else {
1411                    Link::Run { id: q.run.clone() }
1412                }),
1413            );
1414        }
1415    }
1416}
1417
1418/// Rerun the named failed workflow runs of a pull request, each at most once
1419/// per `request` (a question id, or a chat operation identity). The head,
1420/// lifecycle and failed state are re-read from the forge first; `started` is
1421/// called once those checks pass and before the first external call, and the
1422/// ledger entry is written before every `gh` call, so an uncertain result is
1423/// never repeated automatically.
1424pub(crate) async fn rerun_checks_once(
1425    home: &Path,
1426    request: &str,
1427    repo: &Path,
1428    pr: &str,
1429    head: &str,
1430    runs: &[String],
1431    started: impl FnOnce() -> anyhow::Result<()>,
1432) -> anyhow::Result<()> {
1433    use crate::release_watch::{GhForge, ReleaseForge};
1434    anyhow::ensure!(
1435        !runs.is_empty()
1436            && runs.len() <= 20
1437            && runs
1438                .iter()
1439                .all(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
1440            && !pr.starts_with('-'),
1441        "invalid rerun targets"
1442    );
1443    let snap = GhForge.snapshot(repo, pr).await?;
1444    anyhow::ensure!(
1445        snap.head == head && snap.state == crate::land::PrLifecycle::Open,
1446        "pull request head or lifecycle changed"
1447    );
1448    anyhow::ensure!(
1449        runs.iter().all(|r| snap
1450            .checks
1451            .iter()
1452            .any(|c| c.run.as_ref() == Some(r) && crate::release_watch::is_failed(c.verdict))),
1453        "named workflow is no longer failed on this pull request"
1454    );
1455    started()?;
1456    let dir = home.join("choice-actions");
1457    std::fs::create_dir_all(&dir)?;
1458    let rerun_lock = std::fs::OpenOptions::new()
1459        .create(true)
1460        .truncate(false)
1461        .write(true)
1462        .open(dir.join("reruns.lock"))?;
1463    crate::pr_head::try_lock_file(&rerun_lock)?;
1464    let ledger = dir.join("reruns.json");
1465    let mut recorded: std::collections::BTreeSet<String> = if ledger.exists() {
1466        serde_json::from_slice(&std::fs::read(&ledger)?)?
1467    } else {
1468        Default::default()
1469    };
1470    for run in runs {
1471        let key = serde_json::to_string(&(request, repo, pr, head, run))?;
1472        if !recorded.insert(key) {
1473            continue;
1474        }
1475        let tmp = ledger.with_extension("tmp");
1476        std::fs::write(&tmp, serde_json::to_vec(&recorded)?)?;
1477        std::fs::rename(tmp, &ledger)?;
1478        GhForge.rerun(repo, run).await?;
1479    }
1480    Ok(())
1481}
1482
1483/// Carry out the [`ask::ChoiceAction`] attached to each answered choice, once.
1484///
1485/// Runs on every poll before the conductor looks at the queue. The task is
1486/// re-read under its claim, so a task somebody completed or held by hand in
1487/// the meantime is judged on what it is now. `Resume` releases the task and
1488/// records a pinned [`crate::queue::OperatorResume`], which `crate::conduct`
1489/// honours (no re-hold, no requeue) until the task runs and [`attempt`]'s
1490/// ordinary `unfinished_run` logic resumes that same run.
1491pub(crate) fn apply_task_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1492    let tasks = queue.list();
1493    for q in questions.list() {
1494        // Dismissal is committed by the question writer, never a resume.
1495        if q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1496            continue;
1497        }
1498        if q.chosen_action().is_none_or(|a| a.maintenance()) {
1499            continue;
1500        }
1501        let Some(listed) = task_of_question(&tasks, &q) else {
1502            if q.node == land::APPROVAL_NODE
1503                && q.resolution().as_deref().is_some_and(|choice| {
1504                    choice == land::REPAIR || crate::merge_decision::stops(choice)
1505                })
1506            {
1507                notices::raise_in(
1508                    home,
1509                    Notice::warn(
1510                        &format!("repair-owner:{}", q.id),
1511                        format!(
1512                            "Approval action is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing task.",
1513                            q.run, q.run
1514                        ),
1515                    ).link(Link::Run { id: q.run.clone() }),
1516                );
1517            }
1518            continue;
1519        };
1520        if listed.action_applied(&q.id) {
1521            continue;
1522        }
1523        let Ok(_claim) = queue.claim(&listed.id) else {
1524            continue;
1525        };
1526        let Ok(mut task) = queue.get(&listed.id) else {
1527            continue;
1528        };
1529        // Work only on this local copy until the action can be committed.
1530        // In particular, a fresh lease below leaves the persisted task blocked.
1531        if q.node == crate::conduct::NODE && task.status == TaskStatus::Blocked {
1532            let blockers: Vec<_> = task
1533                .blocked_by
1534                .iter()
1535                .filter(|id| {
1536                    crate::queue::dependency(queue, questions, id)
1537                        == crate::queue::Dependency::Question(q.id.clone())
1538                })
1539                .cloned()
1540                .collect();
1541            if !blockers.is_empty() {
1542                for id in blockers {
1543                    task.unblock(&id);
1544                }
1545                let answer = match &q.answer {
1546                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
1547                    None => String::new(),
1548                };
1549                task.record_answer(q.summary.clone(), answer);
1550            }
1551        }
1552        let language = language_of(&task, Path::new("."));
1553        let decision = decide_action(&task, &q, phrases(&language), |id| {
1554            RunState::load_under(id, home)
1555        });
1556        let ran = matches!(
1557            decision,
1558            ActionDecision::Resume(_)
1559                | ActionDecision::Requeue
1560                | ActionDecision::Hold
1561                | ActionDecision::Done
1562        );
1563        if ran && asker_may_still_read(questions, &q, home) {
1564            // The asking process or its seat can still take the word; act
1565            // once it has gone quiet. Bound on the remaining window: the
1566            // check is not atomic with the write below, so an asker that
1567            // takes the word in between (at most one poll, never more than
1568            // `ask::LEASE_TTL`) only prints it - it never touches the task,
1569            // and `Task::actions_applied` under the claim keeps the action to
1570            // one application. The waiter does not deliver an answer that
1571            // carries an action (`waiter::decide_owned`), so it cannot race.
1572            continue;
1573        }
1574        let done = matches!(decision, ActionDecision::Done);
1575        match decision {
1576            ActionDecision::Skip => continue,
1577            ActionDecision::Resume(run) => {
1578                task.release_operator("choice", Some(&q.id));
1579                task.resume_override = Some(crate::queue::OperatorResume {
1580                    question_id: q.id.clone(),
1581                    at: Timestamp::now(),
1582                    conductor_rehold: None,
1583                    forced: true,
1584                    pinned_run: Some(run),
1585                });
1586            }
1587            ActionDecision::Stale => {}
1588            ActionDecision::Requeue => {
1589                task.release_operator("choice-requeue", Some(&q.id));
1590                task.requeue();
1591            }
1592            ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1593            ActionDecision::Done => task.succeed(),
1594            ActionDecision::Refuse(why) => {
1595                if task.operator_held() {
1596                    // A rejected answer does not release the operator's hold
1597                    // or reclassify it as recoverable by the conductor.
1598                    task.hold_reason = Some(match task.hold_reason.take() {
1599                        Some(reason) => format!("{reason}\n\n{why}"),
1600                        None => why,
1601                    });
1602                } else {
1603                    task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1604                    task.hold_machine(Some(why));
1605                }
1606                notices::raise(
1607                    Notice::warn(
1608                        &format!("action:{}", q.id),
1609                        "An answer asked the daemon to resume a run that cannot be resumed; the task stays held.",
1610                    )
1611                    .link(Link::Task {
1612                        id: task.id.clone(),
1613                    }),
1614                );
1615            }
1616        }
1617        task.mark_action_applied(&q.id);
1618        // The applied id travels with the transition, so a failed save loses
1619        // neither and the answer is acted on at the next poll.
1620        record(queue, &mut task);
1621        if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1622            supersede_prior_runs(&task, home);
1623        }
1624        // Delivery is only a note of who has read the answer; the task's own
1625        // mark above is the authority. Best effort.
1626        let _ = questions.update(&q.id, |r| {
1627            r.answer_delivered = true;
1628            Ok(())
1629        });
1630    }
1631}
1632
1633/// Whether something may still read the answer to `q`: a fresh lease, or the
1634/// asking seat still listed as active in its run (its CLI can outlive the
1635/// `magi ask` that was killed).
1636fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1637    let now = Timestamp::now();
1638    if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1639        return true;
1640    }
1641    q.node != crate::conduct::NODE
1642        && RunState::load_under(&q.run, home).is_ok_and(|s| {
1643            s.seats_active()
1644                .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1645        })
1646}
1647
1648/// Retire an unanswered conductor question after its task no longer refers to
1649/// it. Conductor questions use the task id in `Question::run`, so run-based
1650/// cleanup cannot observe a manual release or completion.
1651///
1652/// Restricted to `Question::node == crate::conduct::NODE`: an ordinary run's
1653/// own question also carries a `run`, and a run id that happens to collide
1654/// with some task's id is not this loop's business — only a conductor
1655/// question actually uses the task id that way. One `Questions::list()` scan
1656/// is taken up front and matched against the in-memory task set, rather than
1657/// calling `Questions::open_for` (a full disk scan on its own) once per task.
1658fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1659    let tasks = queue.list();
1660    let by_id: std::collections::BTreeMap<&str, &Task> =
1661        tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1662    let referenced: Vec<&str> = tasks
1663        .iter()
1664        .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1665        .collect();
1666
1667    for mut question in questions.list() {
1668        if !question.status.open() || question.node != crate::conduct::NODE {
1669            continue;
1670        }
1671        // Keep questions a task still names, including when the reference
1672        // moved to a dependent task.
1673        // Preserve even ambiguous references: retiring a possibly referenced
1674        // question is unsafe until the operator disambiguates it.
1675        if referenced
1676            .iter()
1677            .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1678        {
1679            continue;
1680        }
1681        let Some(task) = by_id.get(question.run.as_str()) else {
1682            continue;
1683        };
1684        question.abandon(format!(
1685            "task {} no longer waits for this answer",
1686            task.short()
1687        ));
1688        if let Err(e) = questions.put(&mut question) {
1689            tracing::warn!(
1690                "could not retire question {} for task {}: {e:#}",
1691                question.short(),
1692                task.short()
1693            );
1694        }
1695    }
1696}
1697
1698/// What a finished run tells the queue about the task it came from.
1699///
1700/// A struct rather than a fourth and fifth boolean argument: the two flags
1701/// answer different questions about the same run, and a call site passing
1702/// `(…, true, false)` is one transposition away from refunding attempts
1703/// forever.
1704#[derive(Debug, Clone, Copy)]
1705pub struct Verdict {
1706    /// Where the graph stopped.
1707    pub status: RunStatus,
1708    /// The run opened a pull request.
1709    pub left_pr: bool,
1710    /// At least one seat was lost to a rate limit.
1711    pub quota_hit: bool,
1712    /// The run parked at a node boundary because it was asked to.
1713    pub parked: bool,
1714    /// The run never produced a single candidate a judge could look at.
1715    ///
1716    /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
1717    /// still have another candidate worth judging, in which case the loss was
1718    /// not the reason nothing came of the run. This is `true` only when the
1719    /// implement wave ended with nothing viable at all.
1720    pub no_viable_candidates: bool,
1721}
1722
1723/// Record a finished run against the task it came from.
1724///
1725/// Kept pure and separate from the loop because this mapping *is* the retry
1726/// policy, and a policy that can only be exercised by spawning a graph is a
1727/// policy nobody checks. The table:
1728///
1729/// | run status                           | task becomes        | attempt spent |
1730/// |---------------------------------------|---------------------|---------------|
1731/// | parked at a boundary                  | `Parked` (requeued) | **no**        |
1732/// | `Merged`, `Ready`                      | `Done`               | yes          |
1733/// | `AlreadyInBase`                        | `Done`, with a note  | **no**        |
1734/// | `Stalled`, quota hit                   | `Failed` (requeued) | **no**        |
1735/// | `Failed`, quota hit, no viable cand.   | `Failed` (requeued) | **no**        |
1736/// | `Stalled`, no quota                    | `Failed`, or `Held`  | yes          |
1737/// | recorded authentication/resource stop | `Held` (machine)     | **no**       |
1738/// | recorded usage-limit node stop       | `Failed` (requeued)  | **no**       |
1739/// | `Blocked` with a PR                    | `Held`               | yes          |
1740/// | `Blocked`, `Failed` otherwise          | `Failed`, or `Held`  | yes          |
1741/// | `VerifiedNoop`                          | `Held`               | yes          |
1742/// | anything non-terminal                  | `Failed`, or `Held`  | yes          |
1743///
1744/// The `VerifiedNoop` row is independent of the `Failed`-quota row above it,
1745/// deliberately: every candidate agreeing there is nothing to write is not a
1746/// machine fact about a rate limit, it is an unverified claim about the
1747/// *task* that a human still has to check — see [`RunStatus::VerifiedNoop`]'s
1748/// own doc and [`Task::handed_off`]. `Held` rather than `Done` on purpose: the
1749/// claim could be wrong (a misread instruction, a stale check), and closing
1750/// the task automatically on an implementer's say-so would be the exact
1751/// failure mode task 391f's own audit was raised to avoid. `attempt spent` is
1752/// `yes` here for the same reason it is on the `Blocked`-with-a-PR row just
1753/// above, which settles through the same [`Task::handed_off`]: `Held` is not
1754/// `Failed`-and-requeued, so nothing retries this task on the same unverified
1755/// claim regardless of whether the one already-spent attempt is refunded, and
1756/// [`Task::release`] resets the count to zero anyway the moment a human looks
1757/// at the evidence and lets it run again.
1758///
1759/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
1760/// twice, together. A quorum lost to rate limits is a property of the machine
1761/// and not of the task, so the attempt is refunded and a reset quota picks
1762/// the work up where it stopped — and that is just as true when every
1763/// implement seat lost the same race and `after_implement` bails with nothing
1764/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
1765/// machine fact. The `no_viable_candidates` guard is what keeps that row
1766/// narrow: a `Failed` run that produced a real candidate which then lost for
1767/// some other reason still spends the attempt, exactly like the quorum lost
1768/// to judges that answered with the wrong shape is ordinary flakiness, and
1769/// refunding *that* takes the bound off the retry loop entirely: run e633
1770/// stalled with `quota: []` after two judges wrote unusable JSON, was
1771/// refunded, and the next attempt paid for a fresh hour-long implement wave
1772/// before it could fail the same way. `max_attempts` exists precisely so
1773/// that cannot repeat forever.
1774///
1775/// A non-terminal status means `execute` returned while the graph was still
1776/// mid-flight, which is a bug rather than a verdict; it is treated as a
1777/// failure so that a task cannot loop on it either.
1778///
1779/// `left_pr` splits the `Blocked` row, and it is the difference between a run
1780/// that failed and a run that finished into a gate. See [`Task::handed_off`].
1781pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1782    settle_in(task, verdict, detail, max_attempts, &PHRASES_EN)
1783}
1784
1785/// [`settle`], with the daemon's own fixed prose in `p`'s language.
1786fn settle_in(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize, p: &Phrases) {
1787    // A parked run is the operator's own doing, and its work is intact on
1788    // disk. The task goes back in line with its attempt refunded so the next
1789    // loop resumes the same run - which `one_task` prefers over competing
1790    // again - and so that swapping the binary a few times cannot exhaust a
1791    // budget meant for agents that actually misbehaved.
1792    if verdict.parked {
1793        task.park(detail);
1794        return;
1795    }
1796    match verdict.status {
1797        RunStatus::Merged | RunStatus::Ready
1798            if task.pr_recovery.as_ref().is_some_and(|s| {
1799                s.disposition != Some(crate::pr_recovery::Disposition::Review)
1800            }) =>
1801        {
1802            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()));
1803        }
1804        RunStatus::Merged | RunStatus::Ready => task.succeed(),
1805        RunStatus::AlreadyInBase => task.already_landed(detail),
1806        RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1807        RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1808            task.stall(detail)
1809        }
1810        RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1811        RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1812        RunStatus::Blocked => task.fail(detail, max_attempts),
1813        RunStatus::VerifiedNoop => task.handed_off(detail),
1814        other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1815    }
1816}
1817
1818/// Rewrite this task's now-moot earlier attempts — [`Task::superseded_attempts`]
1819/// — from `Blocked`/`Stalled` to [`RunStatus::Superseded`], once the task
1820/// itself has actually finished *and* its own last attempt is provably why:
1821/// this loads that run and requires `Merged`/`Ready` before touching
1822/// anything earlier in `runs`, since `Task::succeed` can also be called
1823/// directly on a task whose last attempt never landed at all.
1824///
1825/// Called right after whatever call set `task.status` to
1826/// [`TaskStatus::Done`] — this module's own `settle`'s callers below and
1827/// `reclaim`'s, but also every other place a task can be closed by hand
1828/// without the loop ever settling it itself: `magi task done`
1829/// (`main::TaskCmd::Done`) and `POST /api/queue/{id}/done`
1830/// (`web::queue_done`). Closing a task by hand — after confirming a manual
1831/// GitHub merge, say, exactly the workflow this repository's own
1832/// "Landing a run's winner by hand" documents — is just as much "this task's
1833/// story is over" as a daemon-driven `Merged`/`Ready` is, and skipping it
1834/// there would leave every earlier attempt stuck at `Blocked`/`Stalled`
1835/// forever, which is the exact backlog this status exists to clear. `pub`
1836/// for those two out-of-module callers; everything else about this stays
1837/// internal bookkeeping.
1838///
1839/// A run something is still actually driving is left alone: a
1840/// task cannot be `Done` while one of its *own* attempts is still in flight,
1841/// so a live one at this point can only be an unrelated process — a manual
1842/// `--resume` of this old, now-moot run — and rewriting under it would just
1843/// be undone (back to `Blocked`/`Stalled`, or worse) the next time that
1844/// process itself saves. This is the same `daemon_claims` + [`RunState::liveness`]
1845/// pair `run_report`/`run_detail` use for the same question elsewhere:
1846/// `is_working_on` alone only ever proves a *daemon* claim, not a `magi run
1847/// --resume` invoked by hand outside it, which `liveness` also checks via
1848/// the run's own recorded `driver_pid`. Anything not `Blocked` or `Stalled`
1849/// (already terminal in some other way, or itself mid-run) is left untouched
1850/// too.
1851///
1852/// Best-effort, like the rest of this module's bookkeeping: a load or save
1853/// failure here is a `tracing::warn`, not a failed settle, and the next time
1854/// this same task's completion is recorded — or a daemon restart replays
1855/// `reclaim_orphaned_running` — is another chance to catch up. There is no
1856/// separate reconciliation pass; if that gap ever matters in practice, one
1857/// can be added then.
1858///
1859/// `home` is a parameter, not the process-global [`crate::run::home`], for
1860/// the same reason [`RunState::save_under`] takes one: `web::queue_done`
1861/// calls this with `ui.home`, which is `crate::run::home()` in a real
1862/// process but a fixture's own directory under test — falling through to
1863/// the global there would read and write through whichever home some other
1864/// test in the same binary happened to pin into that `OnceLock` first, not
1865/// the run this call actually means.
1866pub fn supersede_prior_runs(task: &Task, home: &Path) {
1867    let now = Timestamp::now();
1868    // `Task::superseded_attempts` cannot tell a loop-driven `Done` (always
1869    // right behind a `Merged`/`Ready` verdict) from one set directly by
1870    // `magi task done`/its web equivalent/the conductor on a task whose last
1871    // recorded attempt never actually landed - that requires reading the
1872    // run itself, which is exactly what this does before trusting anything
1873    // in `runs` is safe to relabel.
1874    let last_run_succeeded = task
1875        .runs
1876        .last()
1877        .and_then(|id| RunState::load_under(id, home).ok())
1878        .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
1879    for id in task.superseded_attempts(last_run_succeeded) {
1880        let mut state = match RunState::load_under(id, home) {
1881            Ok(s) => s,
1882            Err(e) => {
1883                tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
1884                continue;
1885            }
1886        };
1887        if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
1888            continue;
1889        }
1890        let daemon_claims = is_working_on(home, id, now);
1891        if state.liveness(daemon_claims) == Liveness::Live {
1892            continue;
1893        }
1894        state.status = RunStatus::Superseded;
1895        if let Err(e) = state.save_under(home) {
1896            tracing::warn!("could not mark run {id} superseded: {e:#}");
1897        }
1898    }
1899}
1900
1901/// Catch up every `Done` task [`supersede_prior_runs`] could not fully
1902/// finish the moment it was called, because one of its earlier attempts was
1903/// still live then - a `magi run --resume` invoked by hand on an old run,
1904/// most likely.
1905///
1906/// That skip is correct at the time (rewriting under a run something is
1907/// still actively saving would just be undone), but a task only ever
1908/// reaches `Done` once, so without this nothing would ever look at it
1909/// again: if that manual process later ends anywhere other than
1910/// `Merged`/`Ready` - abandoned, or landed as another `Blocked` - the
1911/// skipped attempt would sit at `Blocked`/`Stalled` forever, exactly the
1912/// backlog this status exists to clear. Called on the same idle-only
1913/// cadence as [`janitor`], next to it rather than folded into it: this
1914/// walks `queue` and `janitor` never otherwise needs one.
1915///
1916/// Simply re-running [`supersede_prior_runs`] over every `Done` task with
1917/// more than one attempt, every pass: each call is a handful of local file
1918/// reads bounded by that task's own attempt count, the same order of cost
1919/// [`clean::fold_due`] already pays scanning every run on disk on the same
1920/// cadence, and a task already fully resolved costs one failed liveness
1921/// check turned no-op the moment its lingering attempt is no longer live.
1922fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
1923    for task in queue.list() {
1924        if task.status != TaskStatus::Done || task.runs.len() < 2 {
1925            continue;
1926        }
1927        supersede_prior_runs(&task, home);
1928    }
1929}
1930
1931/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
1932/// task ends up held.
1933///
1934/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
1935/// dead daemon never got back to) share this, so the two cannot drift into
1936/// disagreeing about which held tasks get a diagnostic.
1937fn settle_and_diagnose(
1938    task: &mut Task,
1939    verdict: Verdict,
1940    detail: &str,
1941    max_attempts: usize,
1942    state: &RunState,
1943) {
1944    let p = phrases(&state.config.graph.language);
1945    // Shared by normal completion and crash recovery, under the task claim.
1946    // No new attempt can own the task until the old driver has exited.
1947    if let Some(d) = &state.merge_decision {
1948        use crate::merge_decision as md;
1949        if task.runs.last().is_some_and(|id| id != &state.id) {
1950            return;
1951        }
1952        if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
1953            task.succeed();
1954        } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
1955            if state.liveness(false) != Liveness::Dead {
1956                task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
1957                return;
1958            }
1959            let replacement = md::Replacement {
1960                question: d.question.clone(),
1961                run: state.id.clone(),
1962                pr: d.target.pr.clone(),
1963                agent: agent.to_owned(),
1964                context: format!(
1965                    "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
1966                    d.target.pr,
1967                    state.id,
1968                    serde_json::to_string(&state.reviews).unwrap_or_default()
1969                ),
1970            };
1971            task.requeue();
1972            task.pr_recovery = None;
1973            task.review_of = None;
1974            task.replacement = Some(replacement);
1975        } else {
1976            task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
1977                format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
1978            } 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())) }));
1979        }
1980        task.mark_action_applied(&d.question);
1981        if let Some(pass) = state.passes.last() {
1982            task.record_pass_at(
1983                &state.id,
1984                pass.index,
1985                Some(pass.started_at),
1986                task.attempts,
1987                None,
1988            );
1989        }
1990        return;
1991    }
1992    if let Some(replacement) = &task.replacement
1993        && !state.parked
1994        && state.resource_block.is_none()
1995        && (state.viable().is_empty()
1996            || (state.status == RunStatus::Blocked && state.tally.is_none()))
1997    {
1998        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)));
1999        return;
2000    }
2001    if !verdict.parked && verdict.quota_hit && state.status == RunStatus::Stalled {
2002        let mut agents: Vec<_> = state
2003            .quota
2004            .iter()
2005            .filter(|q| {
2006                q.cause == crate::agent::QuotaCause::Authentication
2007                    && state
2008                        .passes
2009                        .last()
2010                        .is_none_or(|pass| q.at >= pass.started_at)
2011            })
2012            .map(|q| q.agent.as_str())
2013            .collect();
2014        agents.sort_unstable();
2015        agents.dedup();
2016        if !agents.is_empty() {
2017            task.stall(detail);
2018            task.notice_cause("agent-authentication", None, None);
2019            task.hold_machine(Some(format!("[authentication] Agents {} cannot authenticate; re-authenticate, then resume the held task. No attempt was spent.", agents.join(", "))));
2020            return;
2021        }
2022    }
2023    let attempts_before = task.attempts;
2024    // A run that stopped because a shared resource stayed busy was never a
2025    // failure of the task or of an agent. Earlier nodes may have run; only
2026    // the blocked operation lacks a result. The attempt is
2027    // refunded and the task is held by the machine, under a reason `triage`
2028    // can re-check, so the same run resumes with the same agents once the
2029    // resource is free. A park request still wins (it is the operator's).
2030    if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
2031        task.notice_cause(
2032            &format!("resource:{}:{}", block.kind, block.node),
2033            None,
2034            None,
2035        );
2036        task.last_error = Some(detail.to_owned());
2037        task.diagnostic = None;
2038        task.attempts = task.attempts.saturating_sub(1);
2039        if block.kind == "agent authentication" {
2040            task.hold_machine(Some(format!(
2041                "[authentication] {}; no attempt was spent",
2042                block.detail
2043            )));
2044        } else if block.kind == "agent usage limit" {
2045            // Usage limits keep the existing cooldown-and-resume policy.
2046            if let Some(agent) = &state.config.graph.selected_implementer {
2047                task.hold_machine(Some(format!("[agent usage limit] Selected implementer `{agent}` is unavailable. No other implementer was dispatched; resume after usage is available. No attempt was spent.")));
2048            } else {
2049                task.status = TaskStatus::Failed;
2050                task.last_error = Some(block.detail.clone());
2051            }
2052        } else if block.kind == "disk pressure" {
2053            task.hold_machine(Some(format!(
2054                "{}{}",
2055                crate::disk::RUNNING_PRESSURE,
2056                block.detail
2057            )));
2058        } else {
2059            task.hold_machine(Some(format!(
2060                "{}{}; no attempt was spent; resume to retry the affected operation",
2061                crate::cache::RESOURCE_HOLD,
2062                block.description()
2063            )));
2064        }
2065        if let Some(pass) = state.passes.last() {
2066            task.record_pass_at(
2067                &state.id,
2068                pass.index,
2069                Some(pass.started_at),
2070                attempts_before,
2071                None,
2072            );
2073        }
2074        return;
2075    }
2076    if let Some(hold) = state.land_unrelated.as_ref().filter(|hold| {
2077        state.parked
2078            && state.status == RunStatus::Landing
2079            && state
2080                .pr_pushed_head
2081                .as_ref()
2082                .is_none_or(|h| h == &hold.head)
2083            && task.runs.last() == Some(&state.id)
2084    }) {
2085        // Settlement and crash recovery share this idempotency key. A later
2086        // explicit resume is a new pass and may refund its own attempt once.
2087        let pass = state.passes.last().map_or(0, |p| p.index);
2088        if !task
2089            .passes
2090            .iter()
2091            .any(|p| p.run == state.id && p.pass_index == pass)
2092        {
2093            task.attempts = task.attempts.saturating_sub(1);
2094        }
2095        task.hold_machine(Some(format!(
2096            "[ci-unrelated] CI failure reproduced on base; owner question {}",
2097            hold.question
2098        )));
2099        task.last_error = Some(detail.to_owned());
2100        task.diagnostic = None;
2101        task.record_pass_at(
2102            &state.id,
2103            pass,
2104            state.passes.last().map(|p| p.started_at),
2105            attempts_before,
2106            Some(crate::run::ParkCause::Question),
2107        );
2108        return;
2109    }
2110    let unresolved = task.hold_notice_cause.clone();
2111    if state.base_sync_blocked() {
2112        // No automatic retry may turn a retained sync stop into a new competition.
2113        task.hold_machine(Some(detail.to_owned()));
2114        task.last_error = Some(detail.to_owned());
2115    } else if !verdict.parked
2116        && task
2117            .pr_recovery
2118            .as_ref()
2119            .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
2120        && matches!(
2121            verdict.status,
2122            RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
2123        )
2124    {
2125        if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
2126            task.succeed();
2127        } else {
2128            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()));
2129        }
2130    } else if !verdict.parked
2131        && task.pr_recovery.is_some()
2132        && matches!(
2133            verdict.status,
2134            RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
2135        )
2136        && !verdict.quota_hit
2137    {
2138        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.")));
2139    } else {
2140        settle_in(task, verdict, detail, max_attempts, p);
2141    }
2142    if !verdict.parked
2143        && !verdict.quota_hit
2144        && matches!(
2145            verdict.status,
2146            RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
2147        )
2148    {
2149        task.recovery_failed(state);
2150    }
2151    if state.prep_failure.is_some() {
2152        // Minting a run whose candidates could not be prepared is not work
2153        // on a newly approved attempt. Keep the unresolved outcome anchor.
2154        task.hold_notice_cause = unresolved;
2155        task.startup_notice_cause("startup-candidates");
2156    }
2157    // Written here, where the refund (or not) is decided, so the history is a
2158    // fact and not a later guess from the run's status.
2159    if let Some(pass) = state.passes.last() {
2160        let parked = match &pass.end {
2161            Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2162            _ => None,
2163        };
2164        task.record_pass_at(
2165            &state.id,
2166            pass.index,
2167            Some(pass.started_at),
2168            attempts_before,
2169            parked,
2170        );
2171    }
2172    if task.status == TaskStatus::Held {
2173        if state.base_sync_blocked() {
2174            task.base_sync_notice(state);
2175        } else if state.prep_failure.is_none() {
2176            task.notice_cause(
2177                label(verdict.status),
2178                Some(&state.id),
2179                state.passes.last().map(|p| p.index),
2180            );
2181        }
2182        task.diagnostic = diagnostic(state);
2183        note_open_question(task, &state.id, p);
2184    }
2185}
2186
2187/// If `task` is held with a `magi ask` question still open on `run`, name the
2188/// question in [`Task::hold_reason`] rather than leaving the hold reading
2189/// only [`describe`]'s run summary.
2190///
2191/// This is the shape task 20260928-191407-05fd left underspecified: an
2192/// implementer settled a verified no-op and filed a question for the
2193/// operator, and the hold that followed said nothing about the question
2194/// waiting on them. Appended, not substituted - [`crate::triage`] parses the
2195/// existing text ([`is_disk_hold`](crate::triage), the answered-question
2196/// marker) and must keep seeing it unchanged.
2197///
2198/// Best-effort: an unreadable question store must not stop a run from
2199/// settling, so this is a no-op rather than a propagated error when
2200/// [`crate::run::try_home`] has nothing to offer or the store is empty.
2201fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2202    let Some(home) = crate::run::try_home() else {
2203        return;
2204    };
2205    let open = Questions::at(home.join("questions")).open_for(run);
2206    let Some(q) = open.first() else {
2207        return;
2208    };
2209    let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2210    decisions.sort_unstable();
2211    task.notice_cause(
2212        &format!("questions:{}", decisions.join(",")),
2213        Some(run),
2214        None,
2215    );
2216    let base = task.hold_reason.clone().unwrap_or_default();
2217    task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2218}
2219
2220/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
2221/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
2222/// by some other means entirely, like a manual `magi run` resume that
2223/// finishes the graph outside the queue's bookkeeping.
2224///
2225/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
2226/// `settle` is separate from `attempt`: a task recovered this way must land
2227/// exactly where a live daemon would have put it — the same policy table,
2228/// not a second one that quietly drifts from it — and that is only checkable
2229/// without spawning a real run.
2230fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2231    match last_run {
2232        Some(state) => {
2233            let verdict = Verdict {
2234                status: state.status,
2235                left_pr: state.pr.is_some(),
2236                quota_hit: state.quota.iter().any(|loss| {
2237                    state
2238                        .passes
2239                        .last()
2240                        .is_none_or(|pass| loss.at >= pass.started_at)
2241                }),
2242                parked: state.parked,
2243                no_viable_candidates: state.viable().is_empty(),
2244            };
2245            let detail = format!(
2246                "{}{}",
2247                phrases(&state.config.graph.language).recovered_running,
2248                describe(&state)
2249            );
2250            settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2251        }
2252        None => {
2253            // No run, so no config of its own: `language` is the task's
2254            // repository's setting, read by the caller.
2255            let why = phrases(language).no_run_to_recover;
2256            task.last_error = Some(why.to_owned());
2257            // The phone shows `hold_reason`, so a task held by the machine
2258            // says why there too and not only in `last_error`.
2259            task.notice_cause("missing-run", None, None);
2260            task.hold_machine(Some(why.to_owned()));
2261        }
2262    }
2263}
2264
2265/// Find every task left at `running` that no live process is actually
2266/// driving, and settle each one against whatever its last run became.
2267///
2268/// # Why a claim is proof, not a guess
2269///
2270/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
2271/// `running`, and the guard is held for the task's whole time in that status:
2272/// `attempt` does not return, and the loop does not move past the scope
2273/// holding the claim, until the run has settled. So a `running` task whose
2274/// lock is gone cannot have a live owner — this process or any other —
2275/// without needing a staleness threshold or a pid check the way
2276/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
2277/// task that never got as far as `running` at all. Taking the claim here is
2278/// the whole test: it either fails, because something really does hold it
2279/// and the task is left alone, or it succeeds, which is the proof — and it is
2280/// kept for the rest of the decision so nothing else can start a competing
2281/// run while this one is being written.
2282///
2283/// Called on every poll, not only at startup, for the reason
2284/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
2285/// keep noticing this, not only on the one morning it happened to restart.
2286fn reclaim_orphaned_running(
2287    queue: &Queue,
2288    max_attempts: usize,
2289    live_workers: &std::collections::BTreeSet<String>,
2290) -> Vec<String> {
2291    let mut reclaimed = Vec::new();
2292    for listed in queue.list() {
2293        if listed.status != TaskStatus::Running || live_workers.contains(&listed.id) {
2294            continue;
2295        }
2296        let Ok(_claim) = queue.claim(&listed.id) else {
2297            continue;
2298        };
2299        // Re-read under the claim: a release or an edit landed by a human
2300        // between the listing above and the claim just taken must not be
2301        // clobbered by a decision based on the stale copy.
2302        let Ok(mut task) = queue.get(&listed.id) else {
2303            continue;
2304        };
2305        if task.status != TaskStatus::Running {
2306            continue;
2307        }
2308        let last_run = task.runs.last().and_then(|id| RunState::load(id).ok());
2309        // `execute` normally abandons a run's own open questions the moment
2310        // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
2311        // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
2312        // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
2313        // with the question still `open`, because the process died before
2314        // reaching that call. `reclaim` itself stays pure on purpose (see its
2315        // own doc), so the same cleanup runs here instead, against the run
2316        // this reclaim is already reading. `settle_run` costs nothing when
2317        // `execute` already got there first.
2318        if let Some(state) = &last_run
2319            && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2320        {
2321            tracing::warn!("abandon questions for {}: {e:#}", state.id);
2322        }
2323        let language = if last_run.is_none() {
2324            language_of(&task, Path::new("."))
2325        } else {
2326            String::new()
2327        };
2328        reclaim(&mut task, last_run, max_attempts, &language);
2329        if task.status == TaskStatus::Done {
2330            supersede_prior_runs(&task, &crate::run::home());
2331        }
2332        record(queue, &mut task);
2333        reclaimed.push(task.id.clone());
2334    }
2335    reclaimed
2336}
2337
2338/// Find every run whose `run.json` is provably dead — every seat it still
2339/// lists as [`crate::run::RunState::active`] has overrun its own timeout, and
2340/// [`crate::run::RunState::liveness`] reads [`crate::run::Liveness::Dead`],
2341/// not merely "no daemon claims it" — and fail it, clearing the leftover
2342/// active seats so the run stops reading as `implementing` (or whichever
2343/// node) forever.
2344///
2345/// [`reclaim_orphaned_running`] settles the *task* a dead daemon left
2346/// `running`, using whatever `run.json` already says — but nothing in that
2347/// path, nor in [`reclaim`], ever writes back to the run itself (`reclaim`
2348/// stays pure on purpose, see its own doc), so a `run.json` a killed process
2349/// never got back to sits exactly where it was left: `active` full of seats
2350/// nobody will ever answer for, `status` stuck on whatever node was in
2351/// flight. `magi show` already tells an operator this in prose (`no live
2352/// daemon claims this run right now`); this is what makes that fact durable
2353/// on disk, the same way a task's own `TaskStatus::Running` does not get to
2354/// stay stuck once nothing is driving it.
2355///
2356/// Runs on every poll, not only at startup, for the reason
2357/// [`sweep_stale_claims`] and [`reclaim_orphaned_running`] already are: a
2358/// daemon up for days must keep noticing a run some other, now-dead, daemon
2359/// left behind just as readily as one it trips over on the way up.
2360///
2361/// Walks `home.join("runs")` directly and reads each `run.json` on its own,
2362/// rather than the process-global [`RunState::load`] / [`crate::run::list_ids`] —
2363/// the same reason [`crate::clean`]'s housekeeping passes take an explicit
2364/// `runs` directory instead: `home` here is a parameter precisely so a test
2365/// can point it away from the operator's real history (see [`drive`]'s own
2366/// doc), and a scan that fell through to the global home anyway would walk
2367/// whichever directory some *other* process or test pinned into that
2368/// `OnceLock` first — mutating runs this call was never handed.
2369fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2370    reclaim_abandoned_runs_with(
2371        home,
2372        now,
2373        crate::proc::pid_status,
2374        crate::proc::process_started_at,
2375    )
2376}
2377
2378/// [`reclaim_abandoned_runs`] with its `driver_pid` liveness/identity queries
2379/// supplied by the caller — mirrors [`sweep_stale_claims_with`], which exists
2380/// for the identical reason: this sweep's real damage (wiping a run's active
2381/// seats and failing it) has to be provable against an injected answer in a
2382/// test, not just the real process table.
2383fn reclaim_abandoned_runs_with<F, G>(
2384    home: &Path,
2385    now: Timestamp,
2386    query: F,
2387    identity: G,
2388) -> Vec<String>
2389where
2390    F: Fn(u32) -> Option<bool>,
2391    G: Fn(u32) -> Option<String>,
2392{
2393    let mut abandoned = Vec::new();
2394    for entry in std::fs::read_dir(home.join("runs"))
2395        .into_iter()
2396        .flatten()
2397        .flatten()
2398    {
2399        let id = entry.file_name().to_string_lossy().into_owned();
2400        if !crate::run::is_run_id(&id) {
2401            continue;
2402        }
2403        // Serialize the proof and save with claims and takeover: a new
2404        // execution must not be overwritten after the liveness observation.
2405        let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2406            continue;
2407        };
2408        // Unreadable is `clean::fold_due`'s problem, not this one's — see
2409        // that module's docs for why a run this cannot parse is left alone
2410        // rather than guessed at. A different schema number is not that: this
2411        // touches only `status` and `active`, never a field whose meaning a
2412        // schema bump changed, so an old record's values serve this exactly
2413        // as well as a current one's (see `clean::read_state`'s own doc for
2414        // the same reasoning applied to folding).
2415        let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2416            continue;
2417        };
2418        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2419            continue;
2420        };
2421        if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2422            continue;
2423        }
2424        // Not `!is_working_on(..)` alone: that is only "no *daemon* claims
2425        // it", which is also the normal, healthy shape of a manual `magi
2426        // run` / `magi review` sharing this same home — this scan walks
2427        // every run on disk, not only ones this daemon itself started. Such
2428        // a run's active seats can legitimately sit past their own timeout
2429        // for a little while (the CLI finishing up, its result still being
2430        // collected) without the process driving it having died. `liveness`
2431        // is what actually tells the two apart, by corroborating
2432        // `driver_pid` against the process it names — see its own doc. Only
2433        // its strongest, provable answer licenses wiping this run's active
2434        // seats and failing it out from under whatever is still running it.
2435        let daemon_claims = is_working_on(home, &id, now);
2436        if state.liveness_under_with(home, daemon_claims, &query, &identity)
2437            != crate::run::Liveness::Dead
2438        {
2439            continue;
2440        }
2441        state.abandon("daemon");
2442        if let Err(e) = state.save_under(home) {
2443            tracing::warn!("could not persist abandoned run {id}: {e:#}");
2444            continue;
2445        }
2446        // This run never passes through `Runner::execute` again, so its end
2447        // is announced here.
2448        if let Some(notice) = notices::run_ended(&state) {
2449            notices::raise_in(home, notice);
2450        }
2451        // The seat that asked is gone for good now, exactly like any other
2452        // door `graph::Runner::settle_questions` closes the moment `status`
2453        // lands somewhere non-resumable - see that method's own doc. Nothing
2454        // else reaches this one before the next `janitor()` startup pass
2455        // (`clean::abandon_settled_questions`), and a daemon that stays up
2456        // for days must not leave an open question badging the operator
2457        // until it happens to restart.
2458        if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2459            tracing::warn!("abandon questions for {id}: {e:#}");
2460        }
2461        abandoned.push(id);
2462    }
2463    abandoned
2464}
2465
2466#[derive(Debug, Clone, Serialize, Deserialize)]
2467struct TaskWorker {
2468    opts: Opts,
2469    queue: PathBuf,
2470    task: String,
2471    #[serde(default)]
2472    lane: PermitKind,
2473    #[serde(default)]
2474    standalone: bool,
2475}
2476
2477fn task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2478    Ok(crate::worker::active(home)?
2479        .into_iter()
2480        .filter(|job| job.kind == "task")
2481        .collect())
2482}
2483
2484fn owned_task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2485    task_jobs(home)?
2486        .into_iter()
2487        .filter_map(
2488            |job| match serde_json::from_value::<TaskWorker>(job.payload.clone()) {
2489                Ok(request) if !request.standalone => Some(Ok(job)),
2490                Ok(_) => None,
2491                Err(error) => Some(Err(error.into())),
2492            },
2493        )
2494        .collect()
2495}
2496
2497/// Whether an independent scheduler can be controlled without its web parent.
2498#[must_use]
2499pub fn managed(home: &Path) -> bool {
2500    match crate::worker::active(home) {
2501        Err(error) => {
2502            tracing::error!("cannot determine scheduler ownership: {error:#}");
2503            true
2504        }
2505        Ok(jobs) if jobs.iter().any(|j| j.kind == "scheduler") => true,
2506        Ok(_) => {
2507            read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2508                && crate::worker::try_lease(home, "scheduler").map_or(true, |lease| lease.is_none())
2509        }
2510    }
2511}
2512
2513/// Start a detached, singleton scheduler using this executable generation.
2514pub async fn spawn_detached(home: &Path, opts: &Opts) -> Result<crate::worker::Job> {
2515    anyhow::ensure!(
2516        crate::worker::control(home, "scheduler")?.is_none() || !managed(home),
2517        "the scheduler is stopping; wait for retirement before starting it again"
2518    );
2519    crate::worker::spawn(
2520        home,
2521        "scheduler",
2522        "scheduler",
2523        serde_json::to_value(opts.absolute()?)?,
2524    )
2525    .await
2526}
2527
2528fn park_request_path(home: &Path, job: &crate::worker::Job) -> PathBuf {
2529    home.join("worker-parks").join(format!("{}.json", job.id))
2530}
2531
2532fn request_task_park(
2533    home: &Path,
2534    job: &crate::worker::Job,
2535    cause: crate::run::ParkCause,
2536) -> Result<()> {
2537    let path = park_request_path(home, job);
2538    std::fs::create_dir_all(path.parent().context("worker park directory")?)?;
2539    std::fs::write(path, serde_json::to_vec(&cause)?)?;
2540    crate::worker::request(home, &job.key, crate::worker::Control::Park)
2541}
2542
2543/// Stop dispatch immediately; only an explicit park reaches existing workers.
2544pub fn request_control(home: &Path, control: crate::worker::Control) -> Result<()> {
2545    if control == crate::worker::Control::Park {
2546        for job in owned_task_jobs(home)? {
2547            request_task_park(home, &job, crate::run::ParkCause::Operator)?;
2548        }
2549    }
2550    crate::worker::request(home, "scheduler", control)
2551}
2552
2553/// Replace the scheduler, leaving all active task and conversation jobs alone.
2554pub async fn restart_detached(home: &Path) -> Result<()> {
2555    let active = crate::worker::active(home)?;
2556    let prior = active.into_iter().find(|job| job.kind == "scheduler");
2557    if prior.is_none() && !managed(home) {
2558        return Ok(());
2559    }
2560    let opts: Opts = match prior {
2561        Some(job) => serde_json::from_value(job.payload)?,
2562        None => serde_json::from_slice(&std::fs::read(home.join("scheduler-options.json"))?)?,
2563    };
2564    request_control(home, crate::worker::Control::Stop)?;
2565    loop {
2566        let reserved = crate::worker::active(home)?
2567            .iter()
2568            .any(|job| job.kind == "scheduler");
2569        if !reserved && crate::worker::try_lease(home, "scheduler")?.is_some() {
2570            break;
2571        }
2572        tokio::time::sleep(Duration::from_millis(100)).await;
2573    }
2574    spawn_detached(home, &opts).await?;
2575    Ok(())
2576}
2577
2578/// Hidden worker dispatch entry. The worker infrastructure owns its job lease.
2579pub async fn run_scheduler_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2580    let opts: Opts = serde_json::from_value(payload)?;
2581    let _ = home;
2582    serve_until(opts, Stop::new()).await
2583}
2584
2585/// Execute and settle one task with the queue claim owned by this process.
2586pub async fn run_task_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2587    let request: TaskWorker = serde_json::from_value(payload)?;
2588    let queue = Queue::at(request.queue);
2589    let key = format!("task:{}", request.task);
2590    let job = task_jobs(home)?
2591        .into_iter()
2592        .find(|job| job.key == key)
2593        .context("task worker reservation is missing")?;
2594    let park_path = park_request_path(home, &job);
2595    // The spawning CLI/scheduler still owns the claim until spawn acknowledges
2596    // our durable reservation. Never execute before that ownership hand-off.
2597    let _claim = loop {
2598        match queue.claim(&request.task) {
2599            Ok(claim) => break claim,
2600            // Only contention (the claim file exists) is worth waiting out; an
2601            // I/O failure must end this worker instead of pinning its lane.
2602            Err(e) if e.chain().any(|c| c.is::<std::io::Error>()) => {
2603                return Err(e.context("claim the task for its worker"));
2604            }
2605            Err(_) => {
2606                sweep_stale_claims(&queue, STALE_CLAIM);
2607                tokio::time::sleep(Duration::from_millis(50)).await;
2608            }
2609        }
2610    };
2611    let mut task = queue.get(&request.task)?;
2612    if !task.status.runnable()
2613        || (!request.standalone
2614            && request.lane
2615                != permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent))
2616    {
2617        return Ok(());
2618    }
2619    let stop = Stop::new();
2620    let watcher = {
2621        let home = home.to_path_buf();
2622        let stop = stop.clone();
2623        let park_path = park_path.clone();
2624        tokio::spawn(async move {
2625            loop {
2626                if crate::worker::control(&home, &key).ok().flatten().is_some() {
2627                    let cause = std::fs::read(&park_path)
2628                        .ok()
2629                        .and_then(|body| serde_json::from_slice(&body).ok())
2630                        .unwrap_or(crate::run::ParkCause::Operator);
2631                    stop.park(cause);
2632                    return;
2633                }
2634                tokio::time::sleep(Duration::from_millis(200)).await;
2635            }
2636        })
2637    };
2638    let quota = if request.standalone {
2639        run_claimed_until(&request.opts, &queue, &mut task, &stop).await
2640    } else {
2641        let status = Arc::new(Mutex::new(Status::new()));
2642        Box::pin(attempt(
2643            &request.opts,
2644            &queue,
2645            &status,
2646            &stop,
2647            crate::graph::Pause::new(),
2648            &mut task,
2649        ))
2650        .await
2651    };
2652    watcher.abort();
2653    let _ = std::fs::remove_file(park_path);
2654    persist_cooldown(home, &quota).await?;
2655    Ok(())
2656}
2657
2658/// Launch the standalone task worker with a claim-to-reservation handoff.
2659/// Returns only after the worker owns a durable execution reservation.
2660pub async fn spawn_claimed(
2661    home: &Path,
2662    opts: &Opts,
2663    queue: &Queue,
2664    task: &Task,
2665    claim: crate::queue::Claim,
2666) -> Result<crate::worker::Job> {
2667    let request = TaskWorker {
2668        opts: opts.absolute()?,
2669        queue: std::path::absolute(queue.root())?,
2670        task: task.id.clone(),
2671        lane: permit_kind(land_resume_state(task) == LandResume::Ready, task.urgent),
2672        standalone: true,
2673    };
2674    let job = crate::worker::spawn(
2675        home,
2676        "task",
2677        &format!("task:{}", task.id),
2678        serde_json::to_value(request)?,
2679    )
2680    .await?;
2681    drop(claim);
2682    Ok(job)
2683}
2684
2685/// Transfer a standalone caller's claim only after the detached worker is live,
2686/// then follow that worker to its final (non-automatically-retrying) outcome.
2687pub async fn run_detached_claimed(
2688    opts: &Opts,
2689    queue: &Queue,
2690    task: &mut Task,
2691    claim: crate::queue::Claim,
2692) -> Result<()> {
2693    let home = crate::run::home();
2694    let job = spawn_claimed(&home, opts, queue, task, claim).await?;
2695    loop {
2696        // Reconcile execution leases even without a scheduler. A dead worker
2697        // must become a reported failure, never an infinite persisted wait.
2698        crate::worker::active(&home)?;
2699        let current = crate::worker::get(&home, &job.id)?;
2700        if matches!(
2701            current.status,
2702            crate::worker::Status::Finished | crate::worker::Status::Failed
2703        ) {
2704            *task = queue.get(&task.id)?;
2705            anyhow::ensure!(
2706                current.status != crate::worker::Status::Failed,
2707                "task worker failed: {}",
2708                current.result.as_deref().unwrap_or("unknown failure")
2709            );
2710            return Ok(());
2711        }
2712        tokio::time::sleep(Duration::from_millis(200)).await;
2713    }
2714}
2715
2716async fn persist_cooldown(home: &Path, quota: &[QuotaLoss]) -> Result<()> {
2717    if let Some(until) = cooldown_until(quota, Timestamp::now()) {
2718        let _lease = loop {
2719            if let Some(lease) = crate::worker::try_lease(home, "task-quota-cooldown")? {
2720                break lease;
2721            }
2722            tokio::time::sleep(Duration::from_millis(10)).await;
2723        };
2724        if read_cooldown(home)?.is_none_or(|previous| previous < until) {
2725            let path = home.join("task-quota-cooldown.json");
2726            let temporary = path.with_extension("json.tmp");
2727            std::fs::write(&temporary, serde_json::to_vec(&until)?)?;
2728            std::fs::rename(temporary, path)?;
2729        }
2730    }
2731    Ok(())
2732}
2733
2734fn read_cooldown(home: &Path) -> Result<Option<Timestamp>> {
2735    match std::fs::read(home.join("task-quota-cooldown.json")) {
2736        Ok(body) => Ok(Some(serde_json::from_slice(&body)?)),
2737        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
2738        Err(error) => Err(error.into()),
2739    }
2740}
2741
2742/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
2743///
2744/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
2745/// sets, so there is one loop body rather than two that drift apart the first
2746/// time the retry policy changes on only one of them.
2747pub async fn serve(opts: Opts) -> Result<()> {
2748    tracing::info!(
2749        "automatic update and restart requires magi web; standalone serve does not restart"
2750    );
2751    serve_until(opts, Stop::new()).await
2752}
2753
2754/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
2755///
2756/// A stop retires dispatch promptly, including while a worker launch is being
2757/// acknowledged. Already reserved workers own their attempts independently and
2758/// finish with their started executable. Explicit park additionally forwards
2759/// durable park requests; neither scheduler retirement nor update does so.
2760///
2761/// While the queue is empty the stop is honoured within one wakeup rather than
2762/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
2763/// caller that taps stop does not sit through the remainder of a sleep.
2764pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
2765    let opts = opts.absolute()?;
2766    let home = crate::run::home();
2767    let _scheduler = crate::worker::try_lease(&home, "scheduler")?
2768        .context("another scheduler already owns this home")?;
2769    if let Some(reading) = read_status(&home)
2770        && legacy_scheduler_running(&reading, Timestamp::now(), std::process::id())
2771    {
2772        bail!("a legacy scheduler is still running; stop it before starting independent dispatch");
2773    }
2774    if !crate::worker::active(&home)?
2775        .iter()
2776        .any(|job| job.kind == "scheduler")
2777    {
2778        crate::worker::clear_control(&home, "scheduler")?;
2779    }
2780    std::fs::write(
2781        home.join("scheduler-options.json"),
2782        serde_json::to_vec(&opts)?,
2783    )?;
2784    let control = {
2785        let home = home.clone();
2786        let stop = stop.clone();
2787        tokio::spawn(async move {
2788            loop {
2789                match crate::worker::control(&home, "scheduler").ok().flatten() {
2790                    Some(crate::worker::Control::Park) => {
2791                        let _ = request_control(&home, crate::worker::Control::Park);
2792                        stop.park(crate::run::ParkCause::Operator);
2793                        break;
2794                    }
2795                    Some(crate::worker::Control::Stop) => {
2796                        stop.stop();
2797                        break;
2798                    }
2799                    None => {}
2800                }
2801                tokio::time::sleep(Duration::from_millis(100)).await;
2802            }
2803        })
2804    };
2805    let signal = {
2806        let stop = stop.clone();
2807        tokio::spawn(async move {
2808            if tokio::signal::ctrl_c().await.is_ok() {
2809                stop.stop();
2810                tracing::info!("scheduler shutdown requested; independent workers continue");
2811            }
2812        })
2813    };
2814
2815    let worktrees_root = opts
2816        .worktrees_root
2817        .clone()
2818        .unwrap_or_else(crate::run::default_worktree_root);
2819    let outcome = drive(
2820        &opts,
2821        &Queue::open(),
2822        &status_path(),
2823        &crate::run::home(),
2824        &worktrees_root,
2825        &stop,
2826    )
2827    .await;
2828
2829    signal.abort();
2830    control.abort();
2831    outcome
2832}
2833
2834/// The loop proper: setup, poll, teardown, with the queue and the status file
2835/// supplied rather than discovered.
2836///
2837/// All three of `home`, `worktrees_root` and the queue/status paths are
2838/// parameters rather than resolved here, for the same reason:
2839/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
2840/// so a unit test that pinned it would fight every other test in the binary,
2841/// and a loop that resolved its own worktree bay could only be exercised
2842/// against the operator's real `~/wt/<repo>` - publishing over a live
2843/// daemon's status file, claiming tasks out of a live backlog, and, since
2844/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
2845/// whatever the operator actually has on disk.
2846async fn drive(
2847    opts: &Opts,
2848    queue: &Queue,
2849    status_file: &Path,
2850    home: &Path,
2851    worktrees_root: &Path,
2852    stop: &Stop,
2853) -> Result<()> {
2854    // The status file is a *snapshot*, not a stream of events: a reader only
2855    // ever wants the latest values, and every tick rewrites the whole file
2856    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
2857    // while an mpsc channel would force the loop to re-send unchanged fields on
2858    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
2859    // for no gain. The lock is only ever held across a field assignment, never
2860    // across an await.
2861    let recovery_cfg = prepare(&opts.repo, opts).ok();
2862    let daemon_cfg = recovery_cfg
2863        .as_ref()
2864        .map(|c| c.daemon.clone())
2865        .unwrap_or_default();
2866    let reconciled = crate::driver::reconcile(home);
2867    if !reconciled.is_empty() {
2868        tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
2869    }
2870    let mut initial_status = Status::new();
2871    let owned = owned_task_jobs(home)?;
2872    initial_status.current = current_work(home, Timestamp::now())
2873        .into_iter()
2874        .filter(|current| {
2875            owned
2876                .iter()
2877                .any(|job| job.key.strip_prefix("task:") == Some(current.task.as_str()))
2878        })
2879        .collect();
2880    initial_status.idle = initial_status.current.is_empty();
2881    initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
2882        recovery_cfg.as_ref(),
2883        daemon_cfg.max_deputies,
2884    ));
2885    let status = Arc::new(Mutex::new(initial_status));
2886    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
2887    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
2888
2889    // Read once at startup, not per task: how many runs this loop drives at
2890    // once is a property of the machine running it, not of whichever
2891    // repository a given task happens to name - see
2892    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
2893    // fact in the same sense the agent roster is.
2894    let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
2895
2896    tracing::info!(
2897        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
2898        queue.root().display(),
2899        opts.poll.as_secs(),
2900        opts.max_attempts,
2901        concurrency,
2902        if daemon_cfg.pause_for_interrupts {
2903            ", interrupts enabled"
2904        } else {
2905            ""
2906        }
2907    );
2908
2909    let outcome = tokio::select! {
2910        outcome = poll(opts, queue, &status, home, worktrees_root, stop, DispatchLimits {
2911            max_concurrent: concurrency,
2912            pause_for_interrupts: daemon_cfg.pause_for_interrupts,
2913            recovery_cfg,
2914        }) => outcome,
2915        () = async {
2916            while !stop.stopped() {
2917                tokio::time::sleep(Duration::from_millis(25)).await;
2918            }
2919        } => {
2920            if stop.parking() {
2921                request_control(home, crate::worker::Control::Park)?;
2922            }
2923            Ok(())
2924        }
2925    };
2926
2927    stop.busy.store(0, Ordering::SeqCst);
2928    beat.abort();
2929    clear_status_at(status_file);
2930    outcome
2931}
2932
2933/// The checkouts the release watcher covers and `[daemon] release_stall_minutes`,
2934/// re-read each lap. An unreadable config yields `0` minutes: the watcher idles.
2935pub(crate) fn release_watch_settings_from_config(
2936    home: &Path,
2937    repo: &Path,
2938    cfg: &Config,
2939) -> (Vec<PathBuf>, u64) {
2940    let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
2941        .into_iter()
2942        .map(|r| r.path)
2943        .collect();
2944    // Repositories the daemon has worked in, wherever they live: a task may
2945    // name one outside `[repos] roots`, and its release PR must be watched too.
2946    let mut known: Vec<PathBuf> = Queue::at(home.join("queue"))
2947        .list()
2948        .into_iter()
2949        .map(|t| t.repo)
2950        .collect();
2951    let runs = home.join("runs");
2952    for id in crate::run::list_ids_in(&runs) {
2953        let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
2954            .ok()
2955            .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
2956            .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
2957        known.extend(repo);
2958    }
2959    for k in known {
2960        let k = k.canonicalize().unwrap_or(k);
2961        if k.join(".git").exists() && !paths.contains(&k) {
2962            paths.push(k);
2963        }
2964    }
2965    let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
2966    if !paths.contains(&own) {
2967        paths.push(own);
2968    }
2969    (paths, cfg.daemon.release_stall_minutes)
2970}
2971
2972/// Per-repo bound on one `git fetch`, so a dead remote cannot stall the pass.
2973const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
2974
2975/// Refresh the status file on a fixed tick.
2976///
2977/// Separate from the loop because a run takes tens of minutes: a status file
2978/// written only between tasks would look stale for the whole of every run, and
2979/// a reader would report the daemon dead exactly while it was busiest.
2980async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
2981    loop {
2982        tokio::time::sleep(HEARTBEAT).await;
2983        let snapshot = {
2984            let mut guard = lock(&status);
2985            guard.updated_at = Timestamp::now();
2986            guard.clone()
2987        };
2988        if let Err(e) = write_status_to(&path, &snapshot) {
2989            // A failed heartbeat must not take the daemon down: the loop is the
2990            // product, the status file is only the window onto it.
2991            tracing::warn!("could not refresh the daemon status file: {e:#}");
2992        }
2993    }
2994}
2995
2996/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
2997/// if so, whether that wait is over.
2998#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2999enum LandResume {
3000    /// The task's last run is not parked on a land approval; schedule it
3001    /// like any other candidate.
3002    NotLanding,
3003    /// Parked in `land`, waiting on a question nobody has answered yet.
3004    /// Left alone: attempting it now would only re-observe the same pull
3005    /// request and park again, spending a `gh` call on a decision that has
3006    /// not changed since the last time this was checked.
3007    StillWaiting,
3008    /// Parked in `land`, and the question is settled - answered or
3009    /// abandoned. Resuming this is the one kind of candidate that must not
3010    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
3011    Ready,
3012}
3013
3014/// Classify a runnable candidate by whether it is parked on a land-merge
3015/// approval. Read-only - no claim taken, nothing written - so it is cheap
3016/// enough to call on every candidate, every poll.
3017fn land_resume_state(task: &Task) -> LandResume {
3018    let Some(run_id) = task.runs.last() else {
3019        return LandResume::NotLanding;
3020    };
3021    let Ok(state) = RunState::load(run_id) else {
3022        return LandResume::NotLanding;
3023    };
3024    if !state.parked {
3025        return LandResume::NotLanding;
3026    }
3027    if state.status == RunStatus::Landing
3028        && state.land_approval.as_ref().is_some_and(|binding| {
3029            ask::Questions::open()
3030                .get(&binding.question)
3031                .is_ok_and(|q| {
3032                    q.run == state.id
3033                        && q.resolution()
3034                            .as_deref()
3035                            .is_some_and(crate::merge_decision::stops)
3036                })
3037        })
3038    {
3039        return LandResume::Ready;
3040    }
3041    if !implementers_match(task, &state) {
3042        return LandResume::NotLanding;
3043    }
3044    // Parked in `land` on the merge approval, or at `merge` on the owner's
3045    // word about a title/body the posting gate withheld. Told apart by the
3046    // run's own record, not by a status both can share.
3047    let node = if state.status == RunStatus::Landing {
3048        land::APPROVAL_NODE
3049    } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
3050        crate::github_text::ASK_NODE
3051    } else {
3052        return LandResume::NotLanding;
3053    };
3054    let store = ask::Questions::open();
3055    let waiting = store
3056        .list()
3057        .into_iter()
3058        .filter(|q| &q.run == run_id && q.node == node)
3059        .max_by(|a, b| a.id.cmp(&b.id));
3060    let Some(mut q) = waiting else {
3061        return LandResume::Ready;
3062    };
3063    if !q.status.open() {
3064        // Repair spends agent resources and must obey concurrency and quota
3065        // waits; only a merge/hold decision may use the decision-only lane.
3066        if q.resolution().as_deref() == Some(land::REPAIR) {
3067            return if state.liveness(false) == Liveness::Live {
3068                LandResume::StillWaiting
3069            } else {
3070                LandResume::NotLanding
3071            };
3072        }
3073        return LandResume::Ready;
3074    }
3075    // `ask::ask_and_wait`'s own deadline is what used to retire a question
3076    // nobody ever answered; land's approval bypasses that wait entirely (see
3077    // `land::approval_gate`), so the same deadline has to be enforced here
3078    // instead, or `graph.answer_timeout` silently stops meaning anything for
3079    // a land approval and a run can sit `StillWaiting` forever with nobody
3080    // told to look at it.
3081    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
3082    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
3083    if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
3084        q.abandon(format!(
3085            "no answer within {}s of asking",
3086            timeout.as_secs().max(1)
3087        ));
3088        // If this can't be persisted, do not treat the wait as settled on a
3089        // guess: fall through and try again next poll.
3090        if store.put(&mut q).is_ok() {
3091            return LandResume::Ready;
3092        }
3093    }
3094    LandResume::StillWaiting
3095}
3096
3097/// How often the loop rechecks for new work while something it already
3098/// started is still running, rather than sleeping out the whole
3099/// [`Opts::poll`] interval.
3100///
3101/// Short on purpose: this is what lets a land-merge approval that comes back
3102/// while another task is mid-competition be noticed and resumed within a
3103/// fraction of a second, not within the next multi-second poll.
3104const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
3105
3106/// How often [`poll`] rechecks the shared build cache against its cap at a
3107/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
3108/// waiting for the queue to run dry.
3109///
3110/// A queue that never empties means the `janitor` call at the bottom of this
3111/// loop's fully-idle branch can go unreached for as long as the backlog
3112/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
3113/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
3114/// 81.8 GiB an idle-only check let it reach before this existed, and it is
3115/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
3116/// backlog of short tasks does not pay for that walk on every poll.
3117const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
3118
3119/// State of [`poll`]'s own interrupt-scheduling sequence - see
3120/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
3121/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
3122/// both kept free of `Task`'s non-identity fields on purpose: every decision
3123/// here turns only on task ids and which ones are in flight, so the "never
3124/// more than one run at once" and "exactly one resume" invariants can be
3125/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
3126/// queue - which is exactly the coverage this feature's first two attempts
3127/// were missing.
3128///
3129/// Persisted after every transition, so scheduler replacement preserves the
3130/// interrupt's exclusive turn and the interrupted task's priority resume.
3131#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3132enum Interrupt {
3133    /// No interrupt sequence in progress. Ordinary dispatch applies.
3134    Idle,
3135    /// `interrupt_task` is runnable and exactly one other run is in flight;
3136    /// `parked` names that one task's id. Dispatch is withheld from
3137    /// everyone, including `interrupt_task` itself, until it has left
3138    /// flight - only then is `interrupt_task` let through.
3139    ///
3140    /// `parked` is a `Vec` rather than a bare id for symmetry with
3141    /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
3142    /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
3143    /// when exactly one run is in flight, so it is guaranteed to hold
3144    /// exactly one entry in practice - see that branch's own doc for why
3145    /// more than one is deliberately never attempted.
3146    Parking {
3147        parked: Vec<String>,
3148        interrupt_task: String,
3149    },
3150    /// `interrupt_task` is dispatched and in flight alone. Dispatch is
3151    /// withheld from everyone until it leaves flight - merged, failed, held,
3152    /// it makes no difference - at which point the sequence moves to
3153    /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
3154    /// going straight to `Idle` would hand `parked` back to ordinary
3155    /// priority-order dispatch, where a higher-priority task filed in the
3156    /// meantime could start ahead of it.
3157    Running {
3158        parked: Vec<String>,
3159        interrupt_task: String,
3160    },
3161    /// `interrupt_task` left flight; `parked` still names the one run this
3162    /// sequence owes a resume. Dispatch is withheld from everyone except
3163    /// that task - see [`interrupt_gate`] - so the resume this feature
3164    /// promises is never raced by, or run alongside, an unrelated candidate.
3165    /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
3166    /// own doc on abandonment - the moment it is no longer runnable at all.
3167    Resuming { parked: Vec<String> },
3168}
3169
3170/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
3171/// and `runnable` are read-only snapshots of this tick's reality, and the
3172/// only side effect the caller still owes the world is asking whichever
3173/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
3174/// site.
3175///
3176/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
3177/// accepted rather than a narrower type because that is what [`poll`] already
3178/// has on hand from [`runnable`], and building a second, smaller list on
3179/// every tick just to satisfy this signature would cost more than it proves.
3180///
3181/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
3182/// back to a task they are waiting on no longer being [`runnable`] - held,
3183/// blocked, deleted, or finished by some other means entirely, all of which
3184/// an operator can do to a task sitting in the queue with no claim on it at
3185/// all, at any moment, interrupt sequence or not. Without this check the
3186/// sequence would wait forever for a dispatch that can never come, and
3187/// `interrupt_gate` would withhold every other task in the queue right along
3188/// with it - a single `magi task hold` on the wrong id turning into a
3189/// daemon that never dispatches anything again.
3190fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
3191    match state {
3192        Interrupt::Idle => {
3193            // Not just "something to interrupt": exactly one thing. More
3194            // than one run in flight only happens above the default
3195            // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
3196            // one resume, never run alongside anything else" only because
3197            // it is only ever seeded with exactly one id - see
3198            // `Interrupt::Resuming`'s own doc on why releasing more than one
3199            // parked id back to ordinary dispatch cannot be made safe
3200            // against that same setting's own extra concurrency slots.
3201            // Waiting here for the herd to settle to one is the
3202            // simplification this feature's own constraints ask for rather
3203            // than a second concurrency model to reconcile with the first.
3204            if in_flight.len() != 1 {
3205                return Interrupt::Idle;
3206            }
3207            match runnable.iter().find(|t| t.interrupt) {
3208                Some(t) => Interrupt::Parking {
3209                    parked: in_flight.to_vec(),
3210                    interrupt_task: t.id.clone(),
3211                },
3212                None => Interrupt::Idle,
3213            }
3214        }
3215        Interrupt::Parking {
3216            parked,
3217            interrupt_task,
3218        } => {
3219            if in_flight.iter().any(|id| parked.contains(id)) {
3220                // Still waiting for what was in flight to actually stop.
3221                Interrupt::Parking {
3222                    parked,
3223                    interrupt_task,
3224                }
3225            } else if in_flight.contains(&interrupt_task) {
3226                Interrupt::Running {
3227                    parked,
3228                    interrupt_task,
3229                }
3230            } else if runnable.iter().any(|t| t.id == interrupt_task) {
3231                // The parked run(s) are gone, but the interrupt task has not
3232                // been dispatched yet on this tick - `interrupt_gate` is
3233                // what lets it through next.
3234                Interrupt::Parking {
3235                    parked,
3236                    interrupt_task,
3237                }
3238            } else {
3239                // The interrupt task itself is no longer runnable - see this
3240                // function's own doc on abandonment. The parked run(s) still
3241                // get their guaranteed resume; there is simply no interrupt
3242                // to run ahead of them any longer.
3243                Interrupt::Resuming { parked }
3244            }
3245        }
3246        Interrupt::Running {
3247            parked,
3248            interrupt_task,
3249        } => {
3250            if in_flight.contains(&interrupt_task) {
3251                Interrupt::Running {
3252                    parked,
3253                    interrupt_task,
3254                }
3255            } else {
3256                // The interrupt task's own run reached a terminal status,
3257                // whichever one - this is the *only* trigger that moves the
3258                // sequence on, driven straight off the same in-flight
3259                // bookkeeping `poll` already reaps every tick, not a second,
3260                // independent poll of anything.
3261                Interrupt::Resuming { parked }
3262            }
3263        }
3264        Interrupt::Resuming { parked } => {
3265            if in_flight.iter().any(|id| parked.contains(id)) {
3266                // One of the parked runs has been dispatched - the resume
3267                // this sequence owed is fulfilled. Whatever else is left in
3268                // `parked` (ordinarily nothing, at the default concurrency
3269                // of one) rejoins ordinary priority-order dispatch, same as
3270                // any other runnable task.
3271                Interrupt::Idle
3272            } else if runnable.iter().any(|t| parked.contains(&t.id)) {
3273                Interrupt::Resuming { parked }
3274            } else {
3275                // Abandonment (see this function's own doc): nothing left in
3276                // `parked` is even runnable any longer.
3277                Interrupt::Idle
3278            }
3279        }
3280    }
3281}
3282
3283/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
3284/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
3285/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
3286/// indistinguishable from any other runnable task - exactly the "off does
3287/// nothing" this feature promises.
3288fn advance_interrupt_tick(
3289    enabled: bool,
3290    state: Interrupt,
3291    in_flight: &[String],
3292    runnable: &[Task],
3293) -> Interrupt {
3294    if !enabled {
3295        return Interrupt::Idle;
3296    }
3297    advance_interrupt(state, in_flight, runnable)
3298}
3299
3300/// Which of this tick's runnable candidates the interrupt sequence actually
3301/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
3302/// each half is assertable on its own: this is the half that keeps a
3303/// competition and an interrupt from ever running at the same moment.
3304fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
3305    match state {
3306        Interrupt::Idle => candidates,
3307        Interrupt::Parking {
3308            parked,
3309            interrupt_task,
3310        } => {
3311            if in_flight.iter().any(|id| parked.contains(id)) {
3312                Vec::new()
3313            } else {
3314                candidates
3315                    .into_iter()
3316                    .filter(|t| &t.id == interrupt_task)
3317                    .collect()
3318            }
3319        }
3320        Interrupt::Running { .. } => Vec::new(),
3321        // At most one: even if `parked` names more than one id (more than
3322        // one run was in flight when the sequence began, only possible
3323        // above the default `max_concurrent_runs = 1`), only the first match
3324        // is offered. Capping this to a single candidate - not merely to
3325        // `parked`'s own ids - is what makes "exactly one resume, never two
3326        // dispatched together" true regardless of how many ordinary slots
3327        // happen to be free this tick.
3328        Interrupt::Resuming { parked } => candidates
3329            .into_iter()
3330            .find(|t| parked.contains(&t.id))
3331            .into_iter()
3332            .collect(),
3333    }
3334}
3335
3336/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
3337/// bundled into one parameter so `poll`'s own signature stays readable -
3338/// see [`drive`]'s call site for where these are actually read.
3339struct DispatchLimits {
3340    /// How many *ordinary* candidates run at once. See
3341    /// [`crate::config::Daemon::max_concurrent_runs`].
3342    max_concurrent: usize,
3343    /// See [`crate::config::Daemon::pause_for_interrupts`].
3344    pause_for_interrupts: bool,
3345    recovery_cfg: Option<Config>,
3346}
3347
3348/// Which semaphore, if any, dispatching a candidate should draw its permit
3349/// from.
3350///
3351/// Pure and separate from [`poll`]'s loop body for the same reason
3352/// [`advance_interrupt`] is: the choice between "skip the ordinary pool
3353/// entirely", "spend the one urgent slot" and "spend an ordinary slot" is
3354/// exactly the policy this feature adds, and a policy only exercisable by
3355/// running the whole loop is a policy nobody checks.
3356#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3357enum PermitKind {
3358    /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
3359    /// Checked first - a task can be both a land resume and marked
3360    /// [`Task::urgent`], and the resume's own "must not queue behind
3361    /// anything" guarantee takes precedence.
3362    None,
3363    /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
3364    /// (never in addition to trying) the ordinary pool. This is what lets
3365    /// an urgent task dispatch while every ordinary slot is already checked
3366    /// out, and what stops a second urgent task from opening a third run: it
3367    /// waits on this same one-slot semaphore rather than falling through to
3368    /// the ordinary one.
3369    Urgent,
3370    /// The ordinary `max_concurrent_runs` pool - unaffected by either of the
3371    /// above.
3372    #[default]
3373    Ordinary,
3374}
3375
3376/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
3377/// own boolean, already computed by the caller from [`land_resume_state`].
3378fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
3379    if priority {
3380        PermitKind::None
3381    } else if urgent {
3382        PermitKind::Urgent
3383    } else {
3384        PermitKind::Ordinary
3385    }
3386}
3387
3388fn available_slots(requests: &[TaskWorker], limit: usize) -> (usize, usize) {
3389    let (ordinary, urgent) = requests.iter().filter(|request| !request.standalone).fold(
3390        (0usize, 0usize),
3391        |(ordinary, urgent), request| match request.lane {
3392            PermitKind::Ordinary => (ordinary + 1, urgent),
3393            PermitKind::Urgent => (ordinary, urgent + 1),
3394            PermitKind::None => (ordinary, urgent),
3395        },
3396    );
3397    (
3398        limit.saturating_sub(ordinary),
3399        1usize.saturating_sub(urgent),
3400    )
3401}
3402
3403struct DispatchClaim {
3404    task: Task,
3405    claim: crate::queue::Claim,
3406    permit: Option<tokio::sync::OwnedSemaphorePermit>,
3407}
3408
3409/// Claim and re-read before choosing a lane: a queue listing may predate an
3410/// urgent toggle. All unsuccessful paths release the claim without an attempt.
3411fn claim_dispatch(
3412    queue: &Queue,
3413    candidate: &Task,
3414    cooling_down: bool,
3415    ordinary: &Arc<tokio::sync::Semaphore>,
3416    urgent: &Arc<tokio::sync::Semaphore>,
3417) -> Option<DispatchClaim> {
3418    let Ok(claim) = queue.claim(&candidate.id) else {
3419        tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
3420        return None;
3421    };
3422    let task = match queue.get(&candidate.id) {
3423        Ok(t) if t.status.runnable() => t,
3424        Ok(_) => return None,
3425        Err(e) => {
3426            tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
3427            return None;
3428        }
3429    };
3430    let resume = land_resume_state(&task);
3431    if resume == LandResume::StillWaiting {
3432        return None;
3433    }
3434    let priority = resume == LandResume::Ready;
3435    if !priority && cooling_down {
3436        return None;
3437    }
3438    // Never borrow an ordinary slot when the single urgent slot is busy.
3439    // Keep scanning other candidates when either pool has no free slot.
3440    let permit = match permit_kind(priority, task.urgent) {
3441        PermitKind::None => None,
3442        PermitKind::Urgent => Some(Arc::clone(urgent).try_acquire_owned().ok()?),
3443        PermitKind::Ordinary => Some(Arc::clone(ordinary).try_acquire_owned().ok()?),
3444    };
3445    // Persist the dispatch order under the claim, before config discovery or
3446    // coordination waits can reorder concurrent starts.
3447    let stamp = Timestamp::now();
3448    let mut task = task;
3449    task.dispatched_at = Some(stamp);
3450    if let Err(e) = queue.modify(&task.id, |t| {
3451        t.dispatched_at = Some(stamp);
3452        true
3453    }) {
3454        tracing::warn!("could not record dispatch order of {}: {e:#}", task.short());
3455    }
3456    Some(DispatchClaim {
3457        task,
3458        claim,
3459        permit,
3460    })
3461}
3462
3463/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
3464/// teardown and cannot skip the teardown on an early return.
3465///
3466/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
3467/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
3468/// land approval that has since been answered is dispatched outside that
3469/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
3470/// the whole point of parking there is that it must not queue behind
3471/// whatever else the loop happens to be running, even at the default of one.
3472/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
3473/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
3474/// these exemptions is still subject to the interrupt gate below, urgent
3475/// included: a land-resume or urgent candidate is exactly as much "something
3476/// else running" as an ordinary one from the interrupt sequence's point of
3477/// view, and letting either slip through while a run is being parked, or
3478/// while the interrupt task itself has the floor, is precisely the second
3479/// run 75dd's own "at most one run, ever, at once" guarantee must never
3480/// allow - see [`Interrupt`]'s own doc.
3481#[derive(Serialize, Deserialize)]
3482struct ServiceWorker {
3483    opts: Opts,
3484    queue: PathBuf,
3485    worktrees_root: PathBuf,
3486    operation: String,
3487}
3488
3489fn load_conductor(home: &Path) -> Result<Conductor> {
3490    match std::fs::read(home.join("conductor-state.json")) {
3491        Ok(body) => serde_json::from_slice(&body).context("read conductor state"),
3492        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Conductor::new()),
3493        Err(error) => Err(error.into()),
3494    }
3495}
3496
3497fn conductor_work(queue: &Queue, home: &Path) -> (Vec<Task>, Vec<Task>, Vec<Task>) {
3498    let live: std::collections::BTreeSet<_> = current_work(home, Timestamp::now())
3499        .into_iter()
3500        .map(|c| c.task)
3501        .collect();
3502    let stalled = stalled_tasks(queue, home, Timestamp::now());
3503    let stalled_ids: std::collections::BTreeSet<_> = stalled.iter().map(|t| t.id.clone()).collect();
3504    let finished = finished_tasks(queue)
3505        .into_iter()
3506        .filter(|t| !live.contains(&t.id) && !stalled_ids.contains(&t.id))
3507        .filter(|t| !awaiting_resume_with(t, |id| RunState::load_under(id, home)))
3508        .collect();
3509    let queued = queued_tasks(queue)
3510        .into_iter()
3511        .filter(|t| !live.contains(&t.id))
3512        .collect();
3513    (queued, stalled, finished)
3514}
3515
3516async fn start_service(
3517    home: &Path,
3518    opts: &Opts,
3519    queue: &Queue,
3520    worktrees_root: &Path,
3521    operation: &str,
3522    cfg: Option<&Config>,
3523    busy: bool,
3524) -> Result<()> {
3525    // Fetch policy is live configuration, unlike question recovery capacity.
3526    // Reload before both cadence and eligibility, including disabled -> enabled.
3527    let fetch_cfg = if operation == "fetch" {
3528        match prepare(&opts.repo, opts) {
3529            Ok(cfg) => Some(cfg),
3530            Err(error) => {
3531                tracing::warn!("could not reload periodic fetch configuration: {error:#}");
3532                return Ok(());
3533            }
3534        }
3535    } else {
3536        None
3537    };
3538    let cfg = fetch_cfg.as_ref().or(cfg);
3539    let ticks = home.join("service-ticks");
3540    std::fs::create_dir_all(&ticks)?;
3541    let receipt = ticks.join(format!("daemon-{operation}"));
3542    let last = std::fs::read(&receipt)
3543        .ok()
3544        .and_then(|body| serde_json::from_slice::<Timestamp>(&body).ok());
3545    let interval = match operation {
3546        "disk-pressure" => 30,
3547        "cache" => CACHE_CHECK_INTERVAL_SECS,
3548        "fetch" => cfg.map_or(60, |cfg| cfg.repos.fetch_interval.max(1)),
3549        _ => opts.poll.as_secs().max(1),
3550    };
3551    let now = Timestamp::now();
3552    if !cache_check_due(last, now, interval) {
3553        return Ok(());
3554    }
3555    let key = format!("service:daemon-{operation}");
3556    if crate::worker::active(home)?
3557        .iter()
3558        .any(|job| job.key == key)
3559    {
3560        return Ok(());
3561    }
3562    let eligible = match operation {
3563        "conductor" => {
3564            let (queued, stalled, finished) = conductor_work(queue, home);
3565            !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3566                && load_conductor(home)?.worth_a_look(queue, &stalled, &finished)
3567        }
3568        "maintenance" => Questions::at(home.join("questions"))
3569            .list()
3570            .iter()
3571            .any(|q| {
3572                q.chosen_action().is_some_and(|action| action.maintenance())
3573                    && !home
3574                        .join("choice-actions")
3575                        .join(format!("{}.json", q.id))
3576                        .exists()
3577            }),
3578        "housekeeping" => !busy && runnable(queue).is_empty(),
3579        "cache" => {
3580            !busy
3581                && !runnable(queue).is_empty()
3582                && cfg.is_some_and(|cfg| cfg.disk.cache_limit_bytes > 0)
3583        }
3584        "disk-pressure" => busy,
3585        "fetch" => {
3586            cfg.is_some_and(|cfg| cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty())
3587        }
3588        _ => false,
3589    };
3590    if !eligible {
3591        return Ok(());
3592    }
3593    let request = ServiceWorker {
3594        opts: opts.absolute()?,
3595        queue: std::path::absolute(queue.root())?,
3596        worktrees_root: std::path::absolute(worktrees_root)?,
3597        operation: operation.to_owned(),
3598    };
3599    if let Err(error) =
3600        crate::worker::spawn(home, "daemon-service", &key, serde_json::to_value(request)?).await
3601    {
3602        tracing::warn!(operation, "could not launch daemon service: {error:#}");
3603    }
3604    std::fs::write(receipt, serde_json::to_vec(&now)?)?;
3605    Ok(())
3606}
3607
3608/// Finite maintenance jobs survive scheduler replacement without duplicating
3609/// agent calls or cancelling an operation between its effect and receipt.
3610pub async fn run_service_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
3611    let request: ServiceWorker = serde_json::from_value(payload)?;
3612    let opts = &request.opts;
3613    let queue = Queue::at(request.queue);
3614    let questions = Questions::at(home.join("questions"));
3615    match request.operation.as_str() {
3616        "maintenance" => apply_maintenance_choices(&queue, &questions, home).await,
3617        "conductor" => {
3618            let path = home.join("conductor-state.json");
3619            let mut conductor = load_conductor(home)?;
3620            let (queued, stalled, finished) = conductor_work(&queue, home);
3621            if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3622                && conductor.worth_a_look(&queue, &stalled, &finished)
3623            {
3624                let cfg = prepare(&opts.repo, opts)?;
3625                conductor
3626                    .maybe_run(
3627                        &cfg,
3628                        &opts.repo,
3629                        &queue,
3630                        &questions,
3631                        home,
3632                        &queued,
3633                        &stalled,
3634                        &finished,
3635                        opts.max_attempts,
3636                    )
3637                    .await;
3638                let temporary = path.with_extension("json.tmp");
3639                std::fs::write(&temporary, serde_json::to_vec(&conductor)?)?;
3640                std::fs::rename(temporary, path)?;
3641            }
3642        }
3643        "fetch" => {
3644            let cfg = prepare(&opts.repo, opts)?;
3645            if cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty() {
3646                let outcome = clean::fetch_origins(&cfg.repos.roots, FETCH_TIMEOUT, || false).await;
3647                tracing::debug!("fetch origins: {outcome:?}");
3648            }
3649        }
3650        "cache" => {
3651            if task_jobs(home)?.is_empty() {
3652                let mut checked = None;
3653                maybe_prune_cache_between_runs(
3654                    &opts.repo,
3655                    opts,
3656                    home,
3657                    &Stop::new(),
3658                    &mut checked,
3659                    Timestamp::now(),
3660                )
3661                .await;
3662            }
3663        }
3664        "disk-pressure" => {
3665            if let Ok(cfg) = prepare(&opts.repo, opts) {
3666                crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
3667                if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
3668                    tracing::warn!("disk pressure cache cleanup failed: {e:#}");
3669                }
3670                for current in current_work(home, Timestamp::now()) {
3671                    if let Ok(state) = RunState::load_under(&current.run, home)
3672                        && let Some(reason) = disk_gate(&state.repo, &state.config)
3673                    {
3674                        for job in owned_task_jobs(home)?.into_iter().filter(|job| {
3675                            job.key.strip_prefix("task:") == Some(current.task.as_str())
3676                        }) {
3677                            request_task_park(
3678                                home,
3679                                &job,
3680                                crate::run::ParkCause::Interrupt {
3681                                    reason: reason.clone(),
3682                                },
3683                            )?;
3684                        }
3685                        notices::raise_in(
3686                            home,
3687                            Notice::warn(
3688                                "disk:pressure",
3689                                "Disk pressure persists after cleanup; active workers were asked to checkpoint and park. New starts and resumes wait for free space.",
3690                            ),
3691                        );
3692                    }
3693                }
3694            }
3695        }
3696        "housekeeping" => {
3697            if task_jobs(home)?.is_empty() {
3698                if let Ok(cfg) = prepare(&opts.repo, opts) {
3699                    crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
3700                }
3701                janitor(&opts.repo, opts, home, &request.worktrees_root).await;
3702                resweep_superseded_attempts(&queue, home);
3703                triage_held(&queue, home, opts).await;
3704            }
3705        }
3706        operation => bail!("unknown daemon service {operation}"),
3707    }
3708    Ok(())
3709}
3710
3711/// Only a different request under the same key is a dispatch handoff race.
3712/// Our own unacknowledged reservation is a startup failure, not competing work:
3713/// stop dispatch without fencing it, so an already detached child may still run.
3714fn task_worker_spawn_error(home: &Path, request: &TaskWorker, error: anyhow::Error) -> Result<()> {
3715    let key = format!("task:{}", request.task);
3716    let payload = serde_json::to_value(request)?;
3717    if crate::worker::active(home)?
3718        .iter()
3719        .any(|job| job.key == key && job.kind == "task" && job.payload != payload)
3720    {
3721        tracing::warn!(
3722            "task {} acquired a competing worker reservation: {error:#}",
3723            crate::run::short_of(&request.task)
3724        );
3725        return Ok(());
3726    }
3727    tracing::error!("task worker startup stopped dispatch: {error:#}");
3728    notices::raise_in(
3729        home,
3730        Notice::error(
3731            "loop:worker-startup",
3732            // Startup diagnostics may contain private child-process details;
3733            // keep them in the local error/log rather than the chat or notifier.
3734            format!("Task {} worker could not be started or acknowledged. Scheduler dispatch stopped; already reserved workers may still complete. Inspect the local execution log and reservation worker.log for startup details.", request.task),
3735        ).link(Link::Task { id: request.task.clone() }),
3736    );
3737    Err(error).with_context(|| {
3738        format!(
3739            "cannot start task {} worker; dispatcher stopped; any unacknowledged reservation remains occupied",
3740            crate::run::short_of(&request.task)
3741        )
3742    })
3743}
3744
3745async fn poll(
3746    opts: &Opts,
3747    queue: &Queue,
3748    status: &Arc<Mutex<Status>>,
3749    home: &Path,
3750    worktrees_root: &Path,
3751    stop: &Stop,
3752    limits: DispatchLimits,
3753) -> Result<()> {
3754    let mut attempted = Vec::new();
3755    let mut settling_once_services = false;
3756    let interrupt_path = home.join("scheduler-interrupt.json");
3757    let mut interrupt = match std::fs::read(&interrupt_path) {
3758        Ok(body) => serde_json::from_slice(&body).context("read scheduler interrupt state")?,
3759        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Interrupt::Idle,
3760        Err(error) => return Err(error.into()),
3761    };
3762    let mut previous = std::collections::BTreeSet::<String>::new();
3763    while !stop.stopped() {
3764        let jobs: Vec<_> = crate::worker::active(home)?
3765            .into_iter()
3766            .filter(|job| job.kind == "task")
3767            .collect();
3768        let requests: Vec<_> = jobs
3769            .iter()
3770            .map(|job| {
3771                serde_json::from_value::<TaskWorker>(job.payload.clone())
3772                    .with_context(|| format!("read live task worker {}", job.id))
3773            })
3774            .collect::<Result<_>>()?;
3775        let live: std::collections::BTreeSet<_> = requests.iter().map(|r| r.task.clone()).collect();
3776        let owned: std::collections::BTreeSet<_> = requests
3777            .iter()
3778            .filter(|r| !r.standalone)
3779            .map(|r| r.task.clone())
3780            .collect();
3781        let current: Vec<_> = requests
3782            .iter()
3783            .zip(&jobs)
3784            .filter(|(request, _)| !request.standalone)
3785            .map(|(request, job)| Current {
3786                worker: Some(job.id.clone()),
3787                task: request.task.clone(),
3788                run: queue
3789                    .get(&request.task)
3790                    .ok()
3791                    .and_then(|task| task.runs.last().cloned())
3792                    .unwrap_or_default(),
3793            })
3794            .collect();
3795        {
3796            let mut snapshot = lock(status);
3797            snapshot.polls += 1;
3798            snapshot.completed += previous.difference(&owned).count();
3799            snapshot.current = current;
3800            snapshot.idle = owned.is_empty();
3801        }
3802        previous = owned.clone();
3803        stop.busy.store(owned.len(), Ordering::SeqCst);
3804
3805        // Slots are reconstructed from durable reservations and OS-held worker
3806        // leases, not this scheduler's lifetime or mutable task urgency.
3807        let (ordinary, urgent) = available_slots(&requests, limits.max_concurrent);
3808        let sem = Arc::new(tokio::sync::Semaphore::new(ordinary));
3809        let urgent_sem = Arc::new(tokio::sync::Semaphore::new(urgent));
3810        let mut permits = Vec::new();
3811        sweep_stale_claims(queue, STALE_CLAIM);
3812        reclaim_orphaned_running(queue, opts.max_attempts, &live);
3813        reclaim_abandoned_runs(home, Timestamp::now());
3814        let questions = Questions::at(home.join("questions"));
3815
3816        // Deterministic: no model, run before the conductor sees anything so
3817        // its input reflects the queue's current, already-resolved state.
3818        crate::task_chat::sweep(
3819            queue,
3820            &crate::talk::Talks::at(home.join("talks")),
3821            &questions,
3822            home,
3823        );
3824        repair_choice_offers(&questions);
3825        resolve_blockers(queue, &questions);
3826        apply_task_choice_actions(queue, &questions, home);
3827        triage::apply_answers(queue, &questions);
3828        reconcile_task_questions(queue, &questions);
3829        let talks = crate::talk::Talks::at(home.join("talks"));
3830        crate::chat_notify::sweep(queue, &talks, home);
3831        crate::notice_delivery::sweep(queue, &talks, home, &opts.repo);
3832        crate::chat_watch::sweep(home, &talks);
3833        let mut turns = tokio::task::JoinSet::new();
3834        crate::chat_notify::start_turns(&talks, stop.parking(), &mut turns);
3835        // start_turns dispatches detached turns; no paid work lives in this set.
3836        while turns.join_next().await.is_some() {}
3837
3838        crate::consult::start_services(
3839            home,
3840            &opts.repo,
3841            limits.recovery_cfg.as_ref(),
3842            opts.config.as_deref(),
3843        )
3844        .await?;
3845        for operation in [
3846            "conductor",
3847            "maintenance",
3848            "housekeeping",
3849            "disk-pressure",
3850            "cache",
3851            "fetch",
3852        ] {
3853            // Once an idle --once drain starts settling services, subsequent
3854            // scans only consume their effects. An expired cadence receipt
3855            // must not start another service and keep the drain alive.
3856            if settling_once_services {
3857                break;
3858            }
3859            start_service(
3860                home,
3861                opts,
3862                queue,
3863                worktrees_root,
3864                operation,
3865                limits.recovery_cfg.as_ref(),
3866                !live.is_empty(),
3867            )
3868            .await?;
3869        }
3870        let latest = crate::worker::active(home)?;
3871        if latest.iter().any(|job| job.key == "service:daemon-cache")
3872            || latest
3873                .iter()
3874                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
3875        {
3876            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
3877            continue;
3878        }
3879        let candidates: Vec<Task> = runnable(queue)
3880            .into_iter()
3881            .filter(|task| !live.contains(&task.id))
3882            .filter(|task| !opts.once || !attempted.contains(&task.id))
3883            .collect();
3884        let in_flight: Vec<_> = owned.iter().cloned().collect();
3885        let prior_interrupt = std::mem::discriminant(&interrupt);
3886        interrupt = advance_interrupt_tick(
3887            limits.pause_for_interrupts,
3888            interrupt,
3889            &in_flight,
3890            &candidates,
3891        );
3892        // Same-variant transitions preserve their identities. Only an actual
3893        // transition needs a durable write, atomically before sending controls.
3894        if prior_interrupt != std::mem::discriminant(&interrupt) {
3895            let temporary = interrupt_path.with_extension("json.tmp");
3896            std::fs::write(&temporary, serde_json::to_vec(&interrupt)?)?;
3897            std::fs::rename(temporary, &interrupt_path)?;
3898        }
3899        if let Interrupt::Parking {
3900            parked,
3901            interrupt_task,
3902        } = &interrupt
3903        {
3904            for job in jobs.iter().filter(|job| {
3905                parked
3906                    .iter()
3907                    .any(|id| job.key.strip_prefix("task:") == Some(id.as_str()))
3908            }) {
3909                if crate::worker::control(home, &job.key)?.is_none() {
3910                    request_task_park(
3911                        home,
3912                        job,
3913                        crate::run::ParkCause::Interrupt {
3914                            reason: format!(
3915                                "task {} asked to run first",
3916                                crate::run::short_of(interrupt_task)
3917                            ),
3918                        },
3919                    )?;
3920                }
3921            }
3922        }
3923        let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
3924        let cooling = read_cooldown(home)?.is_some_and(|until| Timestamp::now() < until);
3925        let mut started = false;
3926        let mut resync = false;
3927        for candidate in candidates {
3928            if stop.stopped() {
3929                break;
3930            }
3931            let Some(DispatchClaim {
3932                task,
3933                claim,
3934                permit,
3935            }) = claim_dispatch(queue, &candidate, cooling, &sem, &urgent_sem)
3936            else {
3937                continue;
3938            };
3939            if crate::worker::active(home)?
3940                .iter()
3941                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
3942            {
3943                drop(claim);
3944                resync = true;
3945                break;
3946            }
3947            let lane = permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent);
3948            let request = TaskWorker {
3949                opts: opts.absolute()?,
3950                queue: std::path::absolute(queue.root())?,
3951                task: task.id.clone(),
3952                lane,
3953                standalone: false,
3954            };
3955            // Keep the claim until spawn acknowledges the worker's durable
3956            // reservation. The worker then claims and re-reads before attempt.
3957            if let Err(error) = crate::worker::spawn(
3958                home,
3959                "task",
3960                &format!("task:{}", task.id),
3961                serde_json::to_value(&request)?,
3962            )
3963            .await
3964            {
3965                task_worker_spawn_error(home, &request, error)?;
3966                drop(claim);
3967                resync = true;
3968                break;
3969            }
3970            drop(claim);
3971            permits.extend(permit);
3972            attempted.push(task.id);
3973            started = true;
3974        }
3975        if started || resync {
3976            continue;
3977        }
3978        if owned.is_empty() && opts.once {
3979            settling_once_services = true;
3980            // These finite services can own queue claims or publish answers.
3981            // A skipped claim is not an idle queue until they have finished;
3982            // scan again afterwards so their changes are actually scheduled.
3983            if crate::worker::active(home)?.iter().any(|job| {
3984                job.kind == "daemon-service"
3985                    && matches!(
3986                        job.key.as_str(),
3987                        "service:daemon-housekeeping"
3988                            | "service:daemon-conductor"
3989                            | "service:daemon-maintenance"
3990                    )
3991            }) {
3992                stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
3993                continue;
3994            }
3995            break;
3996        }
3997        stop.idle(if live.is_empty() {
3998            opts.poll
3999        } else {
4000            RECHECK_WHILE_BUSY.min(opts.poll)
4001        })
4002        .await;
4003    }
4004    // Dropping a scheduler only drops dispatch bookkeeping. The workers own
4005    // every queue claim and Runner driver lease through outcome settlement.
4006    stop.busy.store(0, Ordering::SeqCst);
4007    Ok(())
4008}
4009
4010/// A maintenance pass may briefly own the same record while a worker starts.
4011/// Wait without blocking the executor or charging an agent attempt, then read
4012/// ownership again under the acquired lock. Other I/O failures still fail closed.
4013async fn resume_owner_lock(home: &Path, id: &str) -> Result<crate::pr_head::OwnerLock> {
4014    let busy = |error: &anyhow::Error| {
4015        error.downcast_ref::<std::io::Error>().is_some_and(|error| {
4016            error.kind() == std::io::ErrorKind::WouldBlock
4017                || cfg!(windows) && error.raw_os_error() == Some(33)
4018        })
4019    };
4020    match crate::pr_head::owner_lock(home, id) {
4021        Ok(lock) => return Ok(lock),
4022        Err(error) if busy(&error) => {}
4023        Err(error) => return Err(error),
4024    }
4025    let wait = RunState::load_under(id, home)?
4026        .config
4027        .graph
4028        .timeout_resource_wait;
4029    crate::pr_head::owner_lock_wait(home, id, Duration::from_secs(wait)).await
4030}
4031
4032/// Historical successors do not revoke a still-resumable public owner. Scan
4033/// under the same lock as publication/driver claims, and fail closed on unknown
4034/// history before spending another attempt.
4035async fn public_resume_owner(
4036    home: &Path,
4037    runs: &[String],
4038    repo: &Path,
4039) -> Result<Option<RunState>> {
4040    let mut owner = None;
4041    for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
4042        let _lock = resume_owner_lock(home, id).await?;
4043        let state = RunState::load_under(id, home)?;
4044        if state.released()
4045            || state.retired_to.is_some()
4046            || state.pr_taken_over_by.is_some()
4047            || !crate::handover::landing_checkpoint(&state)
4048        {
4049            continue;
4050        }
4051        anyhow::ensure!(
4052            crate::git::toplevel(&state.repo).await?.canonicalize()?
4053                == crate::git::toplevel(repo).await?.canonicalize()?,
4054            "public owner repository differs; inspect run lineage"
4055        );
4056        anyhow::ensure!(
4057            owner.is_none(),
4058            "multiple retained public owners; inspect run lineage"
4059        );
4060        if let Some(reason) = crate::handover::resume_refusal_under(&state, Some(home)) {
4061            anyhow::bail!(reason.diagnostic(&state));
4062        }
4063        let claimed = is_working_on_other(home, id, Timestamp::now())?;
4064        anyhow::ensure!(
4065            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
4066            "public owner's driver is live or unknown; wait before retrying"
4067        );
4068        owner = Some(state);
4069    }
4070    Ok(owner)
4071}
4072
4073/// Run one claimed task to a terminal status and record the outcome.
4074///
4075/// Every transition is flushed to the queue as it happens, so the state on disk
4076/// is what actually occurred rather than what this process still intends to
4077/// write.
4078async fn attempt(
4079    opts: &Opts,
4080    queue: &Queue,
4081    status: &Arc<Mutex<Status>>,
4082    stop: &Stop,
4083    interrupt_pause: crate::graph::Pause,
4084    task: &mut Task,
4085) -> Vec<QuotaLoss> {
4086    let repo = repo_for(task, &opts.repo);
4087    tracing::info!(
4088        "task {} — {} (repo {})",
4089        task.short(),
4090        task.title,
4091        repo.display()
4092    );
4093
4094    let public_owner = match public_resume_owner(&crate::run::home(), &task.runs, &repo).await {
4095        Ok(owner) => owner,
4096        Err(e) => {
4097            task.hold_machine(Some(format!(
4098                "Cannot verify existing public owner: {e:#}; no attempt started."
4099            )));
4100            record(queue, task);
4101            return Vec::new();
4102        }
4103    };
4104    let resume_runs = public_owner
4105        .as_ref()
4106        .map(|s| vec![s.id.clone()])
4107        .unwrap_or_else(|| task.runs.clone());
4108
4109    // A stop spends no agent resources and uses the saved landing owner.
4110    // Current roster edits, missing attachments or a failed config fetch must
4111    // never turn it into a new implementation, or prevent a PR from closing.
4112    if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
4113        && previous
4114            .merge_decision
4115            .as_ref()
4116            .is_some_and(|decision| !decision.closed)
4117        && previous.status != RunStatus::Landing
4118        && !crate::merge_decision::resumable_hold(&previous)
4119    {
4120        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)));
4121        record(queue, task);
4122        return Vec::new();
4123    }
4124    let stop_owner = resume_runs
4125        .last()
4126        .and_then(|id| RunState::load(id).ok())
4127        .filter(|state| {
4128            crate::merge_decision::resumable_hold(state)
4129                || state.status == RunStatus::Landing
4130                    && state.land_approval.as_ref().is_some_and(|binding| {
4131                        Questions::open().get(&binding.question).is_ok_and(|q| {
4132                            q.run == state.id
4133                                && q.resolution()
4134                                    .as_deref()
4135                                    .is_some_and(crate::merge_decision::stops)
4136                        })
4137                    })
4138        });
4139    if let Some(owner) = stop_owner {
4140        let mut runner = match Runner::resume(&owner.id) {
4141            Ok(runner) => runner,
4142            Err(e) => {
4143                task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
4144                record(queue, task);
4145                return Vec::new();
4146            }
4147        };
4148        runner.on_pause(stop.pause());
4149        runner.watch_interrupt(interrupt_pause);
4150        let quota_before = runner.state.quota.clone();
4151        task.start(owner.id.clone());
4152        record(queue, task);
4153        lock(status).current.push(Current {
4154            worker: None,
4155            task: task.id.clone(),
4156            run: owner.id,
4157        });
4158        runner.state.next_pass_task_entry = true;
4159        let result = runner.execute().await;
4160        return finish_attempt(
4161            opts.max_attempts,
4162            queue,
4163            task,
4164            &runner.state,
4165            &quota_before,
4166            result,
4167        );
4168    }
4169
4170    if let Some(owner) = &public_owner
4171        && (task.fresh_start || !may_resume_run(owner, task))
4172    {
4173        task.hold_machine(Some(format!("Existing PR belongs to run {}; resume its authorized instructions or explicitly resolve its owner decision before starting a successor. No attempt started.", owner.id)));
4174        record(queue, task);
4175        return Vec::new();
4176    }
4177
4178    if let Some(held) = crate::base_sync_recovery::held_run(queue, task)
4179        && !task.fresh_start
4180        && task.review_branch.is_none()
4181        && task.pr_recovery.is_none()
4182    {
4183        // Authorization still takes the owner lock and execution lease and
4184        // rechecks liveness, retained HEAD and ownership before saving.
4185        let authorized = if task.resumption.is_some() && compatible_run_instruction(&held, task) {
4186            let home = queue.root().parent().expect("queue has a home");
4187            match Runner::authorize_base_recovery_from_resumption(home, &held.id, &task.id).await {
4188                Ok(()) => true,
4189                Err(error) => {
4190                    tracing::debug!(run = %held.id, %error, "base recovery resumption refused");
4191                    false
4192                }
4193            }
4194        } else {
4195            false
4196        };
4197        if !authorized {
4198            task.hold_machine(Some("Base synchronization remains stopped. Inspect the retained run; for movement exhaustion, explicitly use `magi run --resume <run> --recover-base`. A release without a new owner approval grants no additional rebase and starts no replacement competition.".into()));
4199            // Retain the existing stop identity when an old release reached the queue.
4200            task.base_sync_notice(&held);
4201            task.resume_override = None;
4202            record(queue, task);
4203            return Vec::new();
4204        }
4205    }
4206    let unfinished = (!task.fresh_start)
4207        .then(|| unfinished_run(&resume_runs, task.short()))
4208        .flatten()
4209        .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
4210    let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
4211    if !task.fresh_start
4212        && task.pr_recovery.is_none()
4213        && task.review_branch.is_none()
4214        && task.resume_override.is_none()
4215        && previous
4216            .as_ref()
4217            .is_some_and(|run| run.retired_to.is_some())
4218        && unfinished.is_none()
4219    {
4220        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()));
4221        record(queue, task);
4222        return Vec::new();
4223    }
4224
4225    let saved_recovery = previous.as_ref().filter(|run| {
4226        task.replacement.is_none()
4227            && task.pr_recovery.as_ref().is_some_and(|selected| {
4228                selected.check_task(&task.id, &task.instruction).is_ok()
4229                    && selected_starter(selected, Some(run), unfinished.as_deref())
4230                        == Starter::Resume(run.id.clone())
4231            })
4232    });
4233
4234    // The repository's magi.toml comes from `<remote>/<base>`, fetched now. A
4235    // failure here is the network's or the operator's, not the task's: hold
4236    // without spending an attempt, never fall back to a possibly stale copy.
4237    let explicit = match &task.overrides {
4238        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
4239        Some(_) => opts.config.as_deref(),
4240        None => opts.config.as_deref(),
4241    };
4242    let (mut config, layers) = if let Some(run) = saved_recovery {
4243        // A matching resume owns its resolved configuration and evidence;
4244        // current layers and inherited overrides only configure new work.
4245        let mut saved = run.clone();
4246        if let Err(e) = saved.configure_recovery_resume() {
4247            task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
4248            record(queue, task);
4249            return Vec::new();
4250        }
4251        (saved.config, Vec::new())
4252    } else {
4253        let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
4254            Ok(loaded) => loaded,
4255            Err(e) => {
4256                let reason = format!("[config] {e:#}");
4257                record_config_failure(task, &e);
4258                task.last_error = Some(reason.clone());
4259                task.hold_machine(Some(reason));
4260                record(queue, task);
4261                return Vec::new();
4262            }
4263        };
4264        if let Err(e) = apply_options(&mut config, opts, task) {
4265            task.hold_manual(Some(format!(
4266                "[config] {e:#}; correct the merge override before releasing the task"
4267            )));
4268            record(queue, task);
4269            return Vec::new();
4270        }
4271        if let Some(selected) = &task.pr_recovery
4272            && let Err(e) = selected.configure(&mut config)
4273        {
4274            task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
4275            record(queue, task);
4276            return Vec::new();
4277        }
4278        (config, layers)
4279    };
4280    let config_evidence = crate::pr_recovery::ConfigEvidence {
4281        layers,
4282        overrides: task.overrides.clone(),
4283        daemon_merge: task
4284            .overrides
4285            .as_ref()
4286            .is_none_or(|o| o.inherit_daemon_options)
4287            .then(|| opts.merge.clone())
4288            .flatten(),
4289    };
4290    apply_task_implementers(&mut config, task);
4291    if let Some(replacement) = &task.replacement {
4292        let safe = RunState::load(&replacement.run).is_ok_and(|old| {
4293            old.liveness(false) == Liveness::Dead
4294                && old.merge_decision.as_ref().is_some_and(|d| {
4295                    d.closed
4296                        && d.question == replacement.question
4297                        && d.replacement_run.as_ref().is_none_or(|run| {
4298                            task.runs.last() == Some(run)
4299                                && RunState::load(run).is_ok_and(|current| {
4300                                    current.replaces.as_ref().is_some_and(|pin| {
4301                                        pin.question == replacement.question
4302                                            && pin.agent == replacement.agent
4303                                    })
4304                                })
4305                        })
4306                })
4307        });
4308        if !safe {
4309            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()));
4310            record(queue, task);
4311            return Vec::new();
4312        }
4313        match config.agent(&replacement.agent) {
4314            Ok(agent) if crate::agent::installed(agent) => {}
4315            _ => {
4316                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)));
4317                record(queue, task);
4318                return Vec::new();
4319            }
4320        }
4321        config.graph.implementers = 1;
4322        config.graph.land_approval = true;
4323        config.merge.mode = MergeMode::Pr;
4324        config.graph.selected_implementer = Some(replacement.agent.clone());
4325    }
4326    let p = phrases(&config.graph.language);
4327    let start_failed = p.could_not_start;
4328    // Resolve once for both admission and settlement. The inputs are the
4329    // task's explicit sources (never prose), plus an explicit review source's
4330    // current head; review-only runs may rebase later, and neither fact can
4331    // refund a failed automatic generation.
4332    if let Ok(base) =
4333        crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
4334            .await
4335        && let Ok(head) =
4336            crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
4337    {
4338        let mut inputs = crate::queue::recovery_inputs(&task.sources);
4339        if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
4340            let source = crate::git::rev_parse(&repo, branch)
4341                .await
4342                .unwrap_or_default();
4343            inputs.push_str(&format!(";review:{branch}:{source}"));
4344        }
4345        if let Some(reason) = task.recovery_exhausted(
4346            &head,
4347            &inputs,
4348            task.attempt_limit
4349                .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
4350        ) {
4351            task.hold_unrequested_retry(Some(reason));
4352            record(queue, task);
4353            return Vec::new();
4354        }
4355        task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
4356    }
4357
4358    // The free-space gate, checked *before* anything is minted: a task that
4359    // waits out a full disk costs nothing yet, and must not spend an attempt
4360    // or start a run the machine cannot finish. Held tasks stay in the list
4361    // for the human to see, and `magi task release` re-queues them when space
4362    // comes back - the same recovery as any other hold. A volume whose free
4363    // space cannot be measured closes the gate too: starting a run blind on a
4364    // disk that may be full is how the machine ends up with 6.7 GB free.
4365    if let Some(reason) = disk_gate(&repo, &config) {
4366        task.notice_cause("disk-space", None, None);
4367        task.last_error = Some(reason.clone());
4368        task.hold_machine(Some(reason.clone()));
4369        record(queue, task);
4370        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
4371        // Stable wording - the free-space figures live in the task's hold
4372        // reason, and changing numbers would relight the bell every poll.
4373        notices::raise(
4374            Notice::warn(
4375                &format!("disk:{}", repo.display()),
4376                format!("Task {} held for want of free disk space: {reason}. Free some, then release it from the queue.", task.id),
4377            )
4378            .link(Link::Task {
4379                id: task.id.clone(),
4380            }),
4381        );
4382        return Vec::new();
4383    }
4384
4385    // A resumable run of this task is carried on, never re-competed. The
4386    // candidates are built and paid for, and a fresh competition races a
4387    // second implementation against them.
4388    //
4389    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
4390    // started 3cbf on the same task a moment later, duplicating two and a
4391    // half hours of agent work. Then b25f stalled on a judge that timed out
4392    // and one that answered with no JSON - `quota: 0`, so nothing the machine
4393    // was to blame for - and 4043 started **one second** later, buying three
4394    // fresh implementations to reach the same panel. `RunStatus::resumable`
4395    // rather than `!done()` is what catches the second case: a stall is
4396    // terminal, and its cheap recovery re-asks only the absent seats.
4397    //
4398    // A load failure is warned about rather than silently read as "not
4399    // resumable": the alternative is exactly what let a schema mismatch on
4400    // run `eba2` fall through to a full re-competition with nobody told why.
4401    // `crate::conduct` is what actually offers a better answer than
4402    // `Runner::start` here (see `Recovery::Review`), once this task's next
4403    // failure shows it up as `held`/`failed` with the run state unreadable.
4404    // `crate::conduct` chose `Review` for this task on an earlier cycle: its
4405    // branch survived, and this reopens exactly that branch as a
4406    // review-only pass rather than resuming or competing again. Consumed
4407    // (cleared) here whichever way this goes, so it never outlives this one
4408    // attempt - see `queue::Task::review_branch`.
4409    let review_branch = take_review_branch(task, previous.as_ref());
4410    let branch_exists = match &review_branch {
4411        Some(branch) => crate::git::branch_exists(&repo, branch)
4412            .await
4413            .unwrap_or(false),
4414        None => false,
4415    };
4416    // An explicit `magi review <branch>` is reviewed whatever happens to the
4417    // branch unless an explicit implementer change requires fresh work. An
4418    // unfinished run of the same task still wins, so a retry resumes.
4419    let proposed = review_retry_starter(
4420        task,
4421        previous.as_ref(),
4422        review_branch.as_deref(),
4423        branch_exists,
4424        unfinished.as_deref(),
4425    );
4426    let retry_selected = task.replacement.is_some()
4427        && task.resumption.is_some()
4428        && !task.fresh_start
4429        && previous.as_ref().is_some_and(|run| {
4430            run.replaces.is_some()
4431                && ((run.status == RunStatus::Failed && run.viable().is_empty())
4432                    || (run.status == RunStatus::Blocked && run.tally.is_none()))
4433        });
4434    let stop_pin = task
4435        .resume_override
4436        .as_ref()
4437        .filter(|pin| {
4438            Questions::open().get(&pin.question_id).is_ok_and(|q| {
4439                q.node == land::APPROVAL_NODE
4440                    && q.resolution()
4441                        .as_deref()
4442                        .is_some_and(crate::merge_decision::stops)
4443            })
4444        })
4445        .and_then(|pin| pin.pinned_run.clone());
4446    let starter = if let Some(owner) = &public_owner {
4447        Starter::Resume(owner.id.clone())
4448    } else if let Some(run) = stop_pin {
4449        // Stop actions resume their exact owner even after seat-count edits;
4450        // they must never fall through to implementation or a takeover.
4451        Starter::Resume(run)
4452    } else if retry_selected {
4453        Starter::Resume(previous.as_ref().unwrap().id.clone())
4454    } else if let Some(selected) = &task.pr_recovery {
4455        if selected.check_task(&task.id, &task.instruction).is_ok() {
4456            selected_starter(selected, previous.as_ref(), unfinished.as_deref())
4457        } else {
4458            Starter::Review(selected.branch.clone())
4459        }
4460    } else {
4461        starter_with_implementers(task, previous.as_ref(), proposed)
4462    };
4463    // An explicit resume pin must never degrade into a new competition or
4464    // takeover, including when its run stops being eligible after the answer.
4465    if let Some(pin) = &task.resume_override
4466        && let Some(run) = &pin.pinned_run
4467        && starter != Starter::Resume(run.clone())
4468    {
4469        let run = run.clone();
4470        task.notice_cause("resume-owner", Some(&run), None);
4471        task.hold_machine(Some(format!(
4472            "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
4473            task.id
4474        )));
4475        record(queue, task);
4476        return Vec::new();
4477    }
4478    if task.replacement.is_some()
4479        && previous.as_ref().is_some_and(|run| run.replaces.is_some())
4480        && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
4481    {
4482        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()));
4483        record(queue, task);
4484        return Vec::new();
4485    }
4486    if let Some(reason) = retained_attempt_hold(
4487        task,
4488        &starter,
4489        config.disk.retained_attempt_limit,
4490        RunState::load,
4491    ) {
4492        // The review choice was consumed above. Preserve it across this hold
4493        // so a later release cannot silently become a fresh implementation.
4494        if let Starter::Review(branch) = &starter {
4495            task.review_branch = Some(branch.clone());
4496        }
4497        task.hold_unrequested_retry(Some(reason));
4498        record(queue, task);
4499        return Vec::new();
4500    }
4501    // Absolute paths of the files the task was filed with, re-read from the
4502    // task now so a file attached while it was held reaches a resumed run
4503    // too. A stored name whose file has gone is an error before any agent is
4504    // paid for, never a silent omission the implementer cannot notice.
4505    let attachments = match task_attachments(queue, task) {
4506        Ok(a) => a,
4507        Err(e) => {
4508            task.attempts += 1;
4509            task.fail_startup_target(
4510                "startup-attachments",
4511                e.name.clone(),
4512                format!("{start_failed}{e:#}"),
4513                opts.max_attempts,
4514            );
4515            record(queue, task);
4516            return Vec::new();
4517        }
4518    };
4519    let startup_pause = stop.pause();
4520    let startup_interrupt = interrupt_pause.clone();
4521    let wait = crate::repo_lock::WaitPolicy::new(
4522        Duration::from_secs(config.graph.timeout_resource_wait),
4523        move || startup_pause.parked() || startup_interrupt.parked(),
4524    );
4525    // Startup includes review takeover and recovery. Do not embed its large
4526    // future in both the wait scope and the surrounding attempt stack frame.
4527    let started = wait.scope(Box::pin(async { match &starter {
4528        Starter::Review(_) if task.pr_recovery.is_some() => {
4529            let selected = task.pr_recovery.clone().expect("selected recovery");
4530            match selected.check_task(&task.id, &task.instruction) {
4531                Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
4532                    .await
4533                    .map(|mut r| {
4534                        r.state.attachments = attachments.clone();
4535                        r
4536                    }),
4537                Err(e) => Err(e),
4538            }
4539        }
4540        Starter::Review(branch) => {
4541            tracing::info!(
4542                "task {} reopens `{branch}` as a review-only pass",
4543                task.short()
4544            );
4545            // Every earlier attempt is superseded by the one being minted
4546            // now, so a branch one of them still holds may be taken over.
4547            let takeover = crate::handover::Takeover {
4548                earlier: task.earlier_attempts().to_vec(),
4549                home: crate::run::home(),
4550                choice: take_divergence_answer(branch, &config.merge.remote, task),
4551                task_instruction: Some(instruction_for(task)),
4552            };
4553            Runner::review_taking_over(
4554                &repo,
4555                branch,
4556                config,
4557                Some(takeover),
4558                crate::run::Origin::queue(&task.id),
4559            )
4560            .await
4561        }
4562        Starter::Resume(id) => {
4563            tracing::info!("resuming run {id} rather than competing again");
4564            Runner::resume(id).and_then(|mut r| {
4565                if retry_selected {
4566                    // The explicit queue release retries this same pinned
4567                    // implementation, preserving the attempt and worktrees.
4568                    for candidate in &mut r.state.candidates {
4569                        candidate.failed = None;
4570                        candidate.empty = false;
4571                        candidate.commits = 0;
4572                    }
4573                    r.state.status = RunStatus::Implementing;
4574                    r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
4575                }
4576                if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
4577                    r.state.sources = task.sources.clone();
4578                }
4579                if r.state.prep_failure.is_some() {
4580                    let approval = task
4581                        .resumption
4582                        .as_ref()
4583                        .context("preparation retry requires an explicit task release")?;
4584                    r.retry_preparation(approval.at)?;
4585                }
4586                if let Some(instruction) =
4587                    prepare_instruction(&starter, Some(&r.state.instruction), task)
4588                {
4589                    r.state.instruction = instruction;
4590                }
4591                r.state.attachments = attachments.clone();
4592                if task.replacement.is_some() {
4593                    r.state.config.merge.mode = MergeMode::Pr;
4594                    r.state.config.graph.land_approval = true;
4595                }
4596                // Replacements publish a new PR and ask again. Selected PR
4597                // recoveries keep their saved disposition; ordinary runs can
4598                // retain the task's merge override.
4599                if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
4600                    .overrides
4601                    .as_ref()
4602                    .and_then(|o| o.merge.as_deref())
4603                    .and_then(|m| merge_mode(m).ok())
4604                {
4605                    r.state.config.merge.mode = mode;
4606                }
4607                Ok(r)
4608            })
4609        }
4610        Starter::Start => {
4611            if let Some(branch) = &review_branch {
4612                tracing::warn!(
4613                    "conductor chose review for task {} but branch `{branch}` no longer \
4614                     exists; requeuing as a fresh competition instead",
4615                    task.short()
4616                );
4617            }
4618            let instruction = prepare_instruction(&starter, None, task)
4619                .unwrap_or_else(|| task.instruction.clone());
4620            Runner::start_naming(
4621                &repo,
4622                instruction,
4623                &task.title,
4624                config,
4625                crate::run::Origin::queue(&task.id),
4626            )
4627            .await
4628            .map(|mut r| {
4629                r.state.attachments = attachments.clone();
4630                r.state.sources = task.sources.clone();
4631                r
4632            })
4633        }
4634    }})).await;
4635    let mut runner = match started {
4636        Ok(r) => r,
4637        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
4638            task.last_error = Some(e.to_string());
4639            if stop.parking() || interrupt_pause.parked() {
4640                let attempts = task.attempts;
4641                task.park(e.to_string());
4642                // Startup has not spent an attempt to refund.
4643                task.attempts = attempts;
4644            } else {
4645                task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
4646            }
4647            record(queue, task);
4648            return Vec::new();
4649        }
4650        // A branch an earlier attempt still holds and magi will not release
4651        // by itself is the operator's call, not a failed attempt: hold the
4652        // task with the reason, spend nothing, and say so on the bell.
4653        Err(e) if task.pr_recovery.is_some() => {
4654            task.startup_notice_cause("startup-public-head");
4655            task.attempts += 1;
4656            if let Some(partial) = e.downcast_ref::<crate::pr_recovery::StartupFailed>() {
4657                task.link_run(&partial.run);
4658                task.record_pass(&partial.run, 0, task.attempts, None);
4659            }
4660            task.last_error = Some(format!("{start_failed}{e:#}"));
4661            task.hold_unrequested_retry(Some(format!(
4662                "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."
4663            )));
4664            record(queue, task);
4665            return Vec::new();
4666        }
4667        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
4668            let detail = match e.downcast_ref::<crate::handover::Refused>() {
4669                Some(r) => (p.handover_refused)(r),
4670                None => format!("{e:#}"),
4671            };
4672            task.startup_notice_cause("startup-handover");
4673            let reason = format!("{start_failed}{detail}");
4674            task.last_error = Some(reason.clone());
4675            // Consumed above by `take`; keep it so the released task retries
4676            // as a review of this same branch.
4677            let branch = match &starter {
4678                Starter::Review(branch) => Some(branch.clone()),
4679                _ => None,
4680            };
4681            // The hold's own `task:<id>` notice (raised by `Queue::put`) is the
4682            // one page; the guidance rides in the reason, fixed per state so a
4683            // re-put never changes the wording and relights it.
4684            task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
4685            record(queue, task);
4686            tracing::warn!(
4687                "holding {} for a branch it cannot take over: {e:#}",
4688                task.short()
4689            );
4690            return Vec::new();
4691        }
4692        // A branch that differs between here and the remote in ways magi
4693        // cannot prove are the same change is a decision for the owner, not a
4694        // failed attempt: ask with both sides laid out, spend no attempt, and
4695        // let the answer requeue the task.
4696        Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
4697            let d = e
4698                .downcast_ref::<crate::reconcile::Diverged>()
4699                .expect("checked by the guard");
4700            let mut q = ask::Question::new(
4701                task.id.clone(),
4702                crate::reconcile::NODE.to_owned(),
4703                crate::reconcile::SEAT.to_owned(),
4704                d.summary(),
4705                d.detail(),
4706                d.choices(),
4707            );
4708            match Questions::open().put(&mut q) {
4709                Ok(()) => {
4710                    task.last_error = Some(format!("{e:#}"));
4711                    // Consumed above by `take`; the answer has to reach a review
4712                    // of this same branch, so keep pointing the task at it.
4713                    task.review_branch = Some(d.branch.clone());
4714                    task.review_instruction = Some(task.instruction.clone());
4715                    task.block(vec![q.id.clone()], Some(d.summary()));
4716                }
4717                Err(put) => {
4718                    tracing::warn!("could not file the divergence question: {put:#}");
4719                    task.attempts += 1;
4720                    task.fail_startup(
4721                        "startup-question-store",
4722                        format!("{start_failed}{e:#}"),
4723                        opts.max_attempts,
4724                    );
4725                }
4726            }
4727            record(queue, task);
4728            return Vec::new();
4729        }
4730        Err(e) => {
4731            // The answer was stale and nothing was applied: keep pointing at
4732            // the branch so the next attempt asks again against its new tips.
4733            // Nothing went wrong with the task, so no attempt is spent: a
4734            // budget one short of its limit must not hold it instead of
4735            // letting the question be asked again.
4736            if e.downcast_ref::<crate::reconcile::Stale>().is_some()
4737                && let Starter::Review(branch) = &starter
4738            {
4739                task.review_branch = Some(branch.clone());
4740                task.review_instruction = Some(task.instruction.clone());
4741                task.last_error = Some(format!("{start_failed}{e:#}"));
4742                task.status = crate::queue::TaskStatus::Failed;
4743                record(queue, task);
4744                return Vec::new();
4745            }
4746            task.attempts += 1;
4747            task.last_error = Some(format!("{start_failed}{e:#}"));
4748            task.startup_notice_cause("startup-source");
4749            task.hold_unrequested_retry(Some(format!(
4750                "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
4751            )));
4752            record(queue, task);
4753            return Vec::new();
4754        }
4755    };
4756    if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
4757        runner.state.recovery_config = Some(config_evidence);
4758    }
4759    if let Some(replacement) = &task.replacement {
4760        if matches!(starter, Starter::Start) {
4761            runner.state.instruction.push_str(&format!(
4762                "\n\n# Replacement review context\n{}",
4763                replacement.context
4764            ));
4765        }
4766        runner.state.replaces = Some(replacement.clone());
4767        runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
4768        if let Ok(mut old) = RunState::load(&replacement.run)
4769            && let Some(d) = &mut old.merge_decision
4770        {
4771            d.replacement_run = Some(runner.state.id.clone());
4772            old.event(
4773                "replacement",
4774                format!(
4775                    "replacement run {} owns the next attempt; old PR remains closed",
4776                    runner.state.id
4777                ),
4778            );
4779            if let Err(e) = old.save() {
4780                task.hold_manual(Some(format!(
4781                    "Could not link replacement history: {e}; no agents dispatched"
4782                )));
4783                record(queue, task);
4784                return Vec::new();
4785            }
4786        }
4787    }
4788    runner.state.task_instruction = Some(task.instruction.clone());
4789    // The follow-up depth is fixed now, while the task certainly exists:
4790    // deleting it later must not reset the cap (`crate::followup`).
4791    runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
4792    if runner.state.origin_chat.is_none() {
4793        runner.state.origin_chat = task.chat_talk().map(str::to_owned);
4794    }
4795    // A stop that means "park" reaches the graph through this handle.
4796    runner.on_pause(stop.pause());
4797    // `poll`'s interrupt scheduler reaches this one run - and no other -
4798    // through this handle. See `Pause`'s own doc for why these are never
4799    // the same one.
4800    runner.watch_interrupt(interrupt_pause);
4801
4802    // `start` has minted the run, so the task can now point at it. Persisting
4803    // `Running` before `execute` is what makes a crash mid-run legible.
4804    let run = runner.state.id.clone();
4805    task.start(run.clone());
4806    record(queue, task);
4807    lock(status).current.push(Current {
4808        worker: None,
4809        task: task.id.clone(),
4810        run,
4811    });
4812
4813    // `RunState::quota` is the run's whole history across every resume, so
4814    // only what this execution added may arm the cooldown or earn a refund.
4815    let quota_before = runner.state.quota.clone();
4816    runner.state.next_pass_task_entry = true;
4817    let result = runner.execute().await;
4818    finish_attempt(
4819        opts.max_attempts,
4820        queue,
4821        task,
4822        &runner.state,
4823        &quota_before,
4824        result,
4825    )
4826}
4827
4828/// Settle `task` after its run executed: the verdict, the diagnosis, the
4829/// supersession of earlier attempts and the save. Shared by the loop and by
4830/// `magi run --resume`, so an attempt is counted one way wherever it ran.
4831/// Returns the quota losses this execution added to the run.
4832pub fn finish_attempt(
4833    max_attempts: usize,
4834    queue: &Queue,
4835    task: &mut Task,
4836    state: &RunState,
4837    quota_before: &[QuotaLoss],
4838    result: Result<()>,
4839) -> Vec<QuotaLoss> {
4840    let detail = match result {
4841        Ok(()) => describe(state),
4842        Err(e) => format!("{e:#}"),
4843    };
4844    let fresh = losses_this_attempt(quota_before, &state.quota);
4845    let verdict = Verdict {
4846        status: state.status,
4847        // A run that opened a pull request handed its work over, whatever the
4848        // gate then decided about merging it.
4849        left_pr: state.pr.is_some(),
4850        // Only a rate limit earns the task its attempt back - and only one
4851        // suffered now: a refund justified by a previous session's loss is
4852        // the same mistake as re-arming the cooldown from it. A stalled run
4853        // resumed without hitting quota again therefore spends its attempt,
4854        // like any other failure of the task's own.
4855        quota_hit: !fresh.is_empty(),
4856        // A run that parked was asked to stop; that is not a failure and must
4857        // not spend an attempt, or replacing the binary a few times would
4858        // exhaust a task's budget without an agent ever misbehaving.
4859        parked: state.parked,
4860        // A quota loss that left nothing viable is the same machine fact as a
4861        // `Stalled` quota loss; see `settle`'s doc table.
4862        no_viable_candidates: state.viable().is_empty(),
4863    };
4864    if let Some(replacement) = &state.replaces
4865        && let Some(pr) = &state.pr
4866        && let Ok(mut old) = RunState::load(&replacement.run)
4867        && let Some(d) = &mut old.merge_decision
4868    {
4869        d.replacement_pr = Some(pr.url.clone());
4870        let _ = old.save();
4871    }
4872    settle_and_diagnose(task, verdict, &detail, max_attempts, state);
4873    if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
4874        task.hold_unrequested_retry(Some(format!(
4875            "Candidate setup failed: {detail}. Correct the explicit sources with `magi task sources {}` (README, \"Use\": implementation imports), or select a complete implementation with `magi task recover-pr`, then explicitly release the task.",
4876            task.short()
4877        )));
4878    }
4879    if task.status == TaskStatus::Done {
4880        supersede_prior_runs(task, &crate::run::home());
4881    }
4882    record(queue, task);
4883    tracing::info!(
4884        "task {} is {} after run {} ({})",
4885        task.short(),
4886        task.status.as_str(),
4887        state.short(),
4888        label(state.status)
4889    );
4890    fresh
4891}
4892
4893/// A task a hand-started run leaves runnable (failed with attempts to spare,
4894/// or requeued) is **held**: nobody asked for a retry, and a loop starting
4895/// later must not spend agent calls on it. `magi task release` retries.
4896pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
4897    // Parked work (including legacy Failed records with a parked run) is a
4898    // checkpoint or owner handoff, not an unrequested retry.
4899    if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
4900        && !awaiting_resume_with(task, RunState::load)
4901        // A run parked on the owner's word about a withheld PR title/body
4902        // resumes via `land_resume_state`, including review-only tasks that
4903        // `awaiting_resume_with` does not consider.
4904        && withheld_text_wait(task).is_none()
4905        && !(task.fresh_start && task.replacement.is_some())
4906    {
4907        let why = task.last_error.clone().map_or_else(
4908            || "the run did not finish".to_owned(),
4909            |e| format!("the run did not finish: {e}"),
4910        );
4911        task.hold_unrequested_retry(Some(format!(
4912            "{why}. It was started by hand, so it is not retried \
4913             automatically; `magi task release` retries it."
4914        )));
4915        record(queue, task);
4916    }
4917}
4918
4919/// Whether an attempt at a task whose newest run is `run` would resume that
4920/// run rather than start a fresh competition. `magi run --resume` hands a run
4921/// to a live loop only when this holds.
4922#[must_use]
4923pub fn loop_would_resume(run: &str) -> bool {
4924    unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
4925}
4926
4927/// A loop in another process that is alive right now: a fresh heartbeat in
4928/// `<home>/daemon.json` published by a pid that is not `own_pid`. `Some(pid)`
4929/// carries the pid it published (`None` inside when it published none - a
4930/// fresh heartbeat is still evidence of a live loop).
4931///
4932/// The one judgement of "is somebody else serving this queue", shared by the
4933/// web UI's refusal to start a second loop and by `magi run` / `magi review`
4934/// deciding whether to hand a task to the loop. A claim file proves nothing
4935/// here: whether a claim succeeds says nothing about whether its owner lives.
4936#[must_use]
4937pub fn foreign_loop(
4938    reading: Option<&Reading>,
4939    now: Timestamp,
4940    own_pid: u32,
4941) -> Option<Option<u32>> {
4942    let reading = reading.filter(|r| r.running(now))?;
4943    match reading.pid {
4944        Some(pid) if pid == own_pid => None,
4945        pid => Some(pid),
4946    }
4947}
4948
4949fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
4950    reading.worker_protocol != Some(1)
4951        && (foreign_loop(Some(reading), now, own_pid).is_some()
4952            || reading
4953                .pid
4954                .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
4955}
4956
4957/// Low-level claimed-task execution shared by the detached standalone worker
4958/// and focused lifecycle fixtures. The caller must retain the queue claim for
4959/// this entire call. CLI callers transfer ownership through
4960/// [`run_detached_claimed`] instead of executing inside their own runtime.
4961///
4962/// The one deliberate difference from the loop: a task the attempt leaves
4963/// runnable (failed with attempts to spare, or requeued) is **held** instead.
4964/// Nobody asked for a retry, and a daemon starting later must not spend agent
4965/// calls re-running a hand-started task behind the operator's back;
4966/// `magi task release` is the explicit retry.
4967pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
4968    run_claimed_until(opts, queue, task, &Stop::new()).await;
4969}
4970
4971async fn run_claimed_until(
4972    opts: &Opts,
4973    queue: &Queue,
4974    task: &mut Task,
4975    stop: &Stop,
4976) -> Vec<QuotaLoss> {
4977    let status = Arc::new(Mutex::new(Status::new()));
4978    // An attempt embeds startup and graph futures. Keep it off the standalone
4979    // caller's stack, on both the initial execution and withheld-text resume.
4980    let mut quota = Box::pin(attempt(
4981        opts,
4982        queue,
4983        &status,
4984        stop,
4985        crate::graph::Pause::new(),
4986        task,
4987    ))
4988    .await;
4989    // A run parked on the owner's word about a withheld PR title/body has no
4990    // daemon to finish it. Nobody else will enforce `answer_timeout`, so wait
4991    // here with the claim still held, and resume once the question is settled
4992    // (answered, or abandoned at its deadline -> the neutral text).
4993    // A rejected reply files one more question (the gate asks at most twice),
4994    // so after a resume the run may be waiting again: keep going, with a fresh
4995    // limit for the new question. `resumes` bounds it even if a resume parks
4996    // without asking anything new.
4997    let mut resumes = 0;
4998    while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
4999        let Some(timeout) = withheld_text_wait(task) else {
5000            break;
5001        };
5002        eprintln!(
5003            "waiting for the owner's answer on a withheld pull request text \
5004             (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
5005        );
5006        // The deadline abandons the question itself; the extra margin only
5007        // covers an abandon that could not be saved.
5008        let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
5009        let ready = loop {
5010            match land_resume_state(task) {
5011                LandResume::StillWaiting
5012                    if !stop.parking() && std::time::Instant::now() < limit =>
5013                {
5014                    tokio::time::sleep(WITHHELD_POLL).await;
5015                }
5016                LandResume::Ready => break true,
5017                _ => break false,
5018            }
5019        };
5020        if !ready || stop.parking() {
5021            break;
5022        }
5023        resumes += 1;
5024        quota.extend(
5025            Box::pin(attempt(
5026                opts,
5027                queue,
5028                &status,
5029                stop,
5030                crate::graph::Pause::new(),
5031                task,
5032            ))
5033            .await,
5034        );
5035    }
5036    hold_if_runnable(queue, task);
5037    quota
5038}
5039
5040/// Resumes an in-process run makes for withheld-text questions: the gate asks
5041/// at most twice, plus one for a resume that asks nothing new.
5042const MAX_WITHHELD_RESUMES: u32 = 3;
5043
5044/// How often an in-process run rechecks its withheld-text question.
5045const WITHHELD_POLL: Duration = Duration::from_secs(15);
5046
5047/// The `answer_timeout` (seconds) of the task's last run when that run is
5048/// parked on an unresolved withheld-text question; `None` otherwise.
5049fn withheld_text_wait(task: &Task) -> Option<u64> {
5050    let id = task.runs.last()?;
5051    let s = RunState::load(id).ok()?;
5052    (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
5053        .then_some(s.config.graph.answer_timeout)
5054}
5055
5056/// The quota losses `after` holds that `before` did not: what one execution
5057/// suffered, as opposed to the run's history.
5058///
5059/// Compared by value rather than by length or position because
5060/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
5061/// the vector can shrink and shift under a resume. A retried seat that hits
5062/// quota again is a `push` with a new `at`, so it shows up as new here.
5063/// Crash recovery uses the recorded pass start as its boundary when available;
5064/// legacy records without passes retain their original history-based policy.
5065fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
5066    after
5067        .iter()
5068        .filter(|q| !before.contains(q))
5069        .cloned()
5070        .collect()
5071}
5072
5073/// When the loop-wide quota cooldown should end, given this attempt's losses;
5074/// `None` when there were none. Reset-hint parsing and the cap live here.
5075fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
5076    let quota: Vec<_> = quota
5077        .iter()
5078        .filter(|q| q.cause == crate::agent::QuotaCause::UsageLimit)
5079        .collect();
5080    if quota.is_empty() {
5081        return None;
5082    }
5083    let with_hint = quota.iter().find(|q| q.reset.is_some());
5084    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
5085    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
5086    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
5087    Some(
5088        now.checked_add(jiff::SignedDuration::from_secs(secs))
5089            .unwrap_or(Timestamp::MAX),
5090    )
5091}
5092
5093/// An explicit task count must agree with a run before any resume.
5094fn implementers_match(task: &Task, state: &RunState) -> bool {
5095    task.replacement.as_ref().map_or_else(
5096        || {
5097            task.implementers()
5098                .is_none_or(|n| n == state.config.graph.implementers)
5099        },
5100        |replacement| {
5101            state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
5102                && state.config.graph.implementers == 1
5103        },
5104    )
5105}
5106
5107/// Never resume or take over candidate work built for a different seat count.
5108fn starter_with_implementers(
5109    task: &Task,
5110    previous: Option<&RunState>,
5111    proposed: Starter,
5112) -> Starter {
5113    if previous.is_some_and(|s| !implementers_match(task, s)) {
5114        task.review_of
5115            .as_ref()
5116            .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
5117    } else {
5118        proposed
5119    }
5120}
5121
5122/// Apply this task's explicit count to the new attempt, without changing defaults.
5123fn apply_task_implementers(config: &mut Config, task: &Task) {
5124    if let Some(n) = task.implementers() {
5125        config.graph.implementers = n;
5126    }
5127}
5128
5129/// [`prepare`] for one task: its own `--config` and command-line overrides
5130/// (`Task::overrides`, filed by `magi run` / `magi review`) take precedence
5131/// over the loop's, so handing a hand-started task to a daemon changes nothing
5132/// about what it does.
5133#[cfg(test)]
5134fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
5135    let explicit = match &task.overrides {
5136        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
5137        _ => opts.config.as_deref(),
5138    };
5139    let (mut config, _) = Config::discover(repo, explicit)?;
5140    apply_options(&mut config, opts, task)?;
5141    Ok(config)
5142}
5143
5144fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
5145    if task
5146        .overrides
5147        .as_ref()
5148        .is_none_or(|o| o.inherit_daemon_options)
5149        && let Some(mode) = opts.merge.as_deref()
5150    {
5151        config.merge.mode = merge_mode(mode)?;
5152    }
5153    if let Some(o) = &task.overrides {
5154        o.apply(config);
5155    }
5156    Ok(())
5157}
5158
5159/// Load the config for a task's repository, with the merge override applied.
5160fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
5161    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
5162    if let Some(mode) = &opts.merge {
5163        config.merge.mode = merge_mode(mode)?;
5164    }
5165    Ok(config)
5166}
5167
5168/// Prune the shared build cache at a between-runs boundary. The detached cache
5169/// service checks authoritative task jobs first; dispatch waits for that finite
5170/// service, so scheduler replacement cannot turn a compile into idle cleanup.
5171/// Its durable service cadence preserves [`CACHE_CHECK_INTERVAL_SECS`].
5172async fn maybe_prune_cache_between_runs(
5173    repo: &Path,
5174    opts: &Opts,
5175    home: &Path,
5176    stop: &Stop,
5177    last_checked: &mut Option<Timestamp>,
5178    now: Timestamp,
5179) {
5180    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
5181        return;
5182    }
5183    *last_checked = Some(now);
5184    let cfg = match prepare(repo, opts) {
5185        Ok(cfg) => cfg,
5186        Err(e) => {
5187            tracing::warn!("cache check: no config: {e:#}");
5188            return;
5189        }
5190    };
5191    match clean::prune_cache_if_over_limit(&cfg, home) {
5192        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
5193            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
5194            pruned.files,
5195            pruned.freed
5196        ),
5197        Ok(_) => {}
5198        Err(e) => {
5199            tracing::warn!("housekeep: prune cache: {e:#}");
5200            notices::raise_in(
5201                home,
5202                Notice::warn(
5203                    "housekeep:cache",
5204                    format!(
5205                        "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
5206                        e.to_string()
5207                            .lines()
5208                            .next()
5209                            .unwrap_or("unknown cleanup error")
5210                    ),
5211                ),
5212            );
5213        }
5214    }
5215}
5216
5217/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
5218/// now, given when it last did (if ever). Pure, so the cadence is asserted
5219/// directly rather than by waiting out real minutes in a test.
5220fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
5221    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
5222}
5223
5224/// The disk janitor, with its housekeeping logged rather than fatal.
5225///
5226/// Called only at the loop's idle points, for the reason the caller documents:
5227/// a prune racing a live compile would delete files mid-build. The config is
5228/// re-read on every call because the repository that just ran may not be the
5229/// daemon's own default, and the cache directory is a repository fact.
5230///
5231/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
5232/// and [`crate::run::default_worktree_root`] read here, for the same reason
5233/// [`drive`] takes its queue and status file rather than resolving them: a
5234/// test driving the loop must not reach through to the operator's real home
5235/// or worktree bay just because the janitor runs on every idle tick.
5236/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
5237/// to get wrong silently - a test's `home` was already isolated, but nothing
5238/// exercised the parameter next to it, so a real worktree bay stayed wired in
5239/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
5240/// it for real, every test in this file that drives the loop at all started
5241/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
5242async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
5243    let cfg = match prepare(repo, opts) {
5244        Ok(cfg) => cfg,
5245        Err(e) => {
5246            tracing::warn!("housekeep: no config: {e:#}");
5247            return;
5248        }
5249    };
5250    // A run's own worktree lives under `config.graph.worktree_root` when the
5251    // repository sets one - the same precedence `RunState::worktree_root`
5252    // uses - and `worktrees_root` only stands in for the *default* an
5253    // unconfigured repository resolves to (see this function's own
5254    // parameter, or the test fixture wiring one to a fake path). Housekeeping
5255    // that always swept the default regardless of this override would never
5256    // see, and so never reclaim, a single worktree for a repository that
5257    // relocated them elsewhere.
5258    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
5259    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
5260    // Reported whenever there is anything to say, not only when `folded > 0`:
5261    // the incident this exists to prevent was 90 of 93 runs skipped and 0
5262    // folded, on every single pass, for months - a report gated on `folded`
5263    // would have stayed silent through every one of them.
5264    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
5265        let mut extra = Vec::new();
5266        if out.unreadable > 0 {
5267            extra.push(format!("{} unreadable", out.unreadable));
5268        }
5269        if out.orphaned_worktrees > 0 {
5270            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
5271        }
5272        let detail = if extra.is_empty() {
5273            String::new()
5274        } else {
5275            format!(" ({})", extra.join(", "))
5276        };
5277        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
5278    }
5279    if out.external_merges_recorded > 0 {
5280        tracing::info!(
5281            "housekeep: recorded {} run(s) as merged externally",
5282            out.external_merges_recorded
5283        );
5284    }
5285    if out.stale_pr_states_repaired > 0 {
5286        tracing::info!(
5287            "housekeep: rewrote {} run record(s) whose pull request had already settled",
5288            out.stale_pr_states_repaired
5289        );
5290    }
5291    if out.cache_files > 0 {
5292        tracing::info!(
5293            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
5294            out.cache_files,
5295            out.cache_freed
5296        );
5297    }
5298    if out.questions_abandoned > 0 {
5299        tracing::info!(
5300            "housekeep: abandoned {} question(s) left open by a finished run",
5301            out.questions_abandoned
5302        );
5303    }
5304}
5305
5306/// Run [`triage::run_once`] and log whatever it did, the same "only when
5307/// there is something to say" rule [`janitor`] follows for its own report.
5308///
5309/// Called at the same idle points as [`janitor`] - once per full poll
5310/// interval, never mid-attempt - for the same reason: it is not liveness
5311/// critical, and a task's own `hold_reason` string is the one thing this
5312/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
5313/// tick for no benefit.
5314async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
5315    let questions = Questions::at(home.join("questions"));
5316    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
5317    if report.is_empty() {
5318        return;
5319    }
5320    if !report.quarantined.is_empty() {
5321        tracing::info!(
5322            "triage: held {} blocked task(s) whose blocked-on task or \
5323             question no longer exists: {}",
5324            report.quarantined.len(),
5325            report.quarantined.join(", ")
5326        );
5327    }
5328    if !report.resumed.is_empty() {
5329        tracing::info!(
5330            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
5331            report.resumed.len(),
5332            report.resumed.join(", ")
5333        );
5334    }
5335    if !report.asked.is_empty() {
5336        tracing::info!(
5337            "triage: asked about {} held task(s): {}",
5338            report.asked.len(),
5339            report.asked.join(", ")
5340        );
5341    }
5342    if !report.answered.is_empty() {
5343        tracing::info!(
5344            "triage: applied {} operator answer(s): {}",
5345            report.answered.len(),
5346            report.answered.join(", ")
5347        );
5348    }
5349}
5350
5351/// The free-space gate: what stands between this task and a new run, if
5352/// anything. `Some(reason)` holds the task; `None` lets it start.
5353///
5354/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
5355/// the operator opted out. A measurement failure is a gate, not a pass: both
5356/// sides of "cannot tell" are served by not starting.
5357pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
5358    disk_gate_with(repo, config, crate::disk::free_bytes)
5359}
5360
5361/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
5362/// test can assert the exact wiring `attempt` runs - config's threshold in,
5363/// task-holding reason out - without asking the real machine's disk anything.
5364fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
5365    repo: &Path,
5366    config: &Config,
5367    free_bytes: F,
5368) -> Option<String> {
5369    let min = config.disk.min_free_bytes;
5370    if min == 0 {
5371        return None;
5372    }
5373    let mut paths = vec![repo.to_owned()];
5374    if let Some(cache) = config.cache_dir() {
5375        paths.push(cache);
5376    }
5377    if let Some(root) = &config.graph.worktree_root {
5378        paths.push(root.clone());
5379    }
5380    for path in paths {
5381        let probe = if path == repo {
5382            path.as_path()
5383        } else {
5384            path.ancestors().find(|p| p.exists()).unwrap_or(&path)
5385        };
5386        let reason = match free_bytes(probe) {
5387            Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
5388            Err(e) => Some(crate::disk::unmeasured_in(
5389                probe,
5390                &e,
5391                &config.graph.language,
5392            )),
5393        };
5394        if reason.is_some() {
5395            return reason;
5396        }
5397    }
5398    None
5399}
5400
5401/// How long to wait before offering another task when a run lost a seat to a
5402/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
5403/// could read, or carried nothing at all. Long enough that a quota outage
5404/// cannot burn through a whole backlog in the few seconds each doomed attempt
5405/// takes to fail; short enough that a quota which clears early is not left
5406/// idle for the fallback's sake.
5407const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
5408
5409/// Longest a parsed reset hint may push the wait out to. The hint comes from
5410/// the CLI's own words, not a contract, so a parsing slip that lands a day
5411/// away must not leave the loop asleep for a day.
5412const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
5413
5414/// How long [`poll`] should wait before offering the next task, after a run
5415/// lost at least one seat to a rate limit.
5416///
5417/// Pure and separate from the loop so the policy can be exercised without a
5418/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
5419/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
5420/// nothing to parse, or the parsed time has already passed; `cap` bounds how
5421/// far a parsed hint is trusted to push the wait out.
5422fn quota_wait(
5423    reset_at: Option<Timestamp>,
5424    now: Timestamp,
5425    fallback: Duration,
5426    cap: Duration,
5427) -> Duration {
5428    match reset_at {
5429        Some(at) if at > now => {
5430            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
5431            Duration::from_secs(secs).min(cap)
5432        }
5433        _ => fallback,
5434    }
5435}
5436
5437/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
5438///
5439/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
5440/// explains why parsing it exactly "would be a bug factory" — so this only
5441/// recognises the shapes actually observed in the wild, and returns `None`
5442/// for anything else rather than guess at a format nobody has seen.
5443///
5444/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
5445/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
5446/// said it, not from whenever this loop happens to read it: anchoring on `now`
5447/// would push the reset later on every read and would read an already-elapsed
5448/// reset as still in the future. (A long hint is still clamped by
5449/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
5450fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
5451    parse_reset_hint_zoned(text, now)
5452        .or_else(|| parse_reset_hint_dated(text))
5453        .or_else(|| parse_reset_hint_relative(text, recorded))
5454}
5455
5456/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
5457/// optional but at least one required, in that order. A bare number or any
5458/// unknown unit is refused.
5459fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
5460    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
5461    let mut rest = rest.trim();
5462    if rest.is_empty() {
5463        return None;
5464    }
5465    let mut total: i64 = 0;
5466    let mut matched = false;
5467    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
5468        if let Some((digits, tail)) = rest.split_once(unit)
5469            && !digits.is_empty()
5470            && digits.bytes().all(|b| b.is_ascii_digit())
5471        {
5472            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
5473            rest = tail;
5474            matched = true;
5475        }
5476    }
5477    if !rest.is_empty() || !matched {
5478        return None;
5479    }
5480    recorded
5481        .checked_add(jiff::SignedDuration::from_secs(total))
5482        .ok()
5483}
5484
5485/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
5486/// case-insensitive) into a 24-hour hour and minute. Shared by every
5487/// reset-hint shape below.
5488fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
5489    let clock = clock.trim().to_lowercase();
5490    let (digits, pm) = clock
5491        .strip_suffix("am")
5492        .map(|d| (d, false))
5493        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
5494    let (h, m) = digits.trim().split_once(':')?;
5495    let mut hour: i8 = h.trim().parse().ok()?;
5496    let minute: i8 = m.trim().parse().ok()?;
5497    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
5498        return None;
5499    }
5500    if pm && hour != 12 {
5501        hour += 12;
5502    } else if !pm && hour == 12 {
5503        hour = 0;
5504    }
5505    Some((hour, minute))
5506}
5507
5508/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
5509/// and a zone, never a date. A clock reading already past today is read as
5510/// tomorrow's: a CLI naming a same-day reset that has already gone by means
5511/// the window rolled over while nothing was watching.
5512fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
5513    let open = text.find('(')?;
5514    let close = text.rfind(')')?;
5515    if close <= open {
5516        return None;
5517    }
5518    let zone = text[open + 1..close].trim();
5519    let (hour, minute) = parse_12h_clock(&text[..open])?;
5520    let tz = jiff::tz::TimeZone::get(zone).ok()?;
5521    let candidate = now
5522        .to_zoned(tz)
5523        .with()
5524        .hour(hour)
5525        .minute(minute)
5526        .second(0)
5527        .millisecond(0)
5528        .microsecond(0)
5529        .nanosecond(0)
5530        .build()
5531        .ok()?;
5532    let mut at = candidate.timestamp();
5533    if at <= now {
5534        at += jiff::SignedDuration::from_hours(24);
5535    }
5536    Some(at)
5537}
5538
5539/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
5540/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
5541/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
5542/// "already past today" correction to make: the year already disambiguates
5543/// it. Scanned as a five-word window so it can be pulled out of the middle
5544/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
5545/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
5546/// any other timestamp with no zone attached.
5547fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
5548    let words: Vec<&str> = text.split_whitespace().collect();
5549    if words.len() < 5 {
5550        return None;
5551    }
5552    (0..=words.len() - 5)
5553        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
5554}
5555
5556/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
5557/// parenthesis right after the window is refused rather than ignored — it
5558/// reads as an explicit zone annotation on a shape that otherwise carries
5559/// none, and guessing UTC anyway would be exactly the silent misread this
5560/// module's parsing otherwise avoids.
5561fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
5562    if trailing.is_some_and(|next| next.starts_with('(')) {
5563        return None;
5564    }
5565    let month = month_number(window[0])?;
5566    let day_token = window[1].strip_suffix(',')?.to_lowercase();
5567    let day_digits = ["st", "nd", "rd", "th"]
5568        .iter()
5569        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
5570    let day: i8 = day_digits.parse().ok()?;
5571    let year_token = window[2];
5572    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
5573        return None;
5574    }
5575    let year: i16 = year_token.parse().ok()?;
5576    // The am/pm word carries the sentence's own trailing punctuation, e.g.
5577    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
5578    // reusing the same 12-hour clock reader the bracketed shape uses.
5579    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
5580    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
5581    let date = jiff::civil::Date::new(year, month, day).ok()?;
5582    let candidate = date
5583        .at(hour, minute, 0, 0)
5584        .to_zoned(jiff::tz::TimeZone::UTC)
5585        .ok()?;
5586    Some(candidate.timestamp())
5587}
5588
5589/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
5590/// case-insensitively, into a 1-based month number.
5591fn month_number(name: &str) -> Option<i8> {
5592    const NAMES: [&str; 12] = [
5593        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
5594    ];
5595    let lower = name.to_lowercase();
5596    NAMES
5597        .iter()
5598        .position(|n| *n == lower.as_str())
5599        .map(|i| i as i8 + 1)
5600}
5601
5602/// Test probe for the shared resume policy's review-budget exclusion.
5603#[cfg(test)]
5604fn exhausted_review_budget(state: &RunState) -> bool {
5605    // A run whose task-head publication failed has nothing left to review:
5606    // resuming it only retries the publication, so it is never "exhausted".
5607    !crate::handover::can_resume(state)
5608        && state.status == RunStatus::Blocked
5609        && !state.released()
5610        && state.retired_to.is_none()
5611}
5612
5613/// This task's *most recent* run, if resuming it would actually make
5614/// progress. `short` is only for the warning's own message.
5615///
5616/// Only ever `runs.last()` — never a search back through older history.
5617/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
5618/// mint, oldest first, and every entry before the last one was already
5619/// superseded at the moment it was minted: the daemon only ever starts a new
5620/// run when the previous one was not worth resuming (unresumable, exhausted,
5621/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
5622/// opens a fresh review-only run alongside an older, already-failed
5623/// competition. Searching further back would let an old run that merely
5624/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
5625/// behind, say — get resumed instead of the fresh competition
5626/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
5627/// nothing asked to revisit.
5628///
5629/// Two runs paid for the "prefer resuming over restarting" half of this
5630/// lesson, which is why this still checks `runs.last()` rather than always
5631/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
5632/// task a moment later, duplicating two and a half hours of agent work. Then
5633/// b25f stalled on a judge that timed out and one that answered with no JSON
5634/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
5635/// **one second** later, buying three fresh implementations to reach the
5636/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
5637/// the second case: a stall is terminal, and its cheap recovery re-asks only
5638/// the absent seats. [`crate::handover::can_resume`] supplies the other half: a run
5639/// that is technically `resumable()` but provably cannot progress must not
5640/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
5641/// no-op instead of the fresh competition it promises.
5642///
5643/// A load failure is warned about rather than silently read as "not
5644/// resumable": the alternative is exactly what let a schema mismatch on run
5645/// `eba2` fall through to a full re-competition with nobody told why.
5646/// `crate::conduct` is what actually offers a better answer than
5647/// `Runner::start` here (see `Recovery::Review`), once this task's next
5648/// failure shows it up as `held`/`failed` with the run state unreadable.
5649fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
5650    unfinished_run_with(runs, short, RunState::load)
5651}
5652
5653/// [`unfinished_run`] with an injected state reader. Tests provide their
5654/// fixtures directly rather than touching the process-global run home.
5655pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
5656where
5657    F: FnMut(&str) -> Result<RunState>,
5658{
5659    let mut id = runs.last()?.clone();
5660    let mut visited = std::collections::BTreeSet::new();
5661    let mut repo = None;
5662    loop {
5663        if !runs.contains(&id) || !visited.insert(id.clone()) {
5664            tracing::warn!("invalid or cyclic recovery authority for task {short}");
5665            return None;
5666        }
5667        let state = match load(&id) {
5668            Ok(state) if state.id == id => state,
5669            Ok(_) => return None,
5670            Err(e) => {
5671                tracing::warn!("could not read run {id} for task {short}: {e:#}");
5672                return None;
5673            }
5674        };
5675        if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
5676            return None;
5677        }
5678        repo = Some(state.repo.clone());
5679        if let Some(authority) = state.retired_to {
5680            id = authority;
5681            continue;
5682        }
5683        return (crate::handover::can_resume(&state)
5684            && state.liveness(false) != crate::run::Liveness::Live)
5685            .then_some(id);
5686    }
5687}
5688
5689/// Is `task` a parked (or, from an older build, failed) task whose last run was parked at a node boundary, so
5690/// that [`attempt`] will resume it on its own?
5691///
5692/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
5693/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
5694/// injected reader like its sibling. An unreadable run is not awaiting
5695/// anything: it keeps going to the conductor as before.
5696fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
5697where
5698    F: FnOnce(&str) -> Result<RunState>,
5699{
5700    // `Failed` stays: a record an older build wrote for a parked run.
5701    if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
5702        || task.fresh_start
5703        || task.review_branch.is_some()
5704    {
5705        return false;
5706    }
5707    let Some(id) = task.runs.last() else {
5708        return false;
5709    };
5710    load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
5711}
5712
5713/// Which of the three ways [`attempt`] can mint or continue a run this task
5714/// should use.
5715#[derive(Debug, Clone, PartialEq, Eq)]
5716enum Starter {
5717    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
5718    /// and that still exists.
5719    Review(String),
5720    /// `crate::graph::Runner::resume` on an unfinished run of this task.
5721    Resume(String),
5722    /// `crate::graph::Runner::start`: a fresh competition.
5723    Start,
5724}
5725
5726/// A second bound independent of inputs and the resettable failure counter.
5727/// Count recovery records, not history entries: resuming appends the same id.
5728/// Unknown history is not evidence that a new set of worktrees is affordable.
5729fn retained_attempt_hold(
5730    task: &Task,
5731    starter: &Starter,
5732    limit: usize,
5733    mut load: impl FnMut(&str) -> Result<RunState>,
5734) -> Option<String> {
5735    if limit == 0 || matches!(starter, Starter::Resume(_)) {
5736        return None;
5737    }
5738    let mut retained = 0;
5739    for id in task.runs.iter().collect::<std::collections::BTreeSet<_>>() {
5740        let state = match load(id) {
5741            Ok(state) if state.id == *id => state,
5742            _ => {
5743                return Some(format!(
5744                    "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
5745                ));
5746            }
5747        };
5748        if state.retired_to.is_some() || state.released() {
5749            continue;
5750        }
5751        // Neither a completed status nor an empty candidate array proves that
5752        // all recovery sources (including unrecorded preparation) were retired.
5753        retained += 1;
5754    }
5755    (retained >= limit).then(|| format!(
5756        "[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."
5757    ))
5758}
5759
5760/// A selected public implementation overrides every historical candidate and pin.
5761fn selected_starter(
5762    selected: &crate::pr_recovery::Selection,
5763    previous: Option<&RunState>,
5764    unfinished: Option<&str>,
5765) -> Starter {
5766    if let Some(id) = unfinished
5767        && previous.is_some_and(|r| {
5768            r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
5769        })
5770    {
5771        Starter::Resume(id.to_owned())
5772    } else {
5773        Starter::Review(selected.branch.clone())
5774    }
5775}
5776
5777/// The owner's answer to this branch's divergence question, consumed from the
5778/// task so a later, different divergence asks again. The runner applies it
5779/// (see `Runner::review_taking_over`), after the earlier worktree is released.
5780fn take_divergence_answer(
5781    branch: &str,
5782    remote: &str,
5783    task: &mut Task,
5784) -> Option<crate::reconcile::Choice> {
5785    let summary = crate::reconcile::summary_for(branch, remote);
5786    let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
5787        (a.question == summary)
5788            .then(|| crate::reconcile::Choice::from_answer(&a.answer))
5789            .flatten()
5790            .map(|c| (i, c))
5791    })?;
5792    task.answers.remove(idx);
5793    Some(choice)
5794}
5795
5796/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
5797/// this attempt should use. Pure, and separate from [`attempt`], so the
5798/// routing itself is assertable without spawning a real graph or a git
5799/// process: `attempt`'s own `crate::git::branch_exists` call has already
5800/// happened by the time this is called.
5801///
5802/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
5803/// whose branch is gone falls all the way through to [`Starter::Start`], not
5804/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
5805/// old (likely `Blocked`) run in the first place, and a branch that vanished
5806/// out from under that choice is not evidence resuming it would fare better.
5807fn choose_starter(
5808    review_branch: Option<&str>,
5809    branch_exists: bool,
5810    unfinished: Option<&str>,
5811) -> Starter {
5812    match review_branch {
5813        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
5814        Some(_) => Starter::Start,
5815        None => match unfinished {
5816            Some(id) => Starter::Resume(id.to_owned()),
5817            None => Starter::Start,
5818        },
5819    }
5820}
5821
5822/// Reuse a compatible latest review owner instead of taking its checked-out
5823/// branch into a new run. Different branches and changed criteria still use
5824/// the ordinary review/takeover policy.
5825fn review_retry_starter(
5826    task: &Task,
5827    previous: Option<&RunState>,
5828    branch: Option<&str>,
5829    exists: bool,
5830    unfinished: Option<&str>,
5831) -> Starter {
5832    if let Some(run) = previous
5833        && unfinished == Some(run.id.as_str())
5834        && run.reviewed_commits.is_some()
5835        && branch.is_some_and(|branch| {
5836            exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
5837        })
5838        && may_resume_run(run, task)
5839    {
5840        return Starter::Resume(run.id.clone());
5841    }
5842    match (branch, unfinished, &task.review_of) {
5843        (None, None, Some(branch)) => Starter::Review(branch.clone()),
5844        _ => choose_starter(branch, exists, unfinished),
5845    }
5846}
5847
5848/// Consume a retained review only while its authored criteria still match.
5849fn take_review_branch(task: &mut Task, previous: Option<&RunState>) -> Option<String> {
5850    let branch = task.review_branch.take();
5851    let instruction = task.review_instruction.take();
5852    branch.filter(|branch| match &instruction {
5853        Some(authored) => *authored == task.instruction,
5854        // Legacy retained branches must agree with their prior run; only an
5855        // explicitly pinned review can proceed without recoverable provenance.
5856        None => previous.map_or_else(
5857            || task.review_of.as_ref() == Some(branch),
5858            |run| compatible_run_instruction(run, task),
5859        ),
5860    })
5861}
5862
5863/// A current explicit pin can select an otherwise incompatible run. Edits
5864/// and subsequent approvals invalidate pins selected for earlier criteria.
5865fn may_resume_run(run: &RunState, task: &Task) -> bool {
5866    task.resume_override
5867        .as_ref()
5868        .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
5869        || compatible_run_instruction(run, task)
5870}
5871
5872/// Review scaffolding is execution context, not evidence of an operator edit.
5873pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
5874    if let Some(authored) = &run.task_instruction {
5875        return compatible_instruction(authored, task);
5876    }
5877    if compatible_instruction(&run.instruction, task) {
5878        return true;
5879    }
5880    // Recognize only the existing generated review shapes on legacy runs.
5881    // Ordinary authored text with a similar heading is left intact.
5882    if run.reviewed_commits.is_some() {
5883        if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
5884            return strip_answers_block(authored, task).trim() == task.instruction.trim();
5885        }
5886        if let Some(branch) = &task.review_of {
5887            let canonical = format!(
5888                "Review the branch `{branch}` (review-only: no implementation, no judging)."
5889            );
5890            let generated = format!(
5891                "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"
5892            );
5893            return task.instruction == canonical && run.instruction.starts_with(&generated);
5894        }
5895    }
5896    false
5897}
5898
5899/// Compare authored instructions, excluding answer blocks appended by the daemon.
5900pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
5901    strip_answers_block(old, task) == task.instruction
5902}
5903
5904/// Which repository a task runs in. A task that names none — the normal case
5905/// for one filed from a phone — runs in the daemon's own default.
5906fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
5907    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
5908        return fallback.to_path_buf();
5909    }
5910    task.repo.clone()
5911}
5912
5913/// The header [`append_answers`] appends operator answers under. Shared with
5914/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
5915/// rather than grown a new block on every resume.
5916const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
5917
5918/// Render the first `count` answers in the block appended to an instruction.
5919fn answers_block(task: &Task, count: usize) -> String {
5920    let mut s = ANSWERS_HEADER.to_owned();
5921    for a in &task.answers[..count] {
5922        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
5923    }
5924    s
5925}
5926
5927/// Render the approval independently of transient task state, so historical
5928/// suffixes remain recognizable after another explicit release.
5929fn resumption_block(r: &crate::queue::Resumption) -> String {
5930    format!(
5931        "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
5932         Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
5933        r.generation, r.at, r.instruction, r.answers_through,
5934    )
5935}
5936
5937/// Append audit answers and the latest explicit approval to the instruction.
5938fn append_answers(base: &str, task: &Task) -> String {
5939    let mut s = base.to_owned();
5940    if !task.answers.is_empty() {
5941        s.push_str(&answers_block(task, task.answers.len()));
5942    }
5943    if let Some(r) = &task.resumption {
5944        s.push_str(&resumption_block(r));
5945    }
5946    s
5947}
5948
5949/// Drop the prior answer block only when it is exactly the suffix this task
5950/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
5951/// the task author is ordinary instruction text, not a block to remove.
5952fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
5953    let mut instruction = instruction;
5954    for approval in task
5955        .resumption
5956        .iter()
5957        .chain(task.resumption_history.iter().rev())
5958    {
5959        if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
5960            instruction = base;
5961            break;
5962        }
5963    }
5964    for count in (1..=task.answers.len()).rev() {
5965        let block = answers_block(task, count);
5966        if let Some(base) = instruction.strip_suffix(&block) {
5967            return base;
5968        }
5969    }
5970    instruction
5971}
5972
5973/// The instruction handed to `Runner::start`: the task's own text, plus any
5974/// operator answers `crate::conduct` collected for it (see
5975/// [`Task::answers`]), so a decision the operator actually made reaches the
5976/// implementers rather than only clearing the block that was waiting on it.
5977///
5978/// Appended rather than merged into [`Task::instruction`] itself, so the
5979/// task's own record stays exactly what its author wrote.
5980fn instruction_for(task: &Task) -> String {
5981    append_answers(&task.instruction, task)
5982}
5983
5984/// The instruction a resumed run should carry on with: whatever it already
5985/// had, refreshed with the task's *current* operator answers.
5986///
5987/// A resumable run's own `RunState::instruction` predates any answer
5988/// `crate::conduct` collects after the run parks, so resuming it unchanged —
5989/// the behaviour before this function existed — silently drops the very
5990/// decision the operator made to unblock it. Re-stripping any block this
5991/// function appended on an earlier resume before re-appending the current
5992/// list (rather than blindly appending again) is what keeps a task resumed
5993/// three times over three answered questions from carrying the same answer
5994/// three times.
5995fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
5996    append_answers(strip_answers_block(old_instruction, task), task)
5997}
5998
5999/// Preserve the producer's verified boundary and target, independent of prose.
6000fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
6001    let failure = error.downcast_ref::<crate::config::ConfigFailure>();
6002    task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
6003    if let Some(cause) = task.hold_notice_cause.as_mut() {
6004        cause.target = failure.map(|f| f.target.clone());
6005    }
6006}
6007
6008#[derive(Debug, thiserror::Error)]
6009#[error("attachment `{name}` is recorded on the task but {path} is missing")]
6010struct MissingAttachment {
6011    name: String,
6012    path: PathBuf,
6013}
6014
6015/// The task's attachments as absolute paths, each checked to still exist.
6016fn task_attachments(
6017    queue: &Queue,
6018    task: &Task,
6019) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
6020    let paths = queue.attachment_paths(task);
6021    for (name, path) in task.attachments.iter().zip(&paths) {
6022        if !path.is_file() {
6023            return Err(MissingAttachment {
6024                name: name.clone(),
6025                path: path.clone(),
6026            });
6027        }
6028    }
6029    Ok(paths)
6030}
6031
6032/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
6033/// answers before handing it to `Runner` — the actual boundary between
6034/// [`choose_starter`]'s routing and the graph, factored out so it is
6035/// assertable without a real repository, git branch, or agent CLI.
6036///
6037/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
6038/// instruction from the reviewed branch's own commit log because there is no
6039/// task statement to speak of for hand-written work, and splicing operator
6040/// answers into that text would contradict the very message it sends
6041/// reviewers ("there is no task statement").
6042fn prepare_instruction(
6043    starter: &Starter,
6044    old_instruction: Option<&str>,
6045    task: &Task,
6046) -> Option<String> {
6047    match starter {
6048        Starter::Start => Some(instruction_for(task)),
6049        Starter::Resume(_) => Some(resumed_instruction(
6050            old_instruction.expect("a resumed run always has a prior instruction"),
6051            task,
6052        )),
6053        Starter::Review(_) => None,
6054    }
6055}
6056
6057/// Persist a transition. A queue write failure is logged rather than fatal: the
6058/// run already happened, and taking the daemon down would only add a lost
6059/// backlog to a full disk.
6060fn record(queue: &Queue, task: &mut Task) {
6061    if let Err(e) = queue.put(task) {
6062        tracing::error!("could not record task {}: {e:#}", task.short());
6063        let notice = Notice::error(
6064            "loop:record",
6065            format!(
6066                "Task {} state could not be saved: {}. Check the disk.",
6067                task.id,
6068                e.to_string().lines().next().unwrap_or("unknown save error")
6069            ),
6070        )
6071        .link(Link::Task {
6072            id: task.id.clone(),
6073        });
6074        // The queue lives at `<home>/queue`, so its parent is the home.
6075        match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
6076            Some(home) => notices::raise_in(home, notice),
6077            None => notices::raise(notice),
6078        }
6079    }
6080}
6081
6082/// Every runnable task, in the order the loop should try them.
6083///
6084/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
6085/// tail exists so that a claim somebody else holds costs the loop the next
6086/// candidate rather than a whole poll interval of idleness.
6087fn runnable(queue: &Queue) -> Vec<Task> {
6088    let mut tasks: Vec<Task> = queue
6089        .list()
6090        .into_iter()
6091        .filter(|t| t.status.runnable())
6092        .collect();
6093    tasks.sort_unstable_by(crate::queue::dispatch_order);
6094    tasks
6095}
6096
6097/// Why a run ended where it did, in one line, for [`Task::last_error`].
6098///
6099/// A stalled run names the seats the quota took out: "out of quota" is not
6100/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
6101/// agent to replace or which plan to top up.
6102///
6103/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
6104/// purpose: unlike `label`'s other callers (an internal log line, an
6105/// already-a-bug fallback message), this string becomes `Task::last_error`
6106/// verbatim, which the phone renders in the same alarm-styled box an
6107/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
6108/// `.err` styling. A bare `verified_noop` there would read exactly like the
6109/// failure this whole feature exists to tell apart from one.
6110fn describe(state: &RunState) -> String {
6111    let p = phrases(&state.config.graph.language);
6112    let mut detail = if state.status == RunStatus::Stalled {
6113        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
6114        seats.sort_unstable();
6115        seats.dedup();
6116        if seats.is_empty() {
6117            p.quorum_lost.to_owned()
6118        } else {
6119            format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
6120        }
6121    } else {
6122        format!("{}{}", p.run_ended, state.status.display_label())
6123    };
6124    if let Some(cause) = state.verification_blocking_cause() {
6125        detail.push_str(&format!(" ({cause})"));
6126    } else if let Some(last) = state.events.last() {
6127        // The review loop's "never answered" stop is the one event worth
6128        // translating; it is recognised from structured state, not by
6129        // matching the English event text (which stays as recorded).
6130        let unanswered = state
6131            .reviews
6132            .last()
6133            .filter(|r| {
6134                state.status == RunStatus::Blocked
6135                    && last.node == "review"
6136                    && r.incomplete()
6137                    && r.blocking == 0
6138                    && r.round == state.config.graph.review_rounds
6139                    && r.e2e.iter().all(crate::run::CommandOutcome::ok)
6140            })
6141            .map(|r| (r.expected - r.answered, r.round));
6142        match unanswered {
6143            Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
6144                detail.push_str(&format!(
6145                    " ({}: {})",
6146                    last.node,
6147                    (p.reviewers_never_answered)(missing, rounds)
6148                ));
6149            }
6150            _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
6151        }
6152    }
6153    detail.push_str(&format!(" [run {}]", state.id));
6154    detail
6155}
6156
6157/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
6158///
6159/// The task file lives in the backlog indefinitely; a diagnostic is an
6160/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
6161/// stay small regardless of how much a gate command or a candidate printed.
6162const DIAGNOSTIC_MAX: usize = 4_000;
6163
6164/// Tail kept from a single failing command's output inside a diagnostic.
6165/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
6166/// pointer for a human deciding whether to go read the full artifact by hand,
6167/// not a replacement for reading it.
6168const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
6169
6170/// Assemble a bounded diagnostic excerpt from a held task's own run, so
6171/// `magi task show` says more than the one-line reason in [`describe`].
6172///
6173/// The one-liner answers "where did the run stop"; this answers "what would a
6174/// human have found opening `artifacts/` by hand" — the point of the whole
6175/// feature is the case that one-liner actively misleads on: a run held as "no
6176/// candidate produced a change" can mean the implementer actually finished
6177/// the task (opened a PR, merged it, tagged a release) and only left a clean
6178/// local worktree behind, which reads as "nothing happened" unless someone
6179/// goes and reads what the agent actually said. `None` when the run carries
6180/// none of the three shapes this recognises — an ordinary run held for
6181/// something not diagnosable from `RunState` alone still explains itself
6182/// through `Task::last_error`.
6183fn diagnostic(state: &RunState) -> Option<String> {
6184    let mut parts: Vec<String> = Vec::new();
6185
6186    // Gate failure: which check(s), and the tail of what each printed.
6187    for o in state.gate.iter().filter(|o| !o.ok()) {
6188        parts.push(format!(
6189            "gate `{}` failed ({}):\n{}",
6190            o.command,
6191            notices::exit_status(o.code),
6192            crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
6193        ));
6194    }
6195
6196    // The land loop gave up because the fixer declined while checks were
6197    // still red: the message already names them (see `land::run`).
6198    if let Some(last) = state
6199        .events
6200        .iter()
6201        .rev()
6202        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
6203    {
6204        parts.push(last.message.clone());
6205    }
6206
6207    // No viable candidate: every implementer's own final word, sanitized the
6208    // same way a judge would have read it, so a run that actually finished
6209    // the job does not read as an unexplained failure. A verified no-op is
6210    // called out ahead of its own summary and apart from an ordinary
6211    // failure's `why` — this is the one candidate shape whose diagnostic a
6212    // human is expected to actually judge, not just skim.
6213    if state.viable().is_empty() {
6214        for c in &state.candidates {
6215            if let Some(evidence) = &c.verified_noop {
6216                parts.push(format!(
6217                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
6218                    c.label
6219                ));
6220            } else if !c.summary.trim().is_empty() {
6221                parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
6222            } else if let Some(why) = &c.failed {
6223                parts.push(format!("candidate {}: {why}", c.label));
6224            }
6225        }
6226    }
6227
6228    if parts.is_empty() {
6229        return None;
6230    }
6231    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
6232    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
6233    // back slightly over. Leave it enough room to always land under the
6234    // limit.
6235    Some(crate::run::tail(
6236        &parts.join("\n\n"),
6237        DIAGNOSTIC_MAX.saturating_sub(100),
6238    ))
6239}
6240
6241/// Stable lower-case name for a run status, for an internal log line and the
6242/// "graph stopped without reaching a terminal status" bug message in
6243/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
6244/// doc for why that one reads [`RunStatus::display_label`] instead. One
6245/// definition of a status's name, on the type that owns it: this table used
6246/// to live here as a second copy, and a status renamed in one place would
6247/// have gone on reading correctly in the other.
6248fn label(status: RunStatus) -> &'static str {
6249    status.as_str()
6250}
6251
6252/// Parse a merge mode override.
6253pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
6254    match mode {
6255        "none" => Ok(MergeMode::None),
6256        "local" => Ok(MergeMode::Local),
6257        "pr" => Ok(MergeMode::Pr),
6258        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
6259    }
6260}
6261
6262/// Take the status lock, recovering from a poisoned one.
6263///
6264/// A panic elsewhere must not silently stop the heartbeat: the status is plain
6265/// data, and the worst a poisoned lock can hold is a stale timestamp.
6266fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
6267    mutex
6268        .lock()
6269        .unwrap_or_else(std::sync::PoisonError::into_inner)
6270}
6271
6272#[cfg(test)]
6273mod tests {
6274    use super::*;
6275    use crate::queue::{Source, TaskStatus};
6276    use crate::run::{Candidate, CommandOutcome};
6277    use pretty_assertions::assert_eq;
6278
6279    fn task() -> Task {
6280        Task::new(
6281            "add retries".to_owned(),
6282            "add retries".to_owned(),
6283            PathBuf::from("/repo"),
6284            Source::Human,
6285        )
6286    }
6287
6288    fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
6289        let job = crate::worker::Job {
6290            id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
6291            sequence: 1,
6292            kind: "task".into(),
6293            key: format!("task:{}", request.task),
6294            payload: serde_json::to_value(request).unwrap(),
6295            generation: "a".repeat(64),
6296            version: None,
6297            status: crate::worker::Status::Starting,
6298            result: None,
6299            pid: None,
6300            created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
6301            finished_at: None,
6302        };
6303        let dir = home.join("workers/jobs").join(&job.id);
6304        std::fs::create_dir_all(&dir).unwrap();
6305        std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
6306        job
6307    }
6308
6309    #[test]
6310    fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
6311        let home = tempfile::tempdir().unwrap();
6312        let request = TaskWorker {
6313            opts: Opts::default(),
6314            queue: home.path().join("queue"),
6315            task: "startup".into(),
6316            lane: PermitKind::Ordinary,
6317            standalone: false,
6318        };
6319        let job = starting_task_reservation(home.path(), &request);
6320        let error = task_worker_spawn_error(
6321            home.path(),
6322            &request,
6323            anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
6324        )
6325        .expect_err("our own reservation must not turn a failed spawn into a resync");
6326        let active = crate::worker::active(home.path()).unwrap();
6327        assert_eq!(active.len(), 1);
6328        assert_eq!(active[0].id, job.id);
6329        assert_eq!(active[0].status, crate::worker::Status::Starting);
6330        assert!(
6331            crate::worker::control(home.path(), &job.key)
6332                .unwrap()
6333                .is_none()
6334        );
6335        let notices = notices::Notices::at(home.path().join("notifications")).list();
6336        assert_eq!(notices.len(), 1);
6337        assert_eq!(notices[0].key, "loop:worker-startup");
6338        assert!(!notices[0].message.contains("private-error-detail"));
6339        assert!(notices[0].message.contains(&request.task));
6340        assert!(
6341            notices[0]
6342                .message
6343                .contains("could not be started or acknowledged")
6344        );
6345        assert!(notices[0].message.contains("worker.log"));
6346        assert_eq!(
6347            notices[0].link,
6348            Some(Link::Task {
6349                id: request.task.clone()
6350            })
6351        );
6352        assert!(format!("{error:#}").contains("private-error-detail"));
6353    }
6354
6355    #[test]
6356    fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
6357        let home = tempfile::tempdir().unwrap();
6358        let mut request = TaskWorker {
6359            opts: Opts::default(),
6360            queue: home.path().join("queue"),
6361            task: "handoff".into(),
6362            lane: PermitKind::Ordinary,
6363            standalone: true,
6364        };
6365        let job = starting_task_reservation(home.path(), &request);
6366        request.standalone = false;
6367        task_worker_spawn_error(
6368            home.path(),
6369            &request,
6370            anyhow::anyhow!("operation key is already reserved for a different request"),
6371        )
6372        .expect("a different standalone request is the handoff race, not our startup failure");
6373        let active = crate::worker::active(home.path()).unwrap();
6374        assert_eq!(active.len(), 1);
6375        assert_eq!(active[0].id, job.id);
6376        assert_eq!(active[0].payload, job.payload);
6377        assert!(
6378            notices::Notices::at(home.path().join("notifications"))
6379                .list()
6380                .is_empty()
6381        );
6382    }
6383
6384    #[test]
6385    fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
6386        let home = tempfile::tempdir().unwrap();
6387        let queue = Queue::at(home.path().join("queue"));
6388        let mut task = task();
6389        task.runs = vec!["previous".into()];
6390        queue.put(&mut task).unwrap();
6391        let request = TaskWorker {
6392            opts: Opts::default(),
6393            queue: home.path().join("queue"),
6394            task: task.id.clone(),
6395            lane: PermitKind::Ordinary,
6396            standalone: false,
6397        };
6398        let job = starting_task_reservation(home.path(), &request);
6399        let claims = current_work(home.path(), Timestamp::now());
6400        assert_eq!(claims.len(), 1);
6401        assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
6402        assert_eq!(claims[0].run, "previous");
6403        assert!(other_claims_run(&claims, "previous", None));
6404        // Only after confirming the executing caller may admission ignore
6405        // this exact projection. Cleanup continues to observe it as live.
6406        assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
6407        assert!(is_working_on(home.path(), "previous", Timestamp::now()));
6408    }
6409
6410    #[test]
6411    fn admission_excludes_only_the_callers_exact_reservation() {
6412        let own = Current {
6413            worker: Some("own".into()),
6414            task: "same-task".into(),
6415            run: "previous".into(),
6416        };
6417        assert!(!other_claims_run(
6418            std::slice::from_ref(&own),
6419            "previous",
6420            Some("own")
6421        ));
6422        assert!(other_claims_run(
6423            std::slice::from_ref(&own),
6424            "previous",
6425            None
6426        ));
6427        for worker in [None, Some("other".into())] {
6428            let other = Current {
6429                worker,
6430                ..own.clone()
6431            };
6432            assert!(other_claims_run(
6433                &[own.clone(), other],
6434                "previous",
6435                Some("own")
6436            ));
6437        }
6438        let legacy: Current =
6439            serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
6440        assert!(other_claims_run(&[legacy], "previous", Some("own")));
6441    }
6442
6443    #[test]
6444    fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
6445        let mut task = task();
6446        let mut run = run_state(RunStatus::Reviewing);
6447        run.task_instruction = Some(task.instruction.clone());
6448        run.reviewed_commits = Some(vec!["committed-fix".into()]);
6449        let branch = "magi/test/B";
6450        run.candidates.push(crate::run::Candidate {
6451            branch: branch.into(),
6452            ..candidate('B', "preserved work", false, None)
6453        });
6454        task.runs = vec![run.id.clone()];
6455        let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
6456        assert_eq!(
6457            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
6458            Starter::Resume(run.id.clone())
6459        );
6460        assert!(matches!(
6461            review_retry_starter(
6462                &task,
6463                Some(&run),
6464                Some("different"),
6465                true,
6466                unfinished.as_deref()
6467            ),
6468            Starter::Review(_)
6469        ));
6470        assert_eq!(
6471            review_retry_starter(
6472                &task,
6473                Some(&run),
6474                Some(branch),
6475                false,
6476                unfinished.as_deref()
6477            ),
6478            Starter::Start
6479        );
6480        task.instruction.push_str(" changed criteria");
6481        assert!(matches!(
6482            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
6483            Starter::Review(_)
6484        ));
6485        assert!(matches!(
6486            review_retry_starter(&task, Some(&run), Some(branch), true, None),
6487            Starter::Review(_)
6488        ));
6489    }
6490
6491    #[test]
6492    fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
6493        let dir = tempfile::tempdir().unwrap();
6494        let queue = Queue::at(dir.path().join("queue"));
6495        let mut task = task();
6496        task.status = TaskStatus::Running;
6497        task.attempts = 1;
6498        queue.put(&mut task).unwrap();
6499        let live = std::collections::BTreeSet::from([task.id.clone()]);
6500        assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
6501        drop(queue.claim(&task.id).unwrap());
6502        let saved = queue.get(&task.id).unwrap();
6503        assert_eq!(saved.status, TaskStatus::Running);
6504        assert_eq!(saved.attempts, 1);
6505        assert!(saved.last_error.is_none());
6506    }
6507
6508    #[test]
6509    fn standalone_workers_do_not_consume_scheduler_lanes() {
6510        let request = |task: &str, lane, standalone| TaskWorker {
6511            opts: Opts::default(),
6512            queue: PathBuf::from("/queue"),
6513            task: task.to_owned(),
6514            lane,
6515            standalone,
6516        };
6517        let mut jobs = vec![
6518            request("ordinary", PermitKind::Ordinary, false),
6519            request("standalone-urgent", PermitKind::Urgent, true),
6520            request("standalone-ordinary", PermitKind::Ordinary, true),
6521            request("decision", PermitKind::None, false),
6522        ];
6523        assert_eq!(available_slots(&jobs, 2), (1, 1));
6524        jobs.push(request("urgent", PermitKind::Urgent, false));
6525        assert_eq!(available_slots(&jobs, 2), (1, 0));
6526        assert_eq!(available_slots(&jobs, 0), (0, 0));
6527    }
6528
6529    #[test]
6530    fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
6531        let now = Timestamp::now();
6532        let mut reading = Reading {
6533            pid: Some(std::process::id()),
6534            updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
6535            ..Reading::default()
6536        };
6537        assert!(!reading.running(now));
6538        assert!(legacy_scheduler_running(&reading, now, 0));
6539        reading.worker_protocol = Some(1);
6540        assert!(!legacy_scheduler_running(&reading, now, 0));
6541    }
6542
6543    #[test]
6544    fn selected_public_head_overrides_historical_resume_and_pin() {
6545        let mut t = task();
6546        let mut old = run_state(RunStatus::Blocked);
6547        let selection = crate::pr_recovery::Selection {
6548            url: "url".into(),
6549            branch: format!("magi/task-{}", t.id),
6550            head: "a".repeat(40),
6551            source_head: None,
6552            source_run: None,
6553            source_proof: None,
6554            disposition: Some(crate::pr_recovery::Disposition::Review),
6555            instruction: t.instruction.clone(),
6556            approved_at: Timestamp::now(),
6557        };
6558        t.resume_override = Some(crate::queue::OperatorResume {
6559            pinned_run: Some(old.id.clone()),
6560            question_id: "choice".into(),
6561            at: Timestamp::now(),
6562            conductor_rehold: None,
6563            forced: false,
6564        });
6565        assert_eq!(
6566            selected_starter(&selection, Some(&old), Some(&old.id)),
6567            Starter::Review(selection.branch.clone())
6568        );
6569        old.pr_recovery = Some(selection.clone());
6570        assert_eq!(
6571            selected_starter(&selection, Some(&old), Some(&old.id)),
6572            Starter::Review(selection.branch.clone())
6573        );
6574        old.reviewed_commits = Some(vec!["implementation".into()]);
6575        assert_eq!(
6576            selected_starter(&selection, Some(&old), Some(&old.id)),
6577            Starter::Resume(old.id.clone())
6578        );
6579        let mut changed = selection.clone();
6580        changed.head = "b".repeat(40);
6581        assert_eq!(
6582            selected_starter(&changed, Some(&old), Some(&old.id)),
6583            Starter::Review(changed.branch)
6584        );
6585    }
6586
6587    #[test]
6588    fn candidate_transplant_failure_is_one_actionable_hold() {
6589        let dir = tempfile::tempdir().unwrap();
6590        let q = Queue::at(dir.path().join("queue"));
6591        let mut t = task();
6592        let mut state = run_state(RunStatus::Blocked);
6593        state.event("prep", "cannot apply referenced commit: conflict");
6594        state.prep_failure = Some("conflict".into());
6595        t.start(state.id.clone());
6596        finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
6597        assert_eq!(t.attempts, 1);
6598        assert_eq!(t.status, TaskStatus::Held);
6599        assert!(t.operator_held());
6600        assert!(!t.status.runnable());
6601        assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
6602        let first = t.chat_notice_key().unwrap();
6603        t.chat_notices.push(first.clone());
6604        t.release_operator("test", None);
6605        state.id = "another-unprepared-run".into();
6606        t.start(state.id.clone());
6607        finish_attempt(
6608            3,
6609            &q,
6610            &mut t,
6611            &state,
6612            &[],
6613            Err(anyhow::anyhow!("still conflicts")),
6614        );
6615        assert_eq!(
6616            t.chat_notice_key().as_ref(),
6617            Some(&first),
6618            "no work happened"
6619        );
6620        t.release_operator("test", None);
6621        state.prep_failure = None;
6622        state.status = RunStatus::Failed;
6623        state.begin_pass();
6624        t.start(state.id.clone());
6625        finish_attempt(
6626            1,
6627            &q,
6628            &mut t,
6629            &state,
6630            &[],
6631            Err(anyhow::anyhow!("new gate failure")),
6632        );
6633        let failure = t.chat_notice_key().unwrap();
6634        assert_ne!(failure, first, "approved recovery reached a real failure");
6635        t.release_operator("test", None);
6636        state.begin_pass();
6637        t.start(state.id.clone());
6638        finish_attempt(
6639            1,
6640            &q,
6641            &mut t,
6642            &state,
6643            &[],
6644            Err(anyhow::anyhow!("new failure on resume")),
6645        );
6646        assert_ne!(
6647            t.chat_notice_key().as_ref(),
6648            Some(&failure),
6649            "a new settled pass"
6650        );
6651    }
6652
6653    #[test]
6654    fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
6655        for source in ["cli", "web"] {
6656            let mut t = task();
6657            let mut run = run_state(RunStatus::Blocked);
6658            run.instruction = "Run A original criteria".into();
6659            run.task_instruction = Some(run.instruction.clone());
6660            t.start(run.id.clone());
6661            t.release_operator("choice", Some("resume-question"));
6662            t.resume_override = Some(crate::queue::OperatorResume {
6663                question_id: "resume-question".into(),
6664                at: Timestamp::now(),
6665                conductor_rehold: None,
6666                forced: true,
6667                pinned_run: Some(run.id.clone()),
6668            });
6669            t.hold_machine(Some("not enough free space to start a run".into()));
6670            let mut unchanged = t.clone();
6671            unchanged
6672                .edit("title changed".into(), unchanged.instruction.clone())
6673                .unwrap();
6674            unchanged.release_operator(source, None);
6675            assert_eq!(
6676                unchanged
6677                    .resume_override
6678                    .as_ref()
6679                    .unwrap()
6680                    .pinned_run
6681                    .as_deref(),
6682                Some(run.id.as_str())
6683            );
6684            assert!(!compatible_run_instruction(&run, &unchanged));
6685            assert!(may_resume_run(&run, &unchanged));
6686
6687            t.edit(
6688                "approved recovery".into(),
6689                "Reuse measured PR head B; fix Clippy; review".into(),
6690            )
6691            .unwrap();
6692            assert!(t.resume_override.is_none());
6693            t.release_operator(source, None);
6694            let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
6695            assert!(reloaded.resume_override.is_none());
6696            assert!(!may_resume_run(&run, &reloaded));
6697            let unfinished =
6698                unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
6699                    .filter(|_| may_resume_run(&run, &reloaded));
6700            assert_eq!(
6701                choose_starter(None, false, unfinished.as_deref()),
6702                Starter::Start
6703            );
6704            assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
6705            assert_eq!(
6706                reloaded.resumption_history[0].question_id.as_deref(),
6707                Some("resume-question")
6708            );
6709
6710            // A revision already persisted with the old approval/pin is also
6711            // invalidated when the new operator release is recorded.
6712            unchanged.instruction = "Reuse measured PR head B".into();
6713            unchanged.hold_machine(Some("disk hold".into()));
6714            unchanged.release_operator(source, None);
6715            assert!(unchanged.resume_override.is_none());
6716            assert!(!may_resume_run(&run, &unchanged));
6717        }
6718    }
6719
6720    #[test]
6721    fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
6722        let mut t = task();
6723        let mut run = run_state(RunStatus::Blocked);
6724        t.review_of = Some("approved-head".into());
6725        t.instruction =
6726            "Review the branch `approved-head` (review-only: no implementation, no judging)."
6727                .into();
6728        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();
6729        run.reviewed_commits = Some(vec!["Commit log".into()]);
6730        t.start(run.id.clone());
6731        t.hold_machine(Some("interrupted review".into()));
6732        t.release_operator("cli", None);
6733        assert!(
6734            compatible_run_instruction(&run, &t),
6735            "legacy explicit review remains resumable"
6736        );
6737        let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
6738            .filter(|_| compatible_run_instruction(&run, &t));
6739        assert_eq!(
6740            choose_starter(None, false, unfinished.as_deref()),
6741            Starter::Resume(run.id.clone())
6742        );
6743        run.task_instruction = Some(t.instruction.clone());
6744        assert!(compatible_run_instruction(&run, &t));
6745        let reloaded: RunState =
6746            serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
6747        assert!(compatible_run_instruction(&reloaded, &t));
6748        t.edit(
6749            "new approved head".into(),
6750            "Reuse measured PR head B".into(),
6751        )
6752        .unwrap();
6753        assert!(!compatible_run_instruction(&run, &t));
6754
6755        // Legacy recovery reviews retain the task criteria ahead of the log.
6756        t.review_of = None;
6757        t.instruction = "Fix Clippy on approved head".into();
6758        run.task_instruction = None;
6759        run.instruction = format!(
6760            "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
6761            t.instruction
6762        );
6763        assert!(compatible_run_instruction(&run, &t));
6764        t.instruction.push('\n');
6765        assert!(
6766            compatible_run_instruction(&run, &t),
6767            "legacy generated review trimmed the original criteria"
6768        );
6769        t.hold_for_handover(Some("approved-head".into()), "refused".into());
6770        let mut unchanged = t.clone();
6771        assert_eq!(
6772            take_review_branch(&mut unchanged, Some(&run)).as_deref(),
6773            Some("approved-head")
6774        );
6775        t.edit("new plan".into(), "Reuse measured PR head B".into())
6776            .unwrap();
6777        assert!(take_review_branch(&mut t, Some(&run)).is_none());
6778        assert!(!compatible_run_instruction(&run, &t));
6779        t.review_branch = Some("approved-head".into());
6780        t.review_instruction = None;
6781        assert!(
6782            take_review_branch(&mut t, Some(&run)).is_none(),
6783            "legacy retained candidate cannot replace a revised approved head"
6784        );
6785    }
6786
6787    #[test]
6788    fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
6789        crate::run::pin_test_home();
6790        let dir = tempfile::tempdir().unwrap();
6791        let queue = Queue::at(dir.path().join("queue"));
6792        for resume in [true, false] {
6793            let state = run_state(RunStatus::Blocked);
6794            let mut t = task();
6795            t.start(state.id.clone());
6796            let action = if resume {
6797                ask::ChoiceAction::Resume {
6798                    run: state.id.clone(),
6799                }
6800            } else {
6801                ask::ChoiceAction::Requeue
6802            };
6803            let mut q = action_question(&state.id, action);
6804            q.status = ask::QuestionStatus::Open;
6805            q.answer = None;
6806            q.answered_at = None;
6807            t.fail("run stopped with a question", 3);
6808            hold_if_runnable(&queue, &mut t);
6809            assert!(t.operator_decided_at.is_none());
6810            assert!(t.operator_held());
6811            q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
6812            let expected = if resume {
6813                ActionDecision::Resume(state.id.clone())
6814            } else {
6815                ActionDecision::Requeue
6816            };
6817            assert_eq!(
6818                decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
6819                expected
6820            );
6821            t.hold_manual(Some("later explicit hold".into()));
6822            assert_eq!(
6823                decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
6824                ActionDecision::Stale
6825            );
6826        }
6827    }
6828
6829    #[test]
6830    fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
6831        let mut t = task();
6832        t.answers.push(crate::queue::AnsweredQuestion {
6833            question: "Inspect the remote?".into(),
6834            answer: "Inspect then wait".into(),
6835        });
6836        let old = instruction_for(&t);
6837        assert!(compatible_instruction(&old, &t));
6838        t.instruction = "Reuse approved PR head and review".into();
6839        t.release_operator("cli", None);
6840        assert!(!compatible_instruction(&old, &t));
6841        let approved = instruction_for(&t);
6842        assert!(approved.contains("waiting premises are superseded"));
6843        assert!(compatible_instruction(&approved, &t));
6844        assert_eq!(resumed_instruction(&approved, &t), approved);
6845        t.release_operator("web", None);
6846        assert!(compatible_instruction(&approved, &t));
6847        assert_eq!(t.resumption_history.len(), 1);
6848        t.start("run".into());
6849        assert!(instruction_for(&t).contains("Explicit operator resumption"));
6850    }
6851
6852    /// A run that stopped on an infrastructure wait asked no agent anything:
6853    /// the task is held by the machine under a `[resource]` reason (resumable,
6854    /// re-checked by triage), and the attempt it started is given back.
6855    #[test]
6856    fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
6857        let mut state = RunState::new(
6858            PathBuf::from("/repo"),
6859            "main".into(),
6860            "base".into(),
6861            "task".into(),
6862            Config::default(),
6863        );
6864        state.status = RunStatus::Landing;
6865        state.parked = true;
6866        state.pr_pushed_head = Some("head".into());
6867        state.land_unrelated = Some(
6868            serde_json::from_value(serde_json::json!({
6869                "head": "head", "question": "ci-question",
6870                "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
6871            }))
6872            .unwrap(),
6873        );
6874        let mut t = task();
6875        t.start(state.id.clone());
6876        let verdict = Verdict {
6877            status: RunStatus::Landing,
6878            left_pr: true,
6879            quota_hit: false,
6880            parked: true,
6881            no_viable_candidates: false,
6882        };
6883        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
6884        assert_eq!(t.attempts, 0);
6885        assert_eq!(t.status, TaskStatus::Held);
6886        assert!(!t.operator_held());
6887        assert!(
6888            t.hold_reason
6889                .as_deref()
6890                .unwrap()
6891                .starts_with("[ci-unrelated]")
6892        );
6893        // A second settlement must not refund an earlier task attempt.
6894        t.attempts = 1;
6895        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
6896        assert_eq!(t.attempts, 1);
6897        assert_eq!(t.passes.len(), 1);
6898        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
6899        state.pr_pushed_head = Some("new-head".into());
6900        state.parked = false;
6901        state.status = RunStatus::Blocked;
6902        let stale = Verdict {
6903            status: RunStatus::Blocked,
6904            parked: false,
6905            ..verdict
6906        };
6907        settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
6908        assert_eq!(t.attempts, 1);
6909        // A new execution pass can refund its own newly charged attempt.
6910        state.begin_pass();
6911        state.begin_pass();
6912        state.status = RunStatus::Landing;
6913        state.parked = true;
6914        state.pr_pushed_head = Some("head".into());
6915        settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
6916        assert_eq!(t.attempts, 0);
6917        assert_eq!(t.passes.len(), 2);
6918    }
6919
6920    #[test]
6921    fn orphan_recovery_does_not_refund_a_previous_pass_loss() {
6922        let mut state = run_state(RunStatus::Failed);
6923        state
6924            .quota
6925            .push(loss("advisor-1", "2026-10-22T14:38:00Z", None));
6926        state.begin_pass();
6927        let mut t = task();
6928        t.start(state.id.clone());
6929        reclaim(&mut t, Some(state), 2, "en");
6930        assert_eq!(t.attempts, 1);
6931    }
6932
6933    #[test]
6934    fn an_all_seats_unauthenticated_node_refunds_and_holds_without_retry() {
6935        let mut state = run_state(RunStatus::Blocked);
6936        let losses: Vec<_> = ["alpha", "beta"]
6937            .into_iter()
6938            .enumerate()
6939            .map(|(i, agent)| {
6940                QuotaLoss::from_report(
6941                    format!("advisor-{i}"),
6942                    "advise",
6943                    Some(&crate::agent::Quota {
6944                        cause: crate::agent::QuotaCause::Authentication,
6945                        agent: agent.to_owned(),
6946                        reset: None,
6947                    }),
6948                )
6949            })
6950            .collect();
6951        crate::graph::block_machine_outage(&mut state, "advise", &losses);
6952        state.quota = losses;
6953        let mut t = task();
6954        t.start(state.id.clone());
6955        let verdict = Verdict {
6956            status: state.status,
6957            left_pr: false,
6958            quota_hit: true,
6959            parked: false,
6960            no_viable_candidates: true,
6961        };
6962        settle_and_diagnose(&mut t, verdict, "authentication unavailable", 2, &state);
6963        assert_eq!(t.attempts, 0);
6964        assert_eq!(t.status, TaskStatus::Held);
6965        assert!(!t.operator_held());
6966        let reason = t.hold_reason.as_deref().unwrap();
6967        assert!(reason.starts_with("[authentication]"));
6968        assert!(
6969            reason.contains("alpha")
6970                && reason.contains("beta")
6971                && reason.contains("re-authenticate")
6972        );
6973        assert!(cooldown_until(&state.quota, Timestamp::now()).is_none());
6974        // Orphan recovery uses the same settlement and cannot spend an attempt.
6975        let mut orphan = task();
6976        orphan.start(state.id.clone());
6977        reclaim(&mut orphan, Some(state), 2, "en");
6978        assert_eq!(orphan.attempts, 0);
6979        assert_eq!(orphan.status, TaskStatus::Held);
6980    }
6981
6982    #[test]
6983    fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
6984        let mut state = RunState::new(
6985            PathBuf::from("/repo"),
6986            "main".to_owned(),
6987            "abc1234".to_owned(),
6988            "task".to_owned(),
6989            Config::default(),
6990        );
6991        state.status = RunStatus::Blocked;
6992        state.resource_block = Some(crate::run::ResourceBlock {
6993            cause: crate::run::ResourceBlockCause::Other,
6994            node: "graft".to_owned(),
6995            kind: "shared build cache".to_owned(),
6996            detail: "timed out".to_owned(),
6997            at: jiff::Timestamp::now(),
6998        });
6999        let mut t = task();
7000        t.start("20260902-000000-aaaa".to_owned());
7001        assert_eq!(t.attempts, 1);
7002        let verdict = Verdict {
7003            status: RunStatus::Blocked,
7004            left_pr: false,
7005            quota_hit: false,
7006            parked: false,
7007            no_viable_candidates: false,
7008        };
7009        settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
7010        assert_eq!(t.status, TaskStatus::Held);
7011        assert_eq!(t.attempts, 0, "the attempt is refunded");
7012        assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
7013        assert!(
7014            !t.operator_held(),
7015            "a machine hold, released without a human"
7016        );
7017
7018        let mut selected = task();
7019        selected.start("20260902-000000-cccc".into());
7020        selected.replacement = Some(crate::merge_decision::Replacement {
7021            question: "fixture".into(),
7022            run: "earlier".into(),
7023            pr: "https://example.invalid/pr/1".into(),
7024            agent: "selected".into(),
7025            context: "fixture".into(),
7026        });
7027        state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
7028        settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
7029        assert_eq!(selected.attempts, 0);
7030        assert!(
7031            !selected.operator_held(),
7032            "a selected agent also retains a machine resource hold"
7033        );
7034        assert!(
7035            selected
7036                .hold_reason
7037                .as_deref()
7038                .unwrap()
7039                .starts_with("[resource] ")
7040        );
7041
7042        // A park request outranks it: still the operator's doing.
7043        let mut p = task();
7044        p.start("20260902-000000-bbbb".to_owned());
7045        settle_and_diagnose(
7046            &mut p,
7047            Verdict {
7048                parked: true,
7049                ..verdict
7050            },
7051            "parked",
7052            2,
7053            &state,
7054        );
7055        assert_eq!(p.status, TaskStatus::Parked);
7056        assert_eq!(
7057            p.attempts, 0,
7058            "parking refunds once rather than also settling the resource hold"
7059        );
7060    }
7061
7062    #[test]
7063    fn record_failure_notice_links_the_task() {
7064        let dir = tempfile::tempdir().unwrap();
7065        // A regular file where the queue directory should be makes every
7066        // `put` fail, on every platform and whoever runs the test.
7067        std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
7068        let queue = Queue::at(dir.path().join("queue"));
7069        let mut t = interrupt_task("rec-fail-1");
7070        record(&queue, &mut t);
7071
7072        let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
7073        assert_eq!(found.len(), 1);
7074        assert_eq!(found[0].key, "loop:record");
7075        assert_eq!(
7076            found[0].link,
7077            Some(Link::Task {
7078                id: "rec-fail-1".to_owned()
7079            })
7080        );
7081    }
7082
7083    /// A runnable task marked to interrupt, with an id fixed for assertions
7084    /// rather than the random one [`Task::new`] mints.
7085    fn interrupt_task(id: &str) -> Task {
7086        let mut t = task();
7087        t.id = id.to_owned();
7088        t.interrupt = true;
7089        t
7090    }
7091
7092    /// An ordinary runnable task with an id fixed for assertions.
7093    fn task_with_id(id: &str) -> Task {
7094        let mut t = task();
7095        t.id = id.to_owned();
7096        t
7097    }
7098
7099    /// A runnable task marked `--urgent`, with an id fixed for assertions.
7100    fn urgent_task(id: &str) -> Task {
7101        let mut t = task();
7102        t.id = id.to_owned();
7103        t.urgent = true;
7104        t
7105    }
7106
7107    #[test]
7108    fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
7109        let dir = tempfile::tempdir().unwrap();
7110        let queue = Queue::at(dir.path().join("queue"));
7111        let mut parked = task_with_id("parked");
7112        parked.start("run".into());
7113        parked.park("upgrade");
7114        parked.record_pass_at(
7115            "run",
7116            0,
7117            Some(Timestamp::now()),
7118            1,
7119            Some(crate::run::ParkCause::Upgrade {
7120                from: "old".into(),
7121                to: None,
7122            }),
7123        );
7124        let mut fresh = task_with_id("fresh");
7125        fresh.priority = 100;
7126        let mut urgent_task = urgent_task("urgent");
7127        for t in [&mut parked, &mut fresh, &mut urgent_task] {
7128            queue.put(t).unwrap();
7129        }
7130        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7131        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7132        let candidates = runnable(&queue);
7133        assert_eq!(candidates[0].id, parked.id);
7134        let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
7135        assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_none());
7136        assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_some());
7137        drop(first);
7138        let claimed_elsewhere = queue.claim(&parked.id).unwrap();
7139        let next = runnable(&queue)
7140            .into_iter()
7141            .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent))
7142            .unwrap();
7143        assert_eq!(next.task.id, fresh.id);
7144        assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
7145        drop(claimed_elsewhere);
7146        drop(next);
7147        assert!(claim_dispatch(&queue, &parked, true, &ordinary, &urgent).is_none());
7148    }
7149
7150    #[test]
7151    fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
7152        let dir = tempfile::tempdir().unwrap();
7153        let queue = Queue::at(dir.path().join("queue"));
7154        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7155        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7156        let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
7157        let mut first = task();
7158        queue.put(&mut first).unwrap();
7159        let stale_plain = queue.get(&first.id).unwrap();
7160        first.set_urgent(true).unwrap();
7161        queue.put(&mut first).unwrap();
7162        let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
7163        let mut second = urgent_task("second");
7164        queue.put(&mut second).unwrap();
7165        assert!(claim_dispatch(&queue, &second, false, &ordinary, &urgent).is_none());
7166        drop(queue.claim(&second.id).unwrap());
7167        assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
7168        drop(dispatched);
7169        let stale_urgent = queue.get(&first.id).unwrap();
7170        first.set_urgent(false).unwrap();
7171        queue.put(&mut first).unwrap();
7172        assert!(claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent).is_none());
7173        assert_eq!(urgent.available_permits(), 1);
7174        drop(queue.claim(&first.id).unwrap());
7175        drop(occupied);
7176    }
7177
7178    #[test]
7179    fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
7180        let dir = tempfile::tempdir().unwrap();
7181        let queue = Queue::at(dir.path().join("queue"));
7182        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7183        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7184        let mut t = task();
7185        queue.put(&mut t).unwrap();
7186        for enabled in [true, false] {
7187            let stale = queue.get(&t.id).unwrap();
7188            t.set_urgent(enabled).unwrap();
7189            queue.put(&mut t).unwrap();
7190            assert_ne!(stale.urgent, enabled);
7191            let DispatchClaim {
7192                task: fresh,
7193                claim,
7194                permit,
7195            } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
7196            assert_eq!(fresh.urgent, enabled);
7197            assert_eq!(ordinary.available_permits(), usize::from(enabled));
7198            assert_eq!(urgent.available_permits(), usize::from(!enabled));
7199            assert!(queue.claim(&t.id).is_err());
7200            assert_eq!(fresh.attempts, stale.attempts);
7201            drop((claim, permit));
7202            assert_eq!(ordinary.available_permits(), 1);
7203            assert_eq!(urgent.available_permits(), 1);
7204        }
7205        t.set_urgent(true).unwrap();
7206        queue.put(&mut t).unwrap();
7207        let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
7208        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7209        assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
7210        drop(queue.claim(&t.id).unwrap());
7211        assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
7212        drop(occupied);
7213        assert!(claim_dispatch(&queue, &t, true, &ordinary, &urgent).is_none());
7214        drop(queue.claim(&t.id).unwrap());
7215        let held = queue.claim(&t.id).unwrap();
7216        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7217        drop(held);
7218        t.status = TaskStatus::Held;
7219        queue.put(&mut t).unwrap();
7220        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7221        drop(queue.claim(&t.id).unwrap());
7222        std::fs::remove_file(queue.path_of(&t.id)).unwrap();
7223        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7224        drop(queue.claim(&t.id).unwrap());
7225        assert_eq!(urgent.available_permits(), 1);
7226    }
7227
7228    /// The land-resume exemption wins outright, whether or not the candidate
7229    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
7230    /// queue behind anything" guarantee cannot be weaker just because the
7231    /// same task was also filed with `--urgent`.
7232    #[test]
7233    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
7234        assert_eq!(permit_kind(true, false), PermitKind::None);
7235        assert_eq!(permit_kind(true, true), PermitKind::None);
7236    }
7237
7238    /// The one property this whole feature exists for: `--urgent` draws from
7239    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
7240    /// ordinary candidate draws from the ordinary pool exactly as before,
7241    /// untouched by the urgent slot's existence.
7242    #[test]
7243    fn permit_kind_separates_urgent_from_ordinary() {
7244        assert_eq!(permit_kind(false, true), PermitKind::Urgent);
7245        assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
7246    }
7247
7248    /// The exact wiring `attempt` runs before minting anything: a config's
7249    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
7250    /// Free space is injected rather than asked of the real disk - the point
7251    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
7252    /// is deterministic on every machine this test runs on, never dependent
7253    /// on how full the CI runner's own disk happens to be.
7254    #[test]
7255    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
7256        let cfg = Config::default();
7257        let repo = Path::new("/any/repo/path");
7258
7259        let reason =
7260            disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
7261        assert!(reason.contains("1024"), "{reason}");
7262        assert!(
7263            reason.contains(&cfg.disk.min_free_bytes.to_string()),
7264            "{reason}"
7265        );
7266
7267        assert_eq!(
7268            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
7269            None,
7270            "exactly at the floor is open"
7271        );
7272        assert_eq!(
7273            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
7274            None,
7275            "comfortably above the floor is open"
7276        );
7277    }
7278
7279    #[test]
7280    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
7281        let mut cfg = Config::default();
7282        cfg.disk.min_free_bytes = 0;
7283        let repo = Path::new("/any/repo/path");
7284        assert_eq!(
7285            disk_gate_with(repo, &cfg, |_| Ok(0)),
7286            None,
7287            "a zero floor never measures at all"
7288        );
7289    }
7290
7291    #[test]
7292    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
7293        let cfg = Config::default();
7294        let repo = Path::new("/any/repo/path");
7295        let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
7296            .expect("a measurement failure must close the gate, not open it");
7297        assert!(reason.contains("could not measure"), "{reason}");
7298    }
7299
7300    #[test]
7301    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
7302        let ordinary = task();
7303        let next = advance_interrupt(
7304            Interrupt::Idle,
7305            std::slice::from_ref(&ordinary.id),
7306            std::slice::from_ref(&ordinary),
7307        );
7308        assert_eq!(next, Interrupt::Idle);
7309    }
7310
7311    #[test]
7312    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
7313        // Nothing to interrupt - this is just an ordinary candidate, and the
7314        // loop's normal dispatch will pick it up like any other.
7315        let marked = interrupt_task("marked");
7316        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7317        assert_eq!(next, Interrupt::Idle);
7318    }
7319
7320    #[test]
7321    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
7322        let marked = interrupt_task("marked");
7323        let next = advance_interrupt(
7324            Interrupt::Idle,
7325            &["running".to_owned()],
7326            std::slice::from_ref(&marked),
7327        );
7328        assert_eq!(
7329            next,
7330            Interrupt::Parking {
7331                parked: vec!["running".to_owned()],
7332                interrupt_task: "marked".to_owned(),
7333            }
7334        );
7335    }
7336
7337    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
7338    /// one run can be in flight when a task becomes runnable and marked.
7339    /// Parking all of them would mean `Resuming` later has more than one id
7340    /// to release back to ordinary dispatch, which cannot be made safe
7341    /// against that same setting's own extra concurrency slots letting two
7342    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
7343    /// The simplification the task's own constraints ask for: do not begin
7344    /// a sequence at all until the herd settles back to exactly one.
7345    #[test]
7346    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
7347        let marked = interrupt_task("marked");
7348
7349        let two = advance_interrupt(
7350            Interrupt::Idle,
7351            &["a".to_owned(), "b".to_owned()],
7352            std::slice::from_ref(&marked),
7353        );
7354        assert_eq!(two, Interrupt::Idle);
7355
7356        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7357        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
7358    }
7359
7360    #[test]
7361    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
7362        let state = Interrupt::Parking {
7363            parked: vec!["running".to_owned()],
7364            interrupt_task: "marked".to_owned(),
7365        };
7366        // Still in flight: no change.
7367        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
7368        assert_eq!(still_going, state);
7369
7370        // Left flight, but the interrupt task has not been dispatched yet on
7371        // this tick - stays `Parking` so `interrupt_gate` can let it through,
7372        // as long as it is still runnable.
7373        let stopped_but_not_yet_dispatched =
7374            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
7375        assert_eq!(stopped_but_not_yet_dispatched, state);
7376
7377        // Left flight, and the interrupt task is now in flight itself.
7378        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
7379        assert_eq!(
7380            dispatched,
7381            Interrupt::Running {
7382                parked: vec!["running".to_owned()],
7383                interrupt_task: "marked".to_owned(),
7384            }
7385        );
7386    }
7387
7388    #[test]
7389    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
7390        let state = Interrupt::Running {
7391            parked: vec!["running".to_owned()],
7392            interrupt_task: "marked".to_owned(),
7393        };
7394        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
7395        assert_eq!(still_running, state);
7396
7397        // Whatever it ended as - merged, failed, held - is not this
7398        // function's concern: leaving flight is the only trigger, driven
7399        // straight off the same in-flight list `poll` already reaps. It does
7400        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
7401        // why that would let an unrelated task start ahead of, or alongside,
7402        // the guaranteed resume.
7403        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
7404        assert_eq!(
7405            ended,
7406            Interrupt::Resuming {
7407                parked: vec!["running".to_owned()]
7408            }
7409        );
7410    }
7411
7412    #[test]
7413    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
7414        let state = Interrupt::Resuming {
7415            parked: vec!["running".to_owned()],
7416        };
7417        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
7418        assert_eq!(still_waiting, state);
7419
7420        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
7421        assert_eq!(dispatched, Interrupt::Idle);
7422    }
7423
7424    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
7425    /// or otherwise moved on by an operator with no claim standing in the
7426    /// way - must not wedge the sequence (and so the whole loop's dispatch,
7427    /// via `interrupt_gate`) waiting forever for a dispatch that can never
7428    /// come. The parked run still gets its resume.
7429    #[test]
7430    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
7431    {
7432        let state = Interrupt::Parking {
7433            parked: vec!["running".to_owned()],
7434            interrupt_task: "marked".to_owned(),
7435        };
7436        // `marked` has been held/blocked/deleted since the sequence began:
7437        // it no longer appears in `runnable` at all.
7438        let next = advance_interrupt(state, &[], &[]);
7439        assert_eq!(
7440            next,
7441            Interrupt::Resuming {
7442                parked: vec!["running".to_owned()]
7443            },
7444            "abandoning the interrupt must not abandon the resume it owes"
7445        );
7446    }
7447
7448    /// The same abandonment, one step later: `Resuming` itself must not wait
7449    /// forever for a parked task that has since become unrunnable.
7450    #[test]
7451    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
7452        let state = Interrupt::Resuming {
7453            parked: vec!["running".to_owned()],
7454        };
7455        let next = advance_interrupt(state, &[], &[]);
7456        assert_eq!(
7457            next,
7458            Interrupt::Idle,
7459            "nothing is left to wait for; the loop must not stay wedged"
7460        );
7461    }
7462
7463    #[test]
7464    fn disabled_by_config_the_sequence_can_never_leave_idle() {
7465        let marked = interrupt_task("marked");
7466        let next = advance_interrupt_tick(
7467            false,
7468            Interrupt::Idle,
7469            &["running".to_owned()],
7470            std::slice::from_ref(&marked),
7471        );
7472        assert_eq!(
7473            next,
7474            Interrupt::Idle,
7475            "an unmarked, unconfigured daemon must behave exactly as before"
7476        );
7477    }
7478
7479    #[test]
7480    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
7481        let state = Interrupt::Parking {
7482            parked: vec!["running".to_owned()],
7483            interrupt_task: "marked".to_owned(),
7484        };
7485        let candidates = vec![interrupt_task("marked"), task()];
7486        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
7487        assert!(
7488            allowed.is_empty(),
7489            "nothing may dispatch - not even the interrupt task itself - \
7490             until the parked run has actually stopped"
7491        );
7492    }
7493
7494    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
7495    /// grow a special case for it: an urgent candidate that is not the
7496    /// interrupt task withholds exactly like an ordinary one for as long as
7497    /// the parked run it is racing has not actually left flight. A version
7498    /// of this feature once bypassed the gate for urgent candidates, on the
7499    /// theory that a genuinely separate concurrency lane could not collide
7500    /// with 75dd's own; it could, and did - the bypassed task dispatched
7501    /// alongside a run 75dd's own state machine had only *asked* to park,
7502    /// not yet confirmed gone, which is exactly the second run
7503    /// `Interrupt::Parking`'s own doc says must never happen. There is no
7504    /// tick during Parking/Running/Resuming where letting an extra
7505    /// candidate through is safe, urgent or not - the parked run may still
7506    /// be genuinely mid-call.
7507    #[test]
7508    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
7509        for state in [
7510            Interrupt::Parking {
7511                parked: vec!["running".to_owned()],
7512                interrupt_task: "marked".to_owned(),
7513            },
7514            Interrupt::Running {
7515                parked: vec!["running".to_owned()],
7516                interrupt_task: "marked".to_owned(),
7517            },
7518            Interrupt::Resuming {
7519                parked: vec!["running".to_owned()],
7520            },
7521        ] {
7522            let candidates = vec![
7523                interrupt_task("marked"),
7524                urgent_task("hot"),
7525                task_with_id("ordinary"),
7526            ];
7527            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
7528            assert!(
7529                !allowed.iter().any(|t| t.id == "hot"),
7530                "an urgent candidate must wait out the same gate as anything \
7531                 else while the run it would run alongside has not actually \
7532                 left flight, for state {state:?}: {allowed:?}"
7533            );
7534        }
7535    }
7536
7537    /// The one case where marking a task `--urgent` and `interrupt` at once
7538    /// is not redundant: once the interrupt sequence's own guaranteed
7539    /// resume/dispatch actually admits the task, it is unaffected by also
7540    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
7541    /// never on the urgent flag.
7542    #[test]
7543    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
7544        let state = Interrupt::Resuming {
7545            parked: vec!["hot".to_owned()],
7546        };
7547        let candidates = vec![urgent_task("hot"), task()];
7548        let allowed = interrupt_gate(&state, &[], candidates);
7549        assert_eq!(
7550            allowed.iter().filter(|t| t.id == "hot").count(),
7551            1,
7552            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
7553        );
7554    }
7555
7556    #[test]
7557    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
7558        let state = Interrupt::Parking {
7559            parked: vec!["running".to_owned()],
7560            interrupt_task: "marked".to_owned(),
7561        };
7562        let other = task();
7563        let candidates = vec![interrupt_task("marked"), other.clone()];
7564        let allowed = interrupt_gate(&state, &[], candidates);
7565        assert_eq!(allowed.len(), 1);
7566        assert_eq!(allowed[0].id, "marked");
7567    }
7568
7569    #[test]
7570    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
7571        let state = Interrupt::Running {
7572            parked: vec!["running".to_owned()],
7573            interrupt_task: "marked".to_owned(),
7574        };
7575        let candidates = vec![task(), task()];
7576        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
7577        assert!(allowed.is_empty());
7578    }
7579
7580    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
7581    /// sequence began (only reachable above the default
7582    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
7583    /// never both in the same tick, which is what "exactly one resume, no
7584    /// simultaneous run" actually requires structurally rather than by
7585    /// coincidence of how many ordinary slots happen to be free.
7586    #[test]
7587    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
7588        let state = Interrupt::Resuming {
7589            parked: vec!["a".to_owned(), "c".to_owned()],
7590        };
7591        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
7592        let allowed = interrupt_gate(&state, &[], candidates);
7593        assert_eq!(
7594            allowed.len(),
7595            1,
7596            "at most one candidate may be offered while resuming: {allowed:?}"
7597        );
7598        assert_eq!(allowed[0].id, "a");
7599    }
7600
7601    #[test]
7602    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
7603        let state = Interrupt::Resuming {
7604            parked: vec!["a".to_owned()],
7605        };
7606        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
7607        assert!(allowed.is_empty());
7608    }
7609
7610    /// The invariant the completion criteria ask for by name: across a whole
7611    /// simulated sequence, there is never a tick where the gate would let
7612    /// through both the parked run's resume and the interrupt task, and
7613    /// exactly one candidate resumes the instant the interrupt task's run
7614    /// ends - never zero, never more than one.
7615    #[test]
7616    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
7617        let running = task(); // id: whatever `Task::new` minted
7618        let marked = interrupt_task("marked");
7619
7620        let mut state = Interrupt::Idle;
7621        // Tick 1: `running` is in flight, `marked` becomes runnable.
7622        let in_flight = vec![running.id.clone()];
7623        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
7624        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
7625        assert!(gated.is_empty(), "still waiting on `running` to park");
7626
7627        // Tick 2: `running` parked and left flight; nothing dispatched yet.
7628        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
7629        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
7630        assert_eq!(
7631            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7632            vec!["marked"],
7633            "only the interrupt task may be offered to the dispatcher now"
7634        );
7635
7636        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
7637        state = advance_interrupt_tick(
7638            true,
7639            state,
7640            &["marked".to_owned()],
7641            std::slice::from_ref(&running),
7642        );
7643        let gated = interrupt_gate(
7644            &state,
7645            &["marked".to_owned()],
7646            vec![marked.clone(), running.clone()],
7647        );
7648        assert!(
7649            gated.is_empty(),
7650            "the parked run must not be offered back while the interrupt \
7651             task is still running"
7652        );
7653
7654        // Tick 4: `marked`'s run reached a terminal status and left flight.
7655        // A higher-priority ordinary task `other` is also runnable now - it
7656        // must not be let through instead of, or alongside, `running`.
7657        let other = task_with_id("other");
7658        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
7659        assert_eq!(
7660            state,
7661            Interrupt::Resuming {
7662                parked: vec![running.id.clone()]
7663            }
7664        );
7665        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
7666        assert_eq!(
7667            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7668            vec![running.id.as_str()],
7669            "exactly the parked run resumes - not the unrelated task, even \
7670             though it was offered first"
7671        );
7672
7673        // Tick 5: `running` is now in flight (dispatched from tick 4's
7674        // gate). Only now does the sequence end and ordinary dispatch fully
7675        // resume.
7676        state = advance_interrupt_tick(
7677            true,
7678            state,
7679            std::slice::from_ref(&running.id),
7680            std::slice::from_ref(&other),
7681        );
7682        assert_eq!(state, Interrupt::Idle);
7683        let gated = interrupt_gate(
7684            &state,
7685            std::slice::from_ref(&running.id),
7686            vec![other.clone()],
7687        );
7688        assert_eq!(
7689            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7690            vec![other.id.as_str()],
7691            "ordinary dispatch is unrestricted again"
7692        );
7693    }
7694
7695    #[test]
7696    fn every_run_status_settles_the_task_it_came_from() {
7697        // run status, resulting task status, attempts still standing after one
7698        let table = [
7699            (RunStatus::Merged, TaskStatus::Done, 1),
7700            (RunStatus::Ready, TaskStatus::Done, 1),
7701            (RunStatus::Stalled, TaskStatus::Failed, 0),
7702            (RunStatus::Blocked, TaskStatus::Failed, 1),
7703            (RunStatus::Failed, TaskStatus::Failed, 1),
7704            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
7705            (RunStatus::Prep, TaskStatus::Failed, 1),
7706            (RunStatus::Implementing, TaskStatus::Failed, 1),
7707            (RunStatus::Judging, TaskStatus::Failed, 1),
7708            (RunStatus::Deliberating, TaskStatus::Failed, 1),
7709            (RunStatus::Voting, TaskStatus::Failed, 1),
7710            (RunStatus::Reviewing, TaskStatus::Failed, 1),
7711            (RunStatus::Gating, TaskStatus::Failed, 1),
7712        ];
7713        for (run, want, attempts) in table {
7714            let mut t = task();
7715            t.start("20260902-000000-aaaa".to_owned());
7716            settle(
7717                &mut t,
7718                Verdict {
7719                    status: run,
7720                    left_pr: false,
7721                    parked: false,
7722                    quota_hit: matches!(run, RunStatus::Stalled),
7723                    no_viable_candidates: false,
7724                },
7725                "why",
7726                2,
7727            );
7728            assert_eq!(t.status, want, "task status after {}", label(run));
7729            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
7730        }
7731    }
7732
7733    #[test]
7734    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
7735        let mut stalled = task();
7736        stalled.start("20260902-000000-aaaa".to_owned());
7737        settle(
7738            &mut stalled,
7739            Verdict {
7740                status: RunStatus::Stalled,
7741                left_pr: false,
7742                parked: false,
7743                quota_hit: true,
7744                no_viable_candidates: false,
7745            },
7746            "quota",
7747            1,
7748        );
7749        assert_eq!(stalled.attempts, 0);
7750        assert!(
7751            stalled.status.runnable(),
7752            "a machine problem must leave the task in line"
7753        );
7754
7755        let mut blocked = task();
7756        blocked.start("20260902-000000-aaaa".to_owned());
7757        settle(
7758            &mut blocked,
7759            Verdict {
7760                status: RunStatus::Blocked,
7761                left_pr: false,
7762                parked: false,
7763                quota_hit: false,
7764                no_viable_candidates: false,
7765            },
7766            "findings open",
7767            1,
7768        );
7769        assert_eq!(blocked.attempts, 1);
7770        assert_eq!(
7771            blocked.status,
7772            TaskStatus::Held,
7773            "the last attempt hands the task to a human"
7774        );
7775    }
7776
7777    #[test]
7778    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
7779        // Attempts to spare: without the pull request this task would go
7780        // straight back in line and run the whole competition again.
7781        let mut delivered = task();
7782        delivered.start("20260903-080619-01c2".to_owned());
7783        settle(
7784            &mut delivered,
7785            Verdict {
7786                status: RunStatus::Blocked,
7787                left_pr: true,
7788                parked: false,
7789                quota_hit: false,
7790                no_viable_candidates: false,
7791            },
7792            "no check status",
7793            4,
7794        );
7795        assert_eq!(
7796            delivered.status,
7797            TaskStatus::Held,
7798            "a pull request waiting on CI or a person is not a retryable failure"
7799        );
7800        assert!(
7801            !delivered.status.runnable(),
7802            "the loop must not pick this task up again"
7803        );
7804        assert_eq!(
7805            delivered.last_error.as_deref(),
7806            Some("no check status"),
7807            "the operator needs to be told what the gate was waiting for"
7808        );
7809
7810        // The same status without a pull request is a plain failure, and with
7811        // attempts left it is retried.
7812        let mut empty_handed = task();
7813        empty_handed.start("20260903-080619-01c2".to_owned());
7814        settle(
7815            &mut empty_handed,
7816            Verdict {
7817                status: RunStatus::Blocked,
7818                left_pr: false,
7819                parked: false,
7820                quota_hit: false,
7821                no_viable_candidates: false,
7822            },
7823            "findings open",
7824            4,
7825        );
7826        assert_eq!(empty_handed.status, TaskStatus::Failed);
7827        assert!(empty_handed.status.runnable());
7828    }
7829
7830    #[test]
7831    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
7832        // Every candidate agreed, with evidence, that nothing belonged in the
7833        // worktree. That is not a confirmed success to close automatically -
7834        // a human still has to check the claim - and it is not an ordinary
7835        // failure either, so this settles exactly like a pull request nobody
7836        // merged yet: `Held`, same as `Blocked` with a PR.
7837        let mut noop = task();
7838        noop.start("20260912-131304-391f".to_owned());
7839        settle(
7840            &mut noop,
7841            Verdict {
7842                status: RunStatus::VerifiedNoop,
7843                left_pr: false,
7844                parked: false,
7845                quota_hit: false,
7846                no_viable_candidates: true,
7847            },
7848            "candidate A: already fixed by b32cfc4, on main",
7849            4,
7850        );
7851        assert_eq!(
7852            noop.status,
7853            TaskStatus::Held,
7854            "an unverified claim is a request for a human, not a failure"
7855        );
7856        assert!(
7857            !noop.status.runnable(),
7858            "the loop must not requeue this on the same unverified claim"
7859        );
7860        // `Task::release` resets attempts to zero the moment a human looks at
7861        // the evidence and lets it run again, so it does not matter here
7862        // whether the one attempt already spent stays spent - what matters is
7863        // that nothing retries this task unattended in the meantime.
7864        assert_eq!(noop.attempts, 1);
7865    }
7866
7867    #[test]
7868    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
7869        // Parking is the operator asking for the process back - to replace the
7870        // binary, most of all. The run's work is intact on disk, so this is
7871        // not a failed attempt, and charging for it would mean a few upgrades
7872        // could exhaust a budget meant for agents that misbehaved.
7873        let mut parked = task();
7874        parked.start("20260903-183634-2d98".to_owned());
7875        settle(
7876            &mut parked,
7877            Verdict {
7878                status: RunStatus::Implementing,
7879                left_pr: false,
7880                quota_hit: false,
7881                parked: true,
7882                no_viable_candidates: false,
7883            },
7884            "parked after `implementing`",
7885            2,
7886        );
7887        assert_eq!(parked.attempts, 0, "a park is refunded");
7888        assert!(
7889            parked.status.runnable(),
7890            "and the task stays in line so the next loop resumes its run"
7891        );
7892        assert_eq!(parked.status, TaskStatus::Parked);
7893        assert_eq!(
7894            parked.park_reason.as_deref(),
7895            Some("parked after `implementing`"),
7896            "the card says where it stopped"
7897        );
7898        assert_eq!(parked.last_error, None, "nothing failed");
7899
7900        // Without the park flag the same non-terminal status is what it always
7901        // was: `execute` returning mid-flight, which is a bug and spends an
7902        // attempt so a task cannot loop on it forever.
7903        let mut broken = task();
7904        broken.start("20260903-183634-2d98".to_owned());
7905        settle(
7906            &mut broken,
7907            Verdict {
7908                status: RunStatus::Implementing,
7909                left_pr: false,
7910                quota_hit: false,
7911                parked: false,
7912                no_viable_candidates: false,
7913            },
7914            "returned mid-flight",
7915            2,
7916        );
7917        assert_eq!(broken.attempts, 1);
7918    }
7919
7920    #[test]
7921    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
7922        // Run e633: quorum lost because two judges answered with the wrong
7923        // JSON shape, `quota: []`. Refunding that takes the bound off the
7924        // retry loop, and each retry pays for a fresh hour-long implement
7925        // wave before it can fail the same way.
7926        let mut flaky = task();
7927        flaky.start("20260903-123023-e633".to_owned());
7928        settle(
7929            &mut flaky,
7930            Verdict {
7931                status: RunStatus::Stalled,
7932                left_pr: false,
7933                parked: false,
7934                quota_hit: false,
7935                no_viable_candidates: false,
7936            },
7937            "verdict rests on 1 of 3 judges",
7938            2,
7939        );
7940        assert_eq!(
7941            flaky.attempts, 1,
7942            "flakiness spends an attempt, so `max_attempts` still bounds it"
7943        );
7944        assert!(flaky.status.runnable(), "and it is still worth retrying");
7945
7946        // The same status, lost to a rate limit, is the machine's fault.
7947        let mut limited = task();
7948        limited.start("20260903-123023-e633".to_owned());
7949        settle(
7950            &mut limited,
7951            Verdict {
7952                status: RunStatus::Stalled,
7953                left_pr: false,
7954                parked: false,
7955                quota_hit: true,
7956                no_viable_candidates: false,
7957            },
7958            "judge-2, judge-3 out of quota",
7959            2,
7960        );
7961        assert_eq!(limited.attempts, 0, "a quota window is refunded");
7962        assert!(limited.status.runnable());
7963
7964        // And the bound really binds: a task that keeps stalling on flakiness
7965        // reaches a human instead of running the roster forever.
7966        let mut worn = task();
7967        for _ in 0..2 {
7968            worn.release();
7969        }
7970        worn.start("20260903-123023-e633".to_owned());
7971        worn.attempts = 2;
7972        settle(
7973            &mut worn,
7974            Verdict {
7975                status: RunStatus::Stalled,
7976                left_pr: false,
7977                parked: false,
7978                quota_hit: false,
7979                no_viable_candidates: false,
7980            },
7981            "no quorum again",
7982            2,
7983        );
7984        assert_eq!(worn.status, TaskStatus::Held);
7985        assert!(!worn.status.runnable());
7986    }
7987
7988    #[test]
7989    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
7990        // The implement wave loses every seat to the same rate limit and
7991        // `after_implement` bails with nothing viable, which surfaces as
7992        // `Failed` rather than `Stalled`. That is the same machine fact the
7993        // `Stalled`-quota row already refunds, and must be refunded the same
7994        // way, or a quota outage quietly holds every task it touches instead
7995        // of leaving them in line for the reset.
7996        let mut wiped_out = task();
7997        wiped_out.start("20260907-025000-a1b2".to_owned());
7998        settle(
7999            &mut wiped_out,
8000            Verdict {
8001                status: RunStatus::Failed,
8002                left_pr: false,
8003                parked: false,
8004                quota_hit: true,
8005                no_viable_candidates: true,
8006            },
8007            "no candidate produced a change; nothing to judge",
8008            2,
8009        );
8010        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
8011        assert!(
8012            wiped_out.status.runnable(),
8013            "a machine problem must leave the task in line"
8014        );
8015
8016        // This is the exemption that must stay narrow: a candidate that did
8017        // produce a change, and then failed for some other reason, still
8018        // spends the attempt even though a seat elsewhere hit its quota.
8019        // Otherwise every ordinary failure that happens to share a run with
8020        // an unrelated rate limit would be refunded for free.
8021        let mut partial_progress = task();
8022        partial_progress.start("20260907-025500-c3d4".to_owned());
8023        settle(
8024            &mut partial_progress,
8025            Verdict {
8026                status: RunStatus::Failed,
8027                left_pr: false,
8028                parked: false,
8029                quota_hit: true,
8030                no_viable_candidates: false,
8031            },
8032            "gate failed on the winning candidate",
8033            2,
8034        );
8035        assert_eq!(
8036            partial_progress.attempts, 1,
8037            "a candidate that actually produced a change spends the attempt \
8038             even though some other seat hit its quota"
8039        );
8040        assert!(partial_progress.status.runnable());
8041    }
8042
8043    #[test]
8044    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
8045        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
8046        // disk, and that construction must reach the same conclusion as the
8047        // one `attempt` builds from a live run, or a crash at exactly the
8048        // wrong moment gives a recovered task a different policy than one a
8049        // daemon finished settling itself.
8050        let mut t = task();
8051        t.start("20260907-025000-a1b2".to_owned());
8052        let mut state = run_state(RunStatus::Failed);
8053        state.quota.push(QuotaLoss {
8054            cause: crate::agent::QuotaCause::UsageLimit,
8055            agent: String::new(),
8056            seat: "cand-a".to_owned(),
8057            node: "implement".to_owned(),
8058            at: Timestamp::now(),
8059            reset: None,
8060        });
8061        assert!(
8062            state.viable().is_empty(),
8063            "no candidate was added, so nothing is viable"
8064        );
8065        reclaim(&mut t, Some(state), 2, "en");
8066        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
8067        assert!(t.status.runnable());
8068    }
8069
8070    #[test]
8071    fn a_held_task_is_never_offered_to_the_loop() {
8072        let dir = tempfile::tempdir().unwrap();
8073        let queue = Queue::at(dir.path().to_path_buf());
8074        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
8075            let mut t = task();
8076            t.id = format!("2026090{n}-000000-000{n}");
8077            t.priority = priority;
8078            queue.put(&mut t).unwrap();
8079        }
8080        let mut held = task();
8081        held.id = "20260909-000000-9999".to_owned();
8082        held.priority = 99;
8083        held.hold_machine(None);
8084        queue.put(&mut held).unwrap();
8085
8086        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
8087        assert_eq!(order.len(), 3);
8088        assert!(!order.contains(&held.id));
8089        assert_eq!(
8090            order.first().cloned(),
8091            queue.next_runnable().map(|t| t.id),
8092            "the loop's first candidate is exactly what the queue offers"
8093        );
8094        assert_eq!(
8095            order,
8096            vec![
8097                "20260902-000000-0002".to_owned(),
8098                "20260903-000000-0003".to_owned(),
8099                "20260901-000000-0001".to_owned(),
8100            ],
8101            "priority first, then oldest, so nothing starves"
8102        );
8103    }
8104
8105    #[test]
8106    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
8107        let dir = tempfile::tempdir().unwrap();
8108        let queue = Queue::at(dir.path().to_path_buf());
8109        let mut old = task();
8110        old.id = "20260101-000000-old0".to_owned();
8111        queue.put(&mut old).unwrap();
8112        let mut fresh = task();
8113        fresh.id = "20260101-000000-new0".to_owned();
8114        queue.put(&mut fresh).unwrap();
8115
8116        // No parseable pid at all, so age is the only signal there is to
8117        // check - unlike a real `Queue::claim`, which always names a real,
8118        // and therefore alive, pid this test cannot fake as dead.
8119        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
8120        std::thread::sleep(Duration::from_millis(60));
8121        let live = queue.claim(&fresh.id).unwrap();
8122
8123        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8124        assert_eq!(swept, vec![old.id.clone()]);
8125        assert!(
8126            queue.claim(&old.id).is_ok(),
8127            "an unparseable lock older than the threshold is swept"
8128        );
8129        assert!(
8130            queue.claim(&fresh.id).is_err(),
8131            "a live pid protects its lock regardless of age"
8132        );
8133        drop(live);
8134    }
8135
8136    #[test]
8137    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
8138        // A live worker's claim remains authoritative even beyond the sweep's
8139        // age limit. Sweeping it would permit a second competing attempt.
8140        let dir = tempfile::tempdir().unwrap();
8141        let queue = Queue::at(dir.path().to_path_buf());
8142        let mut t = task();
8143        t.id = "20260101-000000-live".to_owned();
8144        queue.put(&mut t).unwrap();
8145
8146        let claim = queue.claim(&t.id).unwrap();
8147        std::thread::sleep(Duration::from_millis(60));
8148
8149        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8150        assert!(
8151            swept.is_empty(),
8152            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
8153        );
8154        assert!(
8155            queue.claim(&t.id).is_err(),
8156            "the lock still protects its task"
8157        );
8158        drop(claim);
8159    }
8160
8161    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
8162    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
8163    fn injected_dead_pid() -> u32 {
8164        std::process::id().checked_add(1).unwrap_or(1)
8165    }
8166
8167    #[test]
8168    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
8169        let dir = tempfile::tempdir().unwrap();
8170        let queue = Queue::at(dir.path().to_path_buf());
8171        let mut t = task();
8172        t.id = "20260101-000000-dead".to_owned();
8173        queue.put(&mut t).unwrap();
8174        let dead_pid = injected_dead_pid();
8175
8176        // Written directly rather than through `Queue::claim`, which would
8177        // stamp this test process's own very much alive pid and defeat the
8178        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
8179        // like moments after it died, not six hours later.
8180        std::fs::write(
8181            dir.path().join(format!("{}.lock", t.id)),
8182            dead_pid.to_string(),
8183        )
8184        .unwrap();
8185
8186        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8187            pid != dead_pid
8188        });
8189        assert_eq!(
8190            swept,
8191            vec![t.id.clone()],
8192            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
8193        );
8194        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
8195    }
8196
8197    #[test]
8198    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
8199        let dir = tempfile::tempdir().unwrap();
8200        let queue = Queue::at(dir.path().to_path_buf());
8201        let mut t = task();
8202        t.id = "20260101-000000-late".to_owned();
8203        queue.put(&mut t).unwrap();
8204        let dead_pid = injected_dead_pid();
8205
8206        // Tick one, standing in for the sweep `poll` already runs at
8207        // startup: nothing to find yet.
8208        assert!(
8209            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
8210            "nothing has claimed the task yet"
8211        );
8212
8213        // A second daemon claims the task and dies before it ever writes
8214        // `running`, well after this loop's own startup sweep already ran.
8215        std::fs::write(
8216            dir.path().join(format!("{}.lock", t.id)),
8217            dead_pid.to_string(),
8218        )
8219        .unwrap();
8220
8221        // Tick two, standing in for a poll long into this daemon's uptime:
8222        // the same function, called again, notices what only just appeared -
8223        // proving the sweep is not a one-shot startup check.
8224        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8225            pid != dead_pid
8226        });
8227        assert_eq!(swept, vec![t.id.clone()]);
8228    }
8229
8230    #[test]
8231    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
8232        // `reclaim_orphaned_running` looks up the task's last run, which
8233        // touches `run::home()`; the first call anywhere in this binary wins,
8234        // so this is a no-op if another test already pinned one, and either
8235        // way the run id below is never written under it.
8236        crate::run::pin_test_home();
8237        let dir = tempfile::tempdir().unwrap();
8238        let queue = Queue::at(dir.path().to_path_buf());
8239        let mut t = task();
8240        t.id = "20260101-000000-crsh".to_owned();
8241        t.status = TaskStatus::Running;
8242        t.attempts = 1;
8243        // No `run.json` behind this id: standing in for a run this test does
8244        // not need to make readable, since the point is the lock, not the
8245        // recovery table `reclaim` already has its own tests for.
8246        t.runs.push("20260904-000000-4043".to_owned());
8247        queue.put(&mut t).unwrap();
8248        let dead_pid = injected_dead_pid();
8249
8250        // The crashed daemon's own claim, naming a pid nothing on the
8251        // machine holds anymore.
8252        std::fs::write(
8253            dir.path().join(format!("{}.lock", t.id)),
8254            dead_pid.to_string(),
8255        )
8256        .unwrap();
8257
8258        // Before the lock is swept the task looks claimed, and
8259        // `reclaim_orphaned_running` must leave it alone - this is exactly
8260        // the bug: a `running` task stranded behind a dead daemon's lock,
8261        // invisible to the claim-as-proof check because the lock outlived
8262        // the process that wrote it.
8263        assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
8264        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
8265
8266        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8267            pid != dead_pid
8268        });
8269        assert_eq!(swept, vec![t.id.clone()]);
8270
8271        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
8272        assert_eq!(reclaimed, vec![t.id.clone()]);
8273        let after = queue.get(&t.id).unwrap();
8274        assert_eq!(
8275            after.status,
8276            TaskStatus::Held,
8277            "no run.json to recover from, so a human is asked"
8278        );
8279        assert_eq!(
8280            after.runs,
8281            vec!["20260904-000000-4043".to_owned()],
8282            "the crashed run's id is kept as evidence, not discarded"
8283        );
8284    }
8285
8286    #[test]
8287    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
8288        let dir = tempfile::tempdir().unwrap();
8289        let queue = Queue::at(dir.path().to_path_buf());
8290        let mut t = task();
8291        t.id = "20260101-000000-unknown".to_owned();
8292        queue.put(&mut t).unwrap();
8293        let dead_pid = injected_dead_pid();
8294        std::fs::write(
8295            dir.path().join(format!("{}.lock", t.id)),
8296            dead_pid.to_string(),
8297        )
8298        .unwrap();
8299
8300        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
8301        assert!(swept.is_empty(), "an unknown pid must keep its lock");
8302        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
8303    }
8304
8305    fn run_state_in(status: RunStatus, language: &str) -> RunState {
8306        let mut s = run_state(status);
8307        s.config.graph.language = language.to_owned();
8308        s
8309    }
8310
8311    fn unstarted_verdict(status: RunStatus) -> Verdict {
8312        Verdict {
8313            status,
8314            left_pr: false,
8315            quota_hit: false,
8316            parked: false,
8317            no_viable_candidates: false,
8318        }
8319    }
8320
8321    #[test]
8322    fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
8323        let mut t = task();
8324        t.attempts = 1;
8325        settle_in(
8326            &mut t,
8327            unstarted_verdict(RunStatus::AlreadyInBase),
8328            "already in main",
8329            1,
8330            phrases("en"),
8331        );
8332        assert_eq!(t.status, TaskStatus::Done);
8333        assert_eq!(t.attempts, 0);
8334    }
8335
8336    #[test]
8337    fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
8338        let reason = |language: &str| {
8339            let mut t = task();
8340            settle_in(
8341                &mut t,
8342                unstarted_verdict(RunStatus::Judging),
8343                "boom",
8344                1,
8345                phrases(language),
8346            );
8347            t.last_error.or(t.hold_reason).unwrap_or_default()
8348        };
8349        assert!(
8350            reason("en").starts_with("the graph stopped at `"),
8351            "{}",
8352            reason("en")
8353        );
8354        assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
8355        assert!(reason("日本語").contains("boom"));
8356        assert_eq!(reason("fr"), reason("en"));
8357    }
8358
8359    #[test]
8360    fn describe_follows_the_run_language_and_keeps_the_run_id() {
8361        let en = describe(&run_state_in(RunStatus::Stalled, "en"));
8362        assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
8363        let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
8364        assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
8365        assert!(ja.contains("[run "), "{ja}");
8366        let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
8367        assert!(ended.starts_with("run 終了: "), "{ended}");
8368        let mut de = run_state_in(RunStatus::Failed, "de");
8369        let mut en = run_state_in(RunStatus::Failed, "en");
8370        de.id = "same".to_owned();
8371        en.id = "same".to_owned();
8372        assert_eq!(describe(&de), describe(&en));
8373    }
8374
8375    #[test]
8376    fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
8377        use crate::handover::Refused;
8378        let cases = [
8379            Refused::Foreign {
8380                branch: "b".into(),
8381                path: "/w/x".into(),
8382                why: "made by hand".into(),
8383            },
8384            Refused::Unsafe {
8385                branch: "b".into(),
8386                path: "/w/x".into(),
8387                why: "its worktree has uncommitted changes (a.rs)".into(),
8388            },
8389            Refused::ReleaseFailed {
8390                branch: "b".into(),
8391                path: "/w/x".into(),
8392                run: "ab12".into(),
8393            },
8394        ];
8395        for r in &cases {
8396            let en = (phrases("en").handover_refused)(r);
8397            assert_eq!(en, r.to_string());
8398            let ja = (phrases("ja").handover_refused)(r);
8399            assert!(
8400                !ja.contains("is checked out") && !ja.contains("try again"),
8401                "{ja}"
8402            );
8403            assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
8404            if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
8405                assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
8406            }
8407        }
8408        assert!(phrases("en").handover_hint.contains("release the task"));
8409        assert!(phrases("ja").handover_hint.contains("解放"));
8410    }
8411
8412    #[test]
8413    fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
8414        let build = |lang: &str| {
8415            let mut s = run_state_in(RunStatus::Blocked, lang);
8416            s.id = "same".to_owned();
8417            s.config.graph.review_rounds = 3;
8418            let mut r = review_round(3);
8419            r.expected = 3;
8420            r.answered = 1;
8421            s.reviews.push(r);
8422            s.event(
8423                "review",
8424                "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
8425            );
8426            s
8427        };
8428        let en = describe(&build("en"));
8429        assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
8430        let ja = describe(&build("ja"));
8431        assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
8432        assert!(!ja.contains("never answered"), "{ja}");
8433        assert!(ja.contains("[run "), "{ja}");
8434
8435        // An incomplete panel whose verification failed is a different stop:
8436        // the real event must survive in ja too.
8437        let mut failed = build("ja");
8438        failed.reviews[0].e2e.push(crate::run::CommandOutcome {
8439            command: "cargo test".to_owned(),
8440            code: Some(1),
8441            output_tail: String::new(),
8442            duration_ms: 0,
8443            resource_blocked: false,
8444        });
8445        failed.event("review", "stopped; e2e failed: cargo test");
8446        let ja = describe(&failed);
8447        assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
8448        assert!(!ja.contains("席のレビュアー"), "{ja}");
8449    }
8450
8451    #[test]
8452    fn refusals_and_recovery_prose_follow_the_language() {
8453        let t = held_task_with("r1");
8454        let q = action_question(
8455            "r1",
8456            ask::ChoiceAction::Resume {
8457                run: "r1".to_owned(),
8458            },
8459        );
8460        let refuse = |p: &Phrases| match decide_action(&t, &q, p, |_: &str| bail!("gone")) {
8461            ActionDecision::Refuse(s) => s,
8462            other => panic!("{other:?}"),
8463        };
8464        assert!(refuse(phrases("en")).contains("could not be read: gone"));
8465        assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
8466        assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
8467
8468        let mut held = task();
8469        reclaim(&mut held, None, 2, "ja");
8470        assert!(held.hold_reason.unwrap().contains("保留にしました"));
8471        let mut held = task();
8472        reclaim(&mut held, None, 2, "xx");
8473        assert!(held.hold_reason.unwrap().contains("held for a human"));
8474    }
8475
8476    fn run_state(status: RunStatus) -> RunState {
8477        let mut state = RunState::new(
8478            PathBuf::from("/repo"),
8479            "main".to_owned(),
8480            "abc1234def".to_owned(),
8481            "add retries".to_owned(),
8482            Config::default(),
8483        );
8484        state.status = status;
8485        state
8486    }
8487
8488    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
8489        Candidate {
8490            index: 0,
8491            label,
8492            agent: "claude".to_owned(),
8493            branch: format!("magi/x/{label}"),
8494            worktree: PathBuf::from("/repo"),
8495            summary: summary.to_owned(),
8496            stat: String::new(),
8497            files: 0,
8498            commits: usize::from(!empty),
8499            empty,
8500            failed: failed.map(str::to_owned),
8501            verified_noop: None,
8502            duration_ms: 0,
8503            folded: false,
8504        }
8505    }
8506
8507    #[test]
8508    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
8509        let mut state = run_state(RunStatus::Blocked);
8510        state.gate = vec![
8511            CommandOutcome {
8512                command: "cargo make check".to_owned(),
8513                code: Some(0),
8514                output_tail: "ok".to_owned(),
8515                duration_ms: 0,
8516                resource_blocked: false,
8517            },
8518            CommandOutcome {
8519                command: "cargo test".to_owned(),
8520                code: Some(101),
8521                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
8522                duration_ms: 0,
8523                resource_blocked: false,
8524            },
8525        ];
8526        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
8527        assert!(d.contains("cargo test"), "{d}");
8528        assert!(
8529            !d.contains("cargo make check"),
8530            "a passing check is not a diagnostic: {d}"
8531        );
8532        assert!(d.contains("assertion failed"), "{d}");
8533    }
8534
8535    #[test]
8536    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
8537        let mut state = run_state(RunStatus::Blocked);
8538        state.event(
8539            "land",
8540            "stopped: the fixer produced no commit while 2 check(s) were failing \
8541             (build, lint); stopping instead of looping on an unchanged tree",
8542        );
8543        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
8544        assert!(d.contains("build"), "{d}");
8545        assert!(d.contains("lint"), "{d}");
8546        assert!(d.contains("fixer produced no commit"), "{d}");
8547    }
8548
8549    #[test]
8550    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
8551        // `describe`'s output becomes `Task::last_error` verbatim, and the
8552        // phone renders that in the same alarm-styled box an ordinary
8553        // failure gets. A bare `verified_noop` there would read exactly like
8554        // the failure this status exists to be told apart from.
8555        let state = run_state(RunStatus::VerifiedNoop);
8556        let d = describe(&state);
8557        assert!(
8558            d.contains("agent-verified no-op"),
8559            "expected the display label, not the wire spelling: {d}"
8560        );
8561        assert!(!d.contains("verified_noop"), "{d}");
8562    }
8563
8564    #[test]
8565    fn diagnostic_keeps_gate_panic_before_large_backtrace() {
8566        let mut state = run_state(RunStatus::Failed);
8567        state.gate.push(crate::run::CommandOutcome {
8568            command: "cargo test".into(),
8569            code: Some(101),
8570            output_tail: format!(
8571                "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
8572                "  41: 0x1234 - backtrace frame\n".repeat(10000)
8573            ),
8574            duration_ms: 1,
8575            resource_blocked: false,
8576        });
8577        let d = diagnostic(&state).unwrap();
8578        assert!(d.contains("panicked at widget.rs:12"), "{d}");
8579        assert!(d.contains("assertion failed: widget missing"));
8580        assert!(d.contains("widget log"));
8581    }
8582
8583    #[test]
8584    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
8585        // The whole point of the feature: a run held as "no candidate produced
8586        // a change" can mean the implementer actually finished the task and
8587        // only left a clean local tree behind - see AGENTS.md on this exact
8588        // failure mode. The diagnostic has to carry what the agent actually
8589        // said, not just the fact that nothing was there to judge.
8590        let mut state = run_state(RunStatus::Failed);
8591        state.candidates = vec![candidate(
8592            'A',
8593            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
8594            true,
8595            None,
8596        )];
8597        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
8598        assert!(d.contains("candidate A"), "{d}");
8599        assert!(d.contains("tagged v1.2.3"), "{d}");
8600    }
8601
8602    #[test]
8603    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
8604        let mut state = run_state(RunStatus::Failed);
8605        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
8606        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
8607        assert!(d.contains("candidate A"), "{d}");
8608        assert!(d.contains("agent timed out"), "{d}");
8609    }
8610
8611    #[test]
8612    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
8613        // A viable candidate existed, the gate never ran, and nothing land
8614        // said matches - `Task::last_error` is left to explain this one alone.
8615        let mut state = run_state(RunStatus::Failed);
8616        state.candidates = vec![candidate('A', "did the work", false, None)];
8617        assert!(diagnostic(&state).is_none());
8618    }
8619
8620    #[test]
8621    fn diagnostic_is_bounded_however_much_a_run_printed() {
8622        let mut state = run_state(RunStatus::Blocked);
8623        state.gate = vec![
8624            CommandOutcome {
8625                command: "cargo test".to_owned(),
8626                code: Some(101),
8627                output_tail: "x".repeat(50_000),
8628                duration_ms: 0,
8629                resource_blocked: false,
8630            },
8631            CommandOutcome {
8632                command: "cargo clippy".to_owned(),
8633                code: Some(1),
8634                output_tail: "y".repeat(50_000),
8635                duration_ms: 0,
8636                resource_blocked: false,
8637            },
8638        ];
8639        state.candidates = vec![
8640            candidate('A', &"z".repeat(50_000), true, None),
8641            candidate('B', &"w".repeat(50_000), true, None),
8642        ];
8643        let d = diagnostic(&state).expect("plenty here to diagnose");
8644        assert!(
8645            d.len() <= DIAGNOSTIC_MAX,
8646            "diagnostic grew to {} bytes, unbounded",
8647            d.len()
8648        );
8649    }
8650
8651    #[test]
8652    fn selected_delivery_guards_survive_recovery_failure_accounting() {
8653        for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
8654            let mut t = task();
8655            let mut state = run_state(status);
8656            t.pr_recovery = Some(crate::pr_recovery::Selection {
8657                url: "url".into(),
8658                branch: format!("magi/task-{}", t.id),
8659                head: "a".repeat(40),
8660                source_head: None,
8661                source_run: None,
8662                source_proof: None,
8663                disposition: Some(crate::pr_recovery::Disposition::Land),
8664                instruction: t.instruction.clone(),
8665                approved_at: Timestamp::now(),
8666            });
8667            state.pr_recovery = t.pr_recovery.clone();
8668            t.start(state.id.clone());
8669            settle_and_diagnose(
8670                &mut t,
8671                Verdict {
8672                    status,
8673                    left_pr: false,
8674                    quota_hit: false,
8675                    parked: false,
8676                    no_viable_candidates: false,
8677                },
8678                "delivery stopped",
8679                5,
8680                &state,
8681            );
8682            assert_eq!(t.status, TaskStatus::Held);
8683            let reason = t.hold_reason.as_deref().unwrap();
8684            if status == RunStatus::Ready {
8685                assert!(reason.contains("Selected PR delivery is incomplete"));
8686                assert!(t.recovery_budget.is_none());
8687            } else {
8688                assert!(reason.contains("Selected recovery stopped"));
8689                assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
8690            }
8691            assert!(t.pr_recovery.is_some());
8692        }
8693    }
8694
8695    #[test]
8696    fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
8697        let mut state = run_state(RunStatus::Voting);
8698        state.base_sync = Some(crate::run::BaseSync {
8699            tip: "base-tip".into(),
8700            behind: 3,
8701            attempts: 4,
8702            conflict: Some("base stopped".into()),
8703            already_in: None,
8704        });
8705        state.record_base_sync_stop("candidate-head");
8706        let mut t = task();
8707        t.start(state.id.clone());
8708        let verdict = Verdict {
8709            status: RunStatus::Blocked,
8710            left_pr: false,
8711            quota_hit: false,
8712            parked: false,
8713            no_viable_candidates: false,
8714        };
8715        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
8716        assert_eq!(
8717            t.status,
8718            TaskStatus::Held,
8719            "unspent task attempts cannot start another competition"
8720        );
8721        let at = t.held_at;
8722        let cause = t.hold_notice_cause.clone();
8723        state.begin_pass();
8724        t.release_operator("test-resume", None);
8725        t.start(state.id.clone());
8726        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
8727        assert_eq!(t.status, TaskStatus::Held);
8728        assert_eq!(t.held_at, at);
8729        assert_eq!(t.hold_notice_cause, cause);
8730    }
8731
8732    #[test]
8733    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
8734        let mut state = run_state(RunStatus::Blocked);
8735        state.gate = vec![CommandOutcome {
8736            command: "cargo test".to_owned(),
8737            code: Some(101),
8738            output_tail: "assertion failed".to_owned(),
8739            duration_ms: 0,
8740            resource_blocked: false,
8741        }];
8742        let verdict = Verdict {
8743            status: RunStatus::Blocked,
8744            left_pr: false,
8745            quota_hit: false,
8746            parked: false,
8747            no_viable_candidates: false,
8748        };
8749
8750        // Attempt one of two still has a retry coming: no diagnostic yet, the
8751        // task is going to run again and this run's evidence would go stale.
8752        let mut t = task();
8753        t.start("run-1".to_owned());
8754        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
8755        assert_eq!(t.status, TaskStatus::Failed);
8756        assert!(t.diagnostic.is_none());
8757
8758        // Attempt two exhausts the budget: now it is held, and the
8759        // diagnostic is what `magi task show` has to say more than one line.
8760        t.start("run-2".to_owned());
8761        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
8762        assert_eq!(t.status, TaskStatus::Held);
8763        let d = t.diagnostic.expect("a held task must carry its diagnostic");
8764        assert!(d.contains("cargo test"), "{d}");
8765    }
8766
8767    #[test]
8768    fn a_held_task_names_the_open_question_it_is_waiting_on() {
8769        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
8770        // `magi ask` question settled Held with `hold_reason: null`, so the
8771        // notification said nothing actionable. `note_open_question` should
8772        // append the question id to whatever `handed_off` already wrote.
8773        crate::run::pin_test_home();
8774        let home = crate::run::home();
8775        let state = run_state(RunStatus::VerifiedNoop);
8776        let mut q = ask::Question::new(
8777            state.id.clone(),
8778            "implement".to_owned(),
8779            "impl-A".to_owned(),
8780            "is this really a no-op?".to_owned(),
8781            String::new(),
8782            Vec::new(),
8783        );
8784        Questions::at(home.join("questions")).put(&mut q).unwrap();
8785
8786        let verdict = Verdict {
8787            status: RunStatus::VerifiedNoop,
8788            left_pr: false,
8789            quota_hit: false,
8790            parked: false,
8791            no_viable_candidates: false,
8792        };
8793        let mut t = task();
8794        t.start(state.id.clone());
8795        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
8796
8797        assert_eq!(t.status, TaskStatus::Held);
8798        let reason = t.hold_reason.expect("a held task must record why");
8799        assert!(
8800            reason.starts_with("run ended agent-verified no-op"),
8801            "the original settle reason must survive unchanged: {reason}"
8802        );
8803        assert!(
8804            reason.contains(q.short()),
8805            "the open question's id must be named so the notice is actionable: {reason}"
8806        );
8807    }
8808
8809    #[test]
8810    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
8811        crate::run::pin_test_home();
8812        let state = run_state(RunStatus::VerifiedNoop);
8813
8814        let verdict = Verdict {
8815            status: RunStatus::VerifiedNoop,
8816            left_pr: false,
8817            quota_hit: false,
8818            parked: false,
8819            no_viable_candidates: false,
8820        };
8821        let mut t = task();
8822        t.start(state.id.clone());
8823        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
8824
8825        assert_eq!(t.status, TaskStatus::Held);
8826        assert_eq!(
8827            t.hold_reason.as_deref(),
8828            Some("run ended agent-verified no-op"),
8829            "nothing to append when the question was already answered or never asked"
8830        );
8831    }
8832
8833    #[test]
8834    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
8835        crate::run::pin_test_home();
8836        let mut first = run_state(RunStatus::Blocked);
8837        first.id = "20260101-000000-sup1".to_owned();
8838        first.save().unwrap();
8839        let mut second = run_state(RunStatus::Merged);
8840        second.id = "20260101-000000-sup2".to_owned();
8841        second.save().unwrap();
8842
8843        let mut t = task();
8844        t.runs = vec![first.id.clone(), second.id.clone()];
8845        t.status = TaskStatus::Done;
8846
8847        supersede_prior_runs(&t, &crate::run::home());
8848
8849        assert_eq!(
8850            RunState::load(&first.id).unwrap().status,
8851            RunStatus::Superseded,
8852            "the first attempt's Blocked no longer needs anyone's attention"
8853        );
8854        assert_eq!(
8855            RunState::load(&second.id).unwrap().status,
8856            RunStatus::Merged,
8857            "the run that actually succeeded is left exactly as it was"
8858        );
8859    }
8860
8861    #[test]
8862    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
8863        // `is_working_on` alone only proves a *daemon* claim; a `magi run
8864        // --resume` invoked by hand outside the daemon never touches
8865        // `daemon.json` at all, so it would look identical to a genuinely
8866        // idle run without also consulting `RunState::liveness`, which reads
8867        // this run's own recorded `driver_pid` instead.
8868        crate::run::pin_test_home();
8869        let mut first = run_state(RunStatus::Blocked);
8870        first.id = "20260101-000000-sup9".to_owned();
8871        // This test process's own pid: guaranteed alive without needing a
8872        // real second process or daemon.
8873        first.driver_pid = Some(std::process::id());
8874        first.driver_started_at = Some(
8875            crate::proc::process_started_at(std::process::id())
8876                .expect("this test process's own start time must be queryable"),
8877        );
8878        first.save().unwrap();
8879        let mut second = run_state(RunStatus::Merged);
8880        second.id = "20260101-000000-supa".to_owned();
8881        second.save().unwrap();
8882
8883        let mut t = task();
8884        t.runs = vec![first.id.clone(), second.id.clone()];
8885        t.status = TaskStatus::Done;
8886
8887        supersede_prior_runs(&t, &crate::run::home());
8888
8889        assert_eq!(
8890            RunState::load(&first.id).unwrap().status,
8891            RunStatus::Blocked,
8892            "a live driver_pid means something is still actually working this run, \
8893             even though no daemon claims it - rewriting under it would just be \
8894             undone the next time that process saves"
8895        );
8896    }
8897
8898    #[test]
8899    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
8900        // The first resweep must skip a still-live attempt exactly like
8901        // `supersede_prior_runs` itself does; a later resweep, once that
8902        // process is no longer actually driving it, is what closes the gap
8903        // `supersede_prior_runs` alone leaves - a task only ever reaches
8904        // `Done` once, so nothing else would ever look at this run again.
8905        let dir = tempfile::tempdir().unwrap();
8906        let home = dir.path().to_path_buf();
8907        let queue = Queue::at(dir.path().join("queue"));
8908
8909        let mut first = run_state(RunStatus::Blocked);
8910        first.id = "20260101-000000-supd".to_owned();
8911        first.driver_pid = Some(std::process::id());
8912        first.driver_started_at = Some(
8913            crate::proc::process_started_at(std::process::id())
8914                .expect("this test process's own start time must be queryable"),
8915        );
8916        first.save_under(&home).unwrap();
8917        let mut second = run_state(RunStatus::Merged);
8918        second.id = "20260101-000000-supe".to_owned();
8919        second.save_under(&home).unwrap();
8920
8921        let mut t = task();
8922        t.runs = vec![first.id.clone(), second.id.clone()];
8923        t.status = TaskStatus::Done;
8924        queue.put(&mut t).unwrap();
8925
8926        resweep_superseded_attempts(&queue, &home);
8927        assert_eq!(
8928            RunState::load_under(&first.id, &home).unwrap().status,
8929            RunStatus::Blocked,
8930            "still live on the first pass, so still untouched"
8931        );
8932
8933        // Stand in for the manual process no longer being the one driving
8934        // this run: same pid (this test process really is still alive), but
8935        // an identity marker that no longer matches it - see
8936        // `RunState::liveness`'s own doc for why a mismatched
8937        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
8938        let mut stale = RunState::load_under(&first.id, &home).unwrap();
8939        stale.driver_started_at = Some("1".to_owned());
8940        stale.save_under(&home).unwrap();
8941
8942        resweep_superseded_attempts(&queue, &home);
8943        assert_eq!(
8944            RunState::load_under(&first.id, &home).unwrap().status,
8945            RunStatus::Superseded,
8946            "the second pass catches up what the first one correctly skipped"
8947        );
8948    }
8949
8950    #[test]
8951    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
8952        crate::run::pin_test_home();
8953        let mut first = run_state(RunStatus::Blocked);
8954        first.id = "20260101-000000-sup3".to_owned();
8955        first.save().unwrap();
8956        let mut second = run_state(RunStatus::Blocked);
8957        second.id = "20260101-000000-sup4".to_owned();
8958        second.save().unwrap();
8959
8960        let mut t = task();
8961        t.runs = vec![first.id.clone(), second.id.clone()];
8962        // Still retrying: nothing about this task's story is settled yet, so
8963        // neither Blocked run may be relabelled, even though a later attempt
8964        // already exists.
8965        t.status = TaskStatus::Failed;
8966
8967        supersede_prior_runs(&t, &crate::run::home());
8968
8969        assert_eq!(
8970            RunState::load(&first.id).unwrap().status,
8971            RunStatus::Blocked
8972        );
8973        assert_eq!(
8974            RunState::load(&second.id).unwrap().status,
8975            RunStatus::Blocked
8976        );
8977    }
8978
8979    #[test]
8980    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
8981        // `magi task done` (or the API's equivalent) can close a task with no
8982        // run of its own ever having succeeded - there is nothing here that
8983        // counts as "the attempt that finished it", so nothing is rewritten.
8984        crate::run::pin_test_home();
8985        let mut first = run_state(RunStatus::Blocked);
8986        first.id = "20260101-000000-sup5".to_owned();
8987        first.save().unwrap();
8988
8989        let mut t = task();
8990        t.runs = vec![first.id.clone()];
8991        t.status = TaskStatus::Done;
8992
8993        supersede_prior_runs(&t, &crate::run::home());
8994
8995        assert_eq!(
8996            RunState::load(&first.id).unwrap().status,
8997            RunStatus::Blocked,
8998            "a single-attempt task has no earlier run to supersede"
8999        );
9000    }
9001
9002    #[test]
9003    fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
9004        // `magi task done` (or the web/conductor equivalents) can close a
9005        // task in any status, including one whose *last* recorded attempt is
9006        // itself still `Blocked`/`Failed` - a manual merge magi's own loop
9007        // never watched, say. `runs.last()` being `Done`-adjacent is not
9008        // proof it actually succeeded, so nothing earlier may be relabelled
9009        // on its say-so alone.
9010        crate::run::pin_test_home();
9011        let mut first = run_state(RunStatus::Blocked);
9012        first.id = "20260101-000000-supb".to_owned();
9013        first.save().unwrap();
9014        let mut second = run_state(RunStatus::Failed);
9015        second.id = "20260101-000000-supc".to_owned();
9016        second.save().unwrap();
9017
9018        let mut t = task();
9019        t.runs = vec![first.id.clone(), second.id.clone()];
9020        t.status = TaskStatus::Done;
9021
9022        supersede_prior_runs(&t, &crate::run::home());
9023
9024        assert_eq!(
9025            RunState::load(&first.id).unwrap().status,
9026            RunStatus::Blocked,
9027            "the task's last attempt never landed, so there is nothing here \
9028             actually superseding it"
9029        );
9030    }
9031
9032    #[test]
9033    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
9034        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
9035        // to look" - `Failed` and `VerifiedNoop` are already their own
9036        // terminal answers and must not be relabelled into a third one.
9037        crate::run::pin_test_home();
9038        let mut failed = run_state(RunStatus::Failed);
9039        failed.id = "20260101-000000-sup6".to_owned();
9040        failed.save().unwrap();
9041        let mut noop = run_state(RunStatus::VerifiedNoop);
9042        noop.id = "20260101-000000-sup7".to_owned();
9043        noop.save().unwrap();
9044        let mut winner = run_state(RunStatus::Ready);
9045        winner.id = "20260101-000000-sup8".to_owned();
9046        winner.save().unwrap();
9047
9048        let mut t = task();
9049        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
9050        t.status = TaskStatus::Done;
9051
9052        supersede_prior_runs(&t, &crate::run::home());
9053
9054        assert_eq!(
9055            RunState::load(&failed.id).unwrap().status,
9056            RunStatus::Failed
9057        );
9058        assert_eq!(
9059            RunState::load(&noop.id).unwrap().status,
9060            RunStatus::VerifiedNoop
9061        );
9062    }
9063
9064    fn approval_question(run: &str) -> ask::Question {
9065        ask::Question::new(
9066            run.to_owned(),
9067            land::APPROVAL_NODE.to_owned(),
9068            "land".to_owned(),
9069            "merge?".to_owned(),
9070            String::new(),
9071            vec!["merge".to_owned(), "hold".to_owned()],
9072        )
9073    }
9074
9075    #[test]
9076    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
9077        crate::run::pin_test_home();
9078        let mut state = run_state(RunStatus::Landing);
9079        state.id = "20260101-000000-fre1".to_owned();
9080        state.parked = true;
9081        state.save().unwrap();
9082        ask::Questions::open()
9083            .put(&mut approval_question(&state.id))
9084            .unwrap();
9085
9086        let mut t = task();
9087        t.runs.push(state.id.clone());
9088        assert_eq!(
9089            land_resume_state(&t),
9090            LandResume::StillWaiting,
9091            "nobody has answered and the timeout has not passed"
9092        );
9093    }
9094
9095    #[test]
9096    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
9097        crate::run::pin_test_home();
9098        let mut state = run_state(RunStatus::Gating);
9099        state.id = "20260101-000000-gt01".to_owned();
9100        state.parked = true;
9101        state.config.graph.answer_timeout = 60;
9102        state.github_text = Some(crate::run::GithubTextAsk {
9103            rewrite: None,
9104            fingerprint: "f".into(),
9105            title: true,
9106            body: false,
9107            categories: vec!["title-language".into()],
9108            question: None,
9109            asks: 1,
9110            resolved: false,
9111            chosen_title: None,
9112            choice: None,
9113        });
9114        state.save().unwrap();
9115        let store = ask::Questions::open();
9116        let mut q = ask::Question::new(
9117            state.id.clone(),
9118            crate::github_text::ASK_NODE.to_owned(),
9119            crate::github_text::ASK_SEAT.to_owned(),
9120            "s".into(),
9121            String::new(),
9122            vec!["use fallback".into()],
9123        );
9124        store.put(&mut q).unwrap();
9125        let mut t = task();
9126        t.runs.push(state.id.clone());
9127        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
9128        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9129        store.put(&mut q).unwrap();
9130        assert_eq!(land_resume_state(&t), LandResume::Ready);
9131        assert!(!store.get(&q.id).unwrap().status.open());
9132        // Once decided, a parked run is an ordinary candidate again.
9133        state.github_text.as_mut().unwrap().resolved = true;
9134        state.save().unwrap();
9135        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
9136    }
9137
9138    #[test]
9139    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
9140        // `ask::ask_and_wait`'s own deadline used to retire a question
9141        // nobody answered; land's approval bypasses that wait (see
9142        // `land::approval_gate`), so this is now the only place
9143        // `graph.answer_timeout` is enforced for a land approval at all.
9144        crate::run::pin_test_home();
9145        let mut state = run_state(RunStatus::Landing);
9146        state.id = "20260101-000000-exp1".to_owned();
9147        state.parked = true;
9148        state.config.graph.answer_timeout = 60;
9149        state.save().unwrap();
9150
9151        let store = ask::Questions::open();
9152        let mut q = approval_question(&state.id);
9153        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9154        store.put(&mut q).unwrap();
9155
9156        let mut t = task();
9157        t.runs.push(state.id.clone());
9158        assert_eq!(
9159            land_resume_state(&t),
9160            LandResume::Ready,
9161            "an expired question must not be waited on forever"
9162        );
9163
9164        let after = store.get(&q.id).unwrap();
9165        assert!(
9166            !after.status.open(),
9167            "the question is abandoned, not silently ignored"
9168        );
9169        assert!(
9170            after.resolution().is_none(),
9171            "an abandoned question is not read as a decision"
9172        );
9173    }
9174
9175    #[test]
9176    fn reclaim_settles_a_running_task_against_its_last_run() {
9177        let mut t = task();
9178        t.start("20260904-000000-4043".to_owned());
9179        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
9180        assert_eq!(
9181            t.status,
9182            TaskStatus::Done,
9183            "a run that actually finished must not stay `running` forever"
9184        );
9185    }
9186
9187    #[test]
9188    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
9189        let mut t = task();
9190        t.start("20260904-000000-4043".to_owned());
9191        t.last_error = Some("earlier trouble".to_owned());
9192        let mut state = run_state(RunStatus::Judging);
9193        state.parked = true;
9194        reclaim(&mut t, Some(state), 1, "en");
9195        assert_eq!(t.status, TaskStatus::Parked);
9196        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
9197        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9198        assert!(t.park_reason.is_some());
9199        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
9200        assert!(!t.fresh_start);
9201        assert!(t.status.runnable());
9202    }
9203
9204    #[test]
9205    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
9206        let mut t = task();
9207        t.start("20260904-000000-4043".to_owned());
9208        t.last_error = Some("earlier trouble".to_owned());
9209        settle(
9210            &mut t,
9211            Verdict {
9212                status: RunStatus::Judging,
9213                left_pr: false,
9214                quota_hit: false,
9215                parked: true,
9216                no_viable_candidates: false,
9217            },
9218            "parked after `judging`",
9219            1,
9220        );
9221        assert_eq!(t.status, TaskStatus::Parked);
9222        assert_eq!(t.attempts, 0);
9223        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9224        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
9225        assert_eq!(t.schema, crate::queue::SCHEMA);
9226        assert!(
9227            crate::notices::task_held(&t).is_none(),
9228            "a park is not news"
9229        );
9230        t.start("20260904-000000-4043".to_owned());
9231        assert_eq!(t.park_reason, None);
9232    }
9233
9234    #[test]
9235    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
9236        // A blocked run with attempts left goes back to `Failed`, exactly as
9237        // it would from `attempt` itself - `reclaim` must not invent a second
9238        // policy for a task a daemon merely stopped without reporting.
9239        let mut t = task();
9240        t.start("20260904-000000-4043".to_owned());
9241        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
9242        assert_eq!(t.status, TaskStatus::Failed);
9243        assert!(t.status.runnable());
9244    }
9245
9246    #[test]
9247    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
9248        let mut t = task();
9249        t.start("20260904-000000-4043".to_owned());
9250        assert_eq!(t.attempts, 1);
9251        let mut run = run_state(RunStatus::Implementing);
9252        run.id = "20260904-000000-4043".to_owned();
9253        run.begin_pass();
9254        let cause = crate::run::ParkCause::Upgrade {
9255            from: "0.121.0".to_owned(),
9256            to: Some("0.121.1".to_owned()),
9257        };
9258        run.end_pass_parked(cause.clone());
9259        run.parked = true;
9260        let verdict = Verdict {
9261            status: run.status,
9262            left_pr: false,
9263            quota_hit: false,
9264            parked: true,
9265            no_viable_candidates: false,
9266        };
9267        // A crash after the checkpoint but before queue settlement must
9268        // recover exactly the same scheduling evidence and refund.
9269        let mut orphan = t.clone();
9270        reclaim(&mut orphan, Some(run.clone()), 2, "en");
9271        assert_eq!(orphan.status, TaskStatus::Parked);
9272        assert_eq!(orphan.attempts, 0);
9273        assert_eq!(
9274            orphan.upgrade_resume_key(),
9275            Some((run.passes[0].started_at, orphan.id.as_str()))
9276        );
9277        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
9278        assert_eq!(t.attempts, 0);
9279        assert_eq!(t.passes.len(), 1);
9280        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9281        assert_eq!(t.passes[0].parked, Some(cause));
9282        assert_eq!(t.passes[0].pass_index, 0);
9283        assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
9284        assert!(t.upgrade_resume_key().is_some());
9285
9286        // A resumed pass that then fails spends its attempt, and the earlier
9287        // pass's entry is untouched.
9288        t.start("20260904-000000-4043".to_owned());
9289        run.begin_pass();
9290        run.status = RunStatus::Failed;
9291        let verdict = Verdict {
9292            status: RunStatus::Failed,
9293            left_pr: false,
9294            quota_hit: false,
9295            parked: false,
9296            no_viable_candidates: false,
9297        };
9298        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
9299        assert_eq!(t.passes.len(), 2);
9300        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9301        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
9302        assert_eq!(t.passes[1].pass_index, 1);
9303        assert_eq!(t.attempts, 1);
9304    }
9305
9306    #[test]
9307    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
9308        let mut t = task();
9309        t.start("20260904-000000-4043".to_owned());
9310        reclaim(&mut t, None, 2, "en");
9311        assert_eq!(t.status, TaskStatus::Held);
9312        assert!(
9313            t.last_error
9314                .as_deref()
9315                .is_some_and(|e| e.contains("running")),
9316            "the operator needs to know why this task was held"
9317        );
9318    }
9319
9320    #[test]
9321    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
9322        let dir = tempfile::tempdir().unwrap();
9323        let queue = Queue::at(dir.path().to_path_buf());
9324
9325        // No run recorded, so this never has to touch `RunState::load`.
9326        let mut orphaned = task();
9327        orphaned.id = "20260904-000000-orph".to_owned();
9328        orphaned.status = TaskStatus::Running;
9329        orphaned.attempts = 1;
9330        queue.put(&mut orphaned).unwrap();
9331
9332        let mut alive = task();
9333        alive.id = "20260904-000000-live".to_owned();
9334        alive.status = TaskStatus::Running;
9335        alive.attempts = 1;
9336        queue.put(&mut alive).unwrap();
9337        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
9338
9339        let mut queued = task();
9340        queued.id = "20260904-000000-wait".to_owned();
9341        queue.put(&mut queued).unwrap();
9342
9343        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
9344        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
9345
9346        assert_eq!(
9347            queue.get(&orphaned.id).unwrap().status,
9348            TaskStatus::Held,
9349            "nothing was driving it and there was no run to recover"
9350        );
9351        assert_eq!(
9352            queue.get(&alive.id).unwrap().status,
9353            TaskStatus::Running,
9354            "a live claim must protect the task it belongs to"
9355        );
9356        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
9357    }
9358
9359    /// Read a run.json back from an explicit `home`, the same way
9360    /// `reclaim_abandoned_runs` itself does - never through the
9361    /// process-global `RunState::load`, which this test's own `home` (an
9362    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
9363    /// use at all.
9364    fn read_run_under(home: &Path, id: &str) -> RunState {
9365        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
9366        serde_json::from_str(&body).unwrap()
9367    }
9368
9369    #[test]
9370    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
9371        let dir = tempfile::tempdir().unwrap();
9372        let home = dir.path().to_path_buf();
9373        let now = Timestamp::now();
9374        let overrun_seat = || crate::run::ActiveSeat {
9375            node: "implement".to_owned(),
9376            started_at: now - jiff::SignedDuration::new(21_000, 0),
9377            timeout_secs: 3_600,
9378            attempt: 0,
9379            task: None,
9380            command: None,
9381            index: None,
9382            total: None,
9383        };
9384
9385        let mut dead = run_state(RunStatus::Implementing);
9386        dead.id = "20260101-000000-dead".to_owned();
9387        dead.active.insert("impl-A".to_owned(), overrun_seat());
9388        // A `driver_pid` the injected query below confirms gone outright —
9389        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
9390        dead.driver_pid = Some(4242);
9391        dead.save_under(&home).unwrap();
9392
9393        // Same shape, but a live daemon's heartbeat names it: must be left
9394        // exactly alone, however far past its own timeout the seat sits.
9395        let mut alive = run_state(RunStatus::Implementing);
9396        alive.id = "20260101-000000-aliv".to_owned();
9397        alive.active.insert("impl-A".to_owned(), overrun_seat());
9398        alive.save_under(&home).unwrap();
9399        let mut status = Status::new();
9400        status.current = vec![Current {
9401            worker: None,
9402            task: "20260101-000000-task".to_owned(),
9403            run: alive.id.clone(),
9404        }];
9405        write_status_to(&home.join("daemon.json"), &status).unwrap();
9406
9407        // The abandoned seat left an open question behind: nobody is left to
9408        // read an answer once the run is failed, and this must not wait for
9409        // some later daemon startup's own sweep to notice that.
9410        let questions = Questions::at(home.join("questions"));
9411        let mut q = ask::Question::new(
9412            dead.id.clone(),
9413            "implement".to_owned(),
9414            "impl-A".to_owned(),
9415            "Which storage backend?".to_owned(),
9416            String::new(),
9417            vec!["SQLite".to_owned(), "Redis".to_owned()],
9418        );
9419        questions.put(&mut q).unwrap();
9420
9421        let abandoned = reclaim_abandoned_runs_with(
9422            &home,
9423            now,
9424            |pid| if pid == 4242 { Some(false) } else { None },
9425            |_| panic!("a query answering Dead outright needs no identity corroboration"),
9426        );
9427        assert_eq!(abandoned, vec![dead.id.clone()]);
9428
9429        let reloaded = read_run_under(&home, &dead.id);
9430        assert_eq!(reloaded.status, RunStatus::Failed);
9431        assert!(reloaded.active.is_empty());
9432        assert!(
9433            !questions.get(&q.id).unwrap().status.open(),
9434            "the failed run's own open question must be settled in the same pass"
9435        );
9436
9437        let still_alive = read_run_under(&home, &alive.id);
9438        assert_eq!(
9439            still_alive.status,
9440            RunStatus::Implementing,
9441            "a live daemon's claim protects it"
9442        );
9443        assert!(!still_alive.active.is_empty());
9444    }
9445
9446    /// The exact shape a review round flagged as broken: `magi serve` running
9447    /// in this same `home` scans *every* run on disk, including a manual
9448    /// `magi review` / `magi run` this daemon never started and that
9449    /// therefore claims no heartbeat of its own. Before this scan asked
9450    /// `liveness` rather than just `is_working_on`, a manual run whose active
9451    /// seat merely ran a little past its own timeout — the CLI finishing up,
9452    /// its result still being collected — got wiped and failed by a daemon
9453    /// that had nothing to do with it, out from under a process that was
9454    /// still very much running.
9455    #[test]
9456    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
9457        let dir = tempfile::tempdir().unwrap();
9458        let home = dir.path().to_path_buf();
9459        let now = Timestamp::now();
9460
9461        let mut manual = run_state(RunStatus::Reviewing);
9462        manual.id = "20260101-000000-manl".to_owned();
9463        manual.active.insert(
9464            "review-1".to_owned(),
9465            crate::run::ActiveSeat {
9466                node: "review".to_owned(),
9467                started_at: now - jiff::SignedDuration::new(21_000, 0),
9468                timeout_secs: 3_600,
9469                attempt: 0,
9470                task: None,
9471                command: None,
9472                index: None,
9473                total: None,
9474            },
9475        );
9476        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
9477        // but a real, still-running process: `liveness` must corroborate this
9478        // as `Live`, not read the missing daemon claim as death.
9479        manual.driver_pid = Some(4242);
9480        manual.driver_started_at = Some("1790000000".to_owned());
9481        manual.save_under(&home).unwrap();
9482
9483        let abandoned = reclaim_abandoned_runs_with(
9484            &home,
9485            now,
9486            |pid| if pid == 4242 { Some(true) } else { None },
9487            |pid| {
9488                if pid == 4242 {
9489                    Some("1790000000".to_owned())
9490                } else {
9491                    None
9492                }
9493            },
9494        );
9495        assert!(
9496            abandoned.is_empty(),
9497            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
9498        );
9499
9500        let reloaded = read_run_under(&home, &manual.id);
9501        assert_eq!(reloaded.status, RunStatus::Reviewing);
9502        assert!(!reloaded.active.is_empty());
9503    }
9504
9505    #[test]
9506    fn an_already_claimed_task_is_skipped_rather_than_failed() {
9507        let dir = tempfile::tempdir().unwrap();
9508        let queue = Queue::at(dir.path().to_path_buf());
9509        let mut only = task();
9510        queue.put(&mut only).unwrap();
9511
9512        let _elsewhere = queue.claim(&only.id).unwrap();
9513        let candidates = runnable(&queue);
9514        assert_eq!(candidates.len(), 1, "the task is still runnable");
9515        assert!(
9516            queue.claim(&candidates[0].id).is_err(),
9517            "the loop cannot take a claim somebody else holds"
9518        );
9519
9520        let after = queue.get(&only.id).unwrap();
9521        assert_eq!(after.status, TaskStatus::Queued);
9522        assert_eq!(
9523            after.attempts, 0,
9524            "losing the race is not an attempt at the task"
9525        );
9526        assert_eq!(after.last_error, None);
9527    }
9528
9529    #[test]
9530    fn the_status_file_round_trips_and_its_heartbeat_advances() {
9531        let dir = tempfile::tempdir().unwrap();
9532        let path = dir.path().join("daemon.json");
9533
9534        let mut status = Status::new();
9535        status.idle = false;
9536        status.completed = 7;
9537        status.current = vec![Current {
9538            worker: None,
9539            task: "20260902-000000-t111".to_owned(),
9540            run: "20260902-000001-r111".to_owned(),
9541        }];
9542        write_status_to(&path, &status).unwrap();
9543        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9544        assert_eq!(first.schema, SCHEMA);
9545        assert_eq!(first.pid, std::process::id());
9546        assert!(!first.idle);
9547        assert_eq!(first.completed, 7);
9548        assert_eq!(first.current, status.current);
9549        assert!(
9550            !path.with_extension("json.tmp").exists(),
9551            "the temp file is renamed, not left behind"
9552        );
9553
9554        std::thread::sleep(Duration::from_millis(5));
9555        status.updated_at = Timestamp::now();
9556        status.polls = 3;
9557        write_status_to(&path, &status).unwrap();
9558        let second: Status =
9559            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9560        assert!(
9561            second.updated_at > first.updated_at,
9562            "a reader can only detect staleness if the heartbeat moves"
9563        );
9564        assert_eq!(
9565            second.started_at, first.started_at,
9566            "the start time is not a heartbeat"
9567        );
9568        assert_eq!(second.polls, 3);
9569    }
9570
9571    #[test]
9572    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
9573        let dir = tempfile::tempdir().unwrap();
9574
9575        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
9576
9577        let mut status = Status::new();
9578        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
9579        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9580        let stale = read_status(dir.path()).unwrap();
9581        assert!(
9582            !stale.running(Timestamp::now()),
9583            "a minute without a heartbeat is a dead daemon, not a busy one"
9584        );
9585        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
9586
9587        status.updated_at = Timestamp::now();
9588        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9589        let fresh = read_status(dir.path()).unwrap();
9590        assert!(fresh.running(Timestamp::now()));
9591    }
9592
9593    #[test]
9594    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
9595        let dir = tempfile::tempdir().unwrap();
9596        let now = Timestamp::now();
9597        let mine = "20260903-080619-01c2";
9598
9599        assert!(
9600            !is_working_on(dir.path(), mine, now),
9601            "no status file means nobody is working on anything"
9602        );
9603
9604        let mut status = Status::new();
9605        status.current = vec![Current {
9606            worker: None,
9607            task: "20260903-080340-0167".to_owned(),
9608            run: mine.to_owned(),
9609        }];
9610        status.updated_at = now;
9611        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9612        assert!(is_working_on(dir.path(), mine, now));
9613        assert!(
9614            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
9615            "a daemon busy with one run is not working on another"
9616        );
9617
9618        // A killed daemon stops writing heartbeats but leaves the file behind
9619        // naming the run it died in. That run must not be undeletable forever.
9620        status.updated_at = now - jiff::SignedDuration::from_secs(600);
9621        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9622        assert!(
9623            !is_working_on(dir.path(), mine, now),
9624            "a stale heartbeat is a dead daemon, so its run is a leftover"
9625        );
9626    }
9627
9628    #[test]
9629    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
9630        let dir = tempfile::tempdir().unwrap();
9631        let now = Timestamp::now();
9632
9633        assert!(
9634            !is_working_on_short(dir.path(), "01c2", now),
9635            "no status file means nobody is working on anything"
9636        );
9637
9638        let mut status = Status::new();
9639        status.current = vec![Current {
9640            worker: None,
9641            task: "20260903-080340-0167".to_owned(),
9642            run: "20260903-080619-01c2".to_owned(),
9643        }];
9644        status.updated_at = now;
9645        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9646        assert!(
9647            is_working_on_short(dir.path(), "01c2", now),
9648            "the run's short id is the last block of its full id"
9649        );
9650        assert!(
9651            !is_working_on_short(dir.path(), "3cbf", now),
9652            "a daemon busy with one worktree bay is not working on another"
9653        );
9654    }
9655
9656    #[test]
9657    fn a_newer_status_file_still_yields_a_reading() {
9658        let dir = tempfile::tempdir().unwrap();
9659        // A field this build has never heard of must not turn the reading into
9660        // nothing at all; that is the whole reason the reader is permissive.
9661        std::fs::write(
9662            dir.path().join("daemon.json"),
9663            serde_json::json!({
9664                "schema": 2,
9665                "updated_at": Timestamp::now().to_string(),
9666                "idle": true,
9667                "surprise": { "nested": [1, 2, 3] },
9668            })
9669            .to_string(),
9670        )
9671        .unwrap();
9672
9673        let reading = read_status(dir.path()).expect("a forward-compatible read");
9674        assert!(reading.running(Timestamp::now()));
9675        assert!(reading.idle);
9676        assert!(reading.current.is_empty());
9677    }
9678
9679    #[test]
9680    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
9681        // A daemon started before `current` became a list keeps writing this
9682        // shape on every heartbeat until it is restarted. A rolling upgrade
9683        // - a newer `magi web` or `magi doctor` reading an older `magi
9684        // serve`'s heartbeat - must still see the run it is on, not "no
9685        // daemon" from a type mismatch failing the whole struct.
9686        let dir = tempfile::tempdir().unwrap();
9687        std::fs::write(
9688            dir.path().join("daemon.json"),
9689            serde_json::json!({
9690                "schema": 1,
9691                "pid": 4242,
9692                "updated_at": Timestamp::now().to_string(),
9693                "idle": false,
9694                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
9695                "completed": 3,
9696                "polls": 9,
9697            })
9698            .to_string(),
9699        )
9700        .unwrap();
9701
9702        let reading = read_status(dir.path()).expect("an older shape must still parse");
9703        assert!(reading.running(Timestamp::now()));
9704        assert_eq!(
9705            reading.current,
9706            vec![Current {
9707                worker: None,
9708                task: "20260902-140501-aaaa".to_owned(),
9709                run: "20260902-140502-bbbb".to_owned(),
9710            }]
9711        );
9712    }
9713
9714    #[test]
9715    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
9716        let dir = tempfile::tempdir().unwrap();
9717        std::fs::write(
9718            dir.path().join("daemon.json"),
9719            serde_json::json!({
9720                "schema": 1,
9721                "updated_at": Timestamp::now().to_string(),
9722                "idle": true,
9723                "current": null,
9724            })
9725            .to_string(),
9726        )
9727        .unwrap();
9728        let with_null = read_status(dir.path()).expect("null must still parse");
9729        assert!(with_null.current.is_empty());
9730
9731        std::fs::write(
9732            dir.path().join("daemon.json"),
9733            serde_json::json!({
9734                "schema": 1,
9735                "updated_at": Timestamp::now().to_string(),
9736                "idle": true,
9737            })
9738            .to_string(),
9739        )
9740        .unwrap();
9741        let absent = read_status(dir.path()).expect("a missing field must still parse");
9742        assert!(absent.current.is_empty());
9743    }
9744
9745    #[test]
9746    fn a_task_without_a_repository_runs_in_the_daemons_default() {
9747        let fallback = Path::new("/default");
9748        let mut blank = task();
9749        blank.repo = PathBuf::new();
9750        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
9751        let mut dot = task();
9752        dot.repo = PathBuf::from(".");
9753        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
9754        assert_eq!(
9755            repo_for(&task(), fallback),
9756            PathBuf::from("/repo"),
9757            "a task that names a repository keeps it"
9758        );
9759    }
9760
9761    #[test]
9762    fn task_implementers_edit_inherits_daemon_config_and_merge() {
9763        let dir = tempfile::tempdir().unwrap();
9764        let path = dir.path().join("explicit.toml");
9765        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
9766        let opts = Opts {
9767            config: Some(path),
9768            merge: Some("none".into()),
9769            ..Default::default()
9770        };
9771        let mut t = task();
9772        t.set_implementers(
9773            2,
9774            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9775                .unwrap(),
9776        )
9777        .unwrap();
9778        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
9779        assert_eq!(cfg.graph.implementers, 2);
9780        assert_eq!(cfg.graph.judges, 1);
9781        assert_eq!(cfg.merge.mode, MergeMode::None);
9782        t.set_implementers(1, &cfg).unwrap();
9783        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
9784        apply_task_implementers(&mut cfg, &t);
9785        assert_eq!(cfg.graph.implementers, 1);
9786        assert_eq!(cfg.graph.judges, 1);
9787        assert_eq!(cfg.merge.mode, MergeMode::None);
9788    }
9789
9790    #[test]
9791    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
9792        let dir = tempfile::tempdir().unwrap();
9793        let repo = dir.path().join("repo");
9794        std::fs::create_dir(&repo).unwrap();
9795        std::fs::write(
9796            repo.join("magi.toml"),
9797            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
9798        )
9799        .unwrap();
9800        let daemon_config = dir.path().join("daemon.toml");
9801        std::fs::write(
9802            &daemon_config,
9803            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
9804        )
9805        .unwrap();
9806        let opts = Opts {
9807            config: Some(daemon_config),
9808            merge: Some("pr".into()),
9809            ..Default::default()
9810        };
9811        let q = Queue::at(dir.path().join("queue"));
9812        let validation: Config =
9813            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9814                .unwrap();
9815        // No provenance field on legacy direct tasks: both shapes stay isolated.
9816        for record in ["{}", r#"{"candidates":2}"#] {
9817            let overrides = serde_json::from_str(record).unwrap();
9818            let filing = crate::direct::Filing {
9819                instruction: "work".into(),
9820                title: "direct".into(),
9821                repo: repo.clone(),
9822                source: crate::queue::Source::Human,
9823                solo: false,
9824                overrides,
9825                review_of: None,
9826                sources: Default::default(),
9827            };
9828            let filed =
9829                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
9830            let crate::direct::Filed::Standalone {
9831                mut task,
9832                claim: _claim,
9833            } = filed
9834            else {
9835                panic!("local filing")
9836            };
9837            let before = prepare_for(&repo, &opts, &task).unwrap();
9838            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
9839            assert_eq!(
9840                before.merge.mode,
9841                MergeMode::None,
9842                "daemon --merge must not leak"
9843            );
9844            for n in [2, 1, 2] {
9845                task.set_implementers(n, &validation).unwrap();
9846                q.put(&mut task).unwrap();
9847                task = q.get(&task.id).unwrap();
9848                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
9849                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
9850                apply_task_implementers(&mut cfg, &task);
9851                assert_eq!(cfg.graph.implementers, usize::from(n));
9852                assert_eq!(cfg.graph.judges, 2);
9853                assert_eq!(cfg.merge.mode, MergeMode::None);
9854            }
9855        }
9856    }
9857
9858    #[test]
9859    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
9860        let cfg: Config =
9861            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9862                .unwrap();
9863        let mut t = task();
9864        t.review_of = Some("review-target".into());
9865        t.hold_manual(Some("retry".into()));
9866        let mut previous = RunState::new(
9867            PathBuf::from("/repo"),
9868            "main".into(),
9869            "abc1234".into(),
9870            "review".into(),
9871            cfg.clone(),
9872        );
9873        previous.config.graph.implementers = 2;
9874        for count in [1, 3] {
9875            t.set_implementers(count, &cfg).unwrap();
9876            t.release();
9877            assert_eq!(t.review_of.as_deref(), Some("review-target"));
9878            for proposed in [
9879                Starter::Resume(previous.id.clone()),
9880                Starter::Review("recovery-target".into()),
9881            ] {
9882                assert_eq!(
9883                    starter_with_implementers(&t, Some(&previous), proposed),
9884                    Starter::Review("review-target".into())
9885                );
9886            }
9887            let mut configured = cfg.clone();
9888            apply_task_implementers(&mut configured, &t);
9889            assert_eq!(configured.graph.implementers, usize::from(count));
9890            assert_eq!(previous.config.graph.implementers, 2);
9891        }
9892    }
9893
9894    #[test]
9895    fn task_implementers_dispatch_and_resume_agree() {
9896        let mut t = task();
9897        let cfg: crate::config::Config =
9898            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9899                .unwrap();
9900        let mut run = RunState::new(
9901            PathBuf::from("/repo"),
9902            "main".into(),
9903            "abc1234".into(),
9904            "work".into(),
9905            cfg.clone(),
9906        );
9907        run.config.graph.implementers = 2;
9908        for n in [2, 1, 3, 2] {
9909            t.set_implementers(n, &cfg).unwrap();
9910            let mut dispatched = cfg.clone();
9911            apply_task_implementers(&mut dispatched, &t);
9912            assert_eq!(dispatched.graph.implementers, usize::from(n));
9913            assert_eq!(implementers_match(&t, &run), n == 2);
9914            for proposed in [
9915                Starter::Resume(run.id.clone()),
9916                Starter::Review("old-branch".into()),
9917            ] {
9918                let expected = if n == 2 {
9919                    proposed.clone()
9920                } else {
9921                    Starter::Start
9922                };
9923                assert_eq!(
9924                    starter_with_implementers(&t, Some(&run), proposed),
9925                    expected
9926                );
9927            }
9928            assert_eq!(
9929                run.config.graph.implementers, 2,
9930                "history must not be rewritten"
9931            );
9932        }
9933        t.solo = false;
9934        t.overrides = None;
9935        assert!(implementers_match(&t, &run));
9936    }
9937
9938    #[test]
9939    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
9940        // Three seats said out loud. What `solo` promises is one candidate
9941        // *whatever the config asks for*, so the contrast has to be a number
9942        // this test owns - it used to be `Config::default()`'s, which became
9943        // 1 when one implementation became the default and left the two
9944        // halves of this test asserting the same thing.
9945        let mut solo_cfg = Config::default();
9946        solo_cfg.graph.implementers = 3;
9947        let mut solo_task = task();
9948        solo_task.solo = true;
9949        apply_task_implementers(&mut solo_cfg, &solo_task);
9950        assert_eq!(solo_cfg.graph.implementers, 1);
9951
9952        let mut plain_cfg = Config::default();
9953        plain_cfg.graph.implementers = 3;
9954        let plain_task = task();
9955        assert!(!plain_task.solo);
9956        apply_task_implementers(&mut plain_cfg, &plain_task);
9957        assert_eq!(
9958            plain_cfg.graph.implementers, 3,
9959            "a task that did not ask to run alone keeps the config's candidates"
9960        );
9961    }
9962
9963    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
9964        QuotaLoss {
9965            cause: crate::agent::QuotaCause::UsageLimit,
9966            agent: String::new(),
9967            seat: seat.into(),
9968            node: "judge".into(),
9969            at: at.parse().unwrap(),
9970            reset: reset.map(str::to_string),
9971        }
9972    }
9973
9974    #[test]
9975    fn authentication_losses_never_arm_a_cooldown_even_with_reset_hints() {
9976        let now = Timestamp::now();
9977        for reset in [None, Some("in 1h")] {
9978            let auth = crate::agent::Quota {
9979                cause: crate::agent::QuotaCause::Authentication,
9980                agent: "alpha".into(),
9981                reset: reset.map(str::to_owned),
9982            };
9983            let loss = QuotaLoss::from_report("advisor-1".into(), "advise", Some(&auth));
9984            assert_eq!(cooldown_until(&[loss], now), None);
9985        }
9986    }
9987
9988    #[test]
9989    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
9990        let old: Vec<QuotaLoss> = (1..=4)
9991            .map(|i| {
9992                loss(
9993                    &format!("judge-{i}"),
9994                    "2026-09-23T05:23:00Z",
9995                    Some("2:40pm (Asia/Tokyo)"),
9996                )
9997            })
9998            .collect();
9999        let fresh = losses_this_attempt(&old, &old);
10000        assert!(fresh.is_empty());
10001        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
10002        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
10003    }
10004
10005    #[test]
10006    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
10007        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
10008        let now = Timestamp::now();
10009        let mut after = old.clone();
10010        after.push(loss("judge-2", &now.to_string(), None));
10011        let fresh = losses_this_attempt(&old, &after);
10012        assert_eq!(fresh, vec![after[1].clone()]);
10013        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
10014        assert_eq!(
10015            until,
10016            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
10017        );
10018    }
10019
10020    #[test]
10021    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
10022        // `recover_stall` removes judge-1's loss and the retry then hits quota
10023        // again: the vector is the same length, so an index diff sees nothing.
10024        let before = vec![
10025            loss("judge-1", "2026-09-23T05:23:00Z", None),
10026            loss("judge-2", "2026-09-23T05:24:00Z", None),
10027        ];
10028        let after = vec![
10029            loss("judge-2", "2026-09-23T05:24:00Z", None),
10030            loss("judge-1", "2026-09-24T01:00:00Z", None),
10031        ];
10032        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
10033    }
10034
10035    #[test]
10036    fn merge_overrides_are_parsed_or_refused() {
10037        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
10038        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
10039        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
10040        assert!(merge_mode("squash").is_err());
10041    }
10042
10043    #[test]
10044    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
10045        let now = Timestamp::now();
10046        let fallback = Duration::from_secs(300);
10047        let cap = Duration::from_secs(1800);
10048
10049        // No reset hint at all: the fallback.
10050        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
10051
10052        // A reset ten minutes out, well inside the cap: waited for exactly.
10053        let soon = now + jiff::SignedDuration::from_secs(600);
10054        assert_eq!(
10055            quota_wait(Some(soon), now, fallback, cap),
10056            Duration::from_secs(600)
10057        );
10058
10059        // A reset already in the past is not trusted: the fallback, not a
10060        // zero or negative wait that would spin the loop right back around.
10061        let past = now - jiff::SignedDuration::from_secs(60);
10062        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
10063
10064        // A reset further out than the cap is trusted for direction but not
10065        // for magnitude: a parsing slip must not sleep the loop for a day.
10066        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
10067        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
10068    }
10069
10070    #[test]
10071    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
10072        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
10073
10074        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
10075        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
10076
10077        // Same clock reading, but it has already gone by today: read as
10078        // tomorrow's, since the CLI would not still be reporting a limit past
10079        // its own stated reset.
10080        let already_past =
10081            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
10082        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
10083
10084        assert!(
10085            parse_reset_hint("session limit reached", now, now).is_none(),
10086            "free text with no recognised shape is not guessed at"
10087        );
10088        assert!(
10089            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
10090            "an unresolvable zone name is not guessed at either"
10091        );
10092    }
10093
10094    #[test]
10095    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
10096        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
10097
10098        let at = parse_reset_hint(
10099            "You've hit your usage limit. Visit \
10100             https://chatgpt.com/codex/settings/usage to purchase more \
10101             credits or try again at Sep 19th, 2026 5:10 PM.",
10102            now,
10103            now,
10104        )
10105        .expect("the codex reset wording is a recognised shape");
10106        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
10107
10108        // The month is explicit, so a date already earlier in the same
10109        // sentence-implied year than `now` is trusted as written rather than
10110        // rolled forward a year the way the bracketed shape rolls a
10111        // same-day clock reading to tomorrow.
10112        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
10113            .expect("an explicit year needs no rollover");
10114        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
10115
10116        assert!(
10117            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
10118            "a two-digit year is not the documented shape and is not guessed at"
10119        );
10120        assert!(
10121            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
10122            "a four-letter month name is not the documented three-letter abbreviation"
10123        );
10124        assert!(
10125            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
10126            "an explicit zone on the dated shape is a format nobody has \
10127             documented, and is refused rather than guessed at as UTC"
10128        );
10129    }
10130
10131    #[test]
10132    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
10133        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
10134        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
10135
10136        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
10137        assert_eq!(at.as_second() - recorded.as_second(), 3769);
10138
10139        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
10140        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
10141
10142        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
10143            assert!(
10144                parse_reset_hint(bad, now, recorded).is_none(),
10145                "{bad:?} must not be guessed at"
10146            );
10147        }
10148    }
10149
10150    /// A loop whose queue lives in a temp tree and whose poll interval is far
10151    /// longer than the test's patience, so anything that waits out a poll
10152    /// instead of noticing the stop fails rather than merely being slow.
10153    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
10154        let config = dir.join("magi.toml");
10155        std::fs::write(
10156            &config,
10157            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
10158        )
10159        .unwrap();
10160        let opts = Opts {
10161            poll: Duration::from_secs(30),
10162            config: Some(config),
10163            // The explicit fixture config keeps startup cleanup from reading
10164            // machine configuration. This fictional repository likewise
10165            // keeps any best-effort git cleanup away from this checkout.
10166            repo: dir.join("repo"),
10167            ..Opts::default()
10168        };
10169        // The status file goes in a directory that does not exist yet, so its
10170        // creation is itself evidence the loop published one. `worktrees`
10171        // must be just as fictional: the janitor reclaims worktrees under it
10172        // for real, and a test that let it fall through to
10173        // `crate::run::default_worktree_root()` would have it reclaim
10174        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
10175        // which is exactly what happened before this function took the
10176        // parameter at all.
10177        let home = dir.join("home");
10178        // These control-only fixtures do not launch native workers. Give the
10179        // independently tested maintenance services a fresh cadence receipt.
10180        let stamps = home.join("service-ticks");
10181        std::fs::create_dir_all(&stamps).unwrap();
10182        for service in ["waiter", "deputies", "release-watch"] {
10183            std::fs::write(
10184                stamps.join(service),
10185                Timestamp::now().as_second().to_string(),
10186            )
10187            .unwrap();
10188        }
10189        for operation in [
10190            "conductor",
10191            "maintenance",
10192            "housekeeping",
10193            "disk-pressure",
10194            "cache",
10195            "fetch",
10196        ] {
10197            std::fs::write(
10198                stamps.join(format!("daemon-{operation}")),
10199                serde_json::to_vec(&Timestamp::now()).unwrap(),
10200            )
10201            .unwrap();
10202        }
10203        let worktrees = dir.join("wt");
10204        (
10205            opts,
10206            Queue::at(dir.join("queue")),
10207            home.join("daemon.json"),
10208            home,
10209            worktrees,
10210        )
10211    }
10212
10213    #[test]
10214    fn a_stop_is_idempotent_and_once_set_stays_set() {
10215        let stop = Stop::new();
10216        assert!(!stop.stopped());
10217
10218        stop.stop();
10219        assert!(stop.stopped());
10220        stop.stop();
10221        assert!(stop.stopped(), "a second stop is not a toggle");
10222
10223        let shared = stop.clone();
10224        assert!(
10225            shared.stopped(),
10226            "a clone is the same stop; that is how the loop and its caller share one"
10227        );
10228    }
10229
10230    #[tokio::test]
10231    async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
10232        for operation in ["conductor", "maintenance", "housekeeping"] {
10233            let dir = tempfile::tempdir().unwrap();
10234            let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
10235            opts.once = true;
10236            opts.poll = Duration::from_millis(1);
10237            let mut task = task();
10238            task.runs.push("fixture-run".into());
10239            queue.put(&mut task).unwrap();
10240            let claim = queue.claim(&task.id).unwrap();
10241
10242            // Model a live service holding the task's claim across the
10243            // scheduler's dispatch scan. No real subprocess or timed race.
10244            let directory = home.join("workers/jobs/abcdef");
10245            std::fs::create_dir_all(&directory).unwrap();
10246            let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
10247            crate::pr_head::try_lock_file(&lease).unwrap();
10248            let mut job = crate::worker::Job {
10249                id: "abcdef".into(),
10250                sequence: 1,
10251                kind: "daemon-service".into(),
10252                key: format!("service:daemon-{operation}"),
10253                payload: serde_json::Value::Null,
10254                generation: "fixture".into(),
10255                version: None,
10256                status: crate::worker::Status::Running,
10257                result: None,
10258                pid: Some(std::process::id()),
10259                created_at: Timestamp::now().as_second() as u64,
10260                finished_at: None,
10261            };
10262            let record = directory.join("job.json");
10263            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10264
10265            let status = Arc::new(Mutex::new(Status::new()));
10266            let stop = Stop::new();
10267            let mut drain = Box::pin(poll(
10268                &opts,
10269                &queue,
10270                &status,
10271                &home,
10272                &worktrees,
10273                &stop,
10274                DispatchLimits {
10275                    max_concurrent: 1,
10276                    pause_for_interrupts: false,
10277                    recovery_cfg: None,
10278                },
10279            ));
10280            std::future::poll_fn(|cx| {
10281                use std::future::Future;
10282                assert!(
10283                    drain.as_mut().poll(cx).is_pending(),
10284                    "--once must wait for {operation} to release its queue claim"
10285                );
10286                std::task::Poll::Ready(())
10287            })
10288            .await;
10289            assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
10290
10291            // An answer arrives while the service still owns the claim. A
10292            // fresh scheduling pass must apply it before declaring idle.
10293            let questions = Questions::at(home.join("questions"));
10294            let mut q = action_question("fixture-run", ask::ChoiceAction::Done);
10295            questions.put(&mut q).unwrap();
10296            drop(claim);
10297            // Model services that took longer than their cadence, without a
10298            // wall-clock sleep. The final scans must not respawn them even
10299            // though their receipts now permit another periodic invocation.
10300            let expired =
10301                serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
10302            for service in [operation, "housekeeping"] {
10303                std::fs::write(
10304                    home.join("service-ticks").join(format!("daemon-{service}")),
10305                    &expired,
10306                )
10307                .unwrap();
10308            }
10309            job.status = crate::worker::Status::Finished;
10310            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10311            drop(lease);
10312            tokio::time::timeout(Duration::from_secs(2), drain)
10313                .await
10314                .expect("the settled service must allow the drain to finish")
10315                .unwrap();
10316            let after = queue.get(&task.id).unwrap();
10317            assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
10318            assert!(after.action_applied(&q.id));
10319            for service in [operation, "housekeeping"] {
10320                assert_eq!(
10321                    std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
10322                        .unwrap(),
10323                    expired,
10324                    "the final once rescan must not restart {service}"
10325                );
10326            }
10327        }
10328    }
10329
10330    #[test]
10331    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
10332        let stop = Stop::new();
10333        stop.busy.store(1, Ordering::SeqCst);
10334        assert!(
10335            !stop.finishing(),
10336            "a busy loop nobody has asked to stop is just running"
10337        );
10338
10339        stop.stop();
10340        assert!(
10341            stop.finishing(),
10342            "a stop asked for mid-run has not landed until the run is settled"
10343        );
10344
10345        stop.busy.store(0, Ordering::SeqCst);
10346        assert!(
10347            !stop.finishing(),
10348            "once the run is settled the stop has landed and there is nothing to finish"
10349        );
10350    }
10351
10352    #[test]
10353    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
10354        let stop = Stop::new();
10355        stop.busy.store(2, Ordering::SeqCst);
10356        stop.stop();
10357        assert!(stop.finishing(), "two runs still in flight");
10358
10359        stop.busy.store(1, Ordering::SeqCst);
10360        assert!(
10361            stop.finishing(),
10362            "one run finished, but a sibling is still working"
10363        );
10364
10365        stop.busy.store(0, Ordering::SeqCst);
10366        assert!(
10367            !stop.finishing(),
10368            "the last run out is what actually lands the stop"
10369        );
10370    }
10371
10372    #[tokio::test]
10373    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
10374        let dir = tempfile::tempdir().unwrap();
10375        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10376        let stop = Stop::new();
10377        stop.stop();
10378
10379        let began = std::time::Instant::now();
10380        tokio::time::timeout(
10381            Duration::from_secs(2),
10382            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10383        )
10384        .await
10385        .expect("a stopped loop must return, not sit out its poll interval")
10386        .expect("the loop's own setup and teardown must not fail");
10387        assert!(
10388            began.elapsed() < opts.poll,
10389            "returned only after {:?}, which is a poll interval, not a stop",
10390            began.elapsed()
10391        );
10392    }
10393
10394    #[tokio::test]
10395    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
10396        let dir = tempfile::tempdir().unwrap();
10397        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10398        let stop = Stop::new();
10399
10400        // Asked for after the loop is already parked on its empty queue, which
10401        // is the case an operator tapping stop on a phone actually hits.
10402        let asker = {
10403            let stop = stop.clone();
10404            tokio::spawn(async move {
10405                tokio::time::sleep(Duration::from_millis(20)).await;
10406                stop.stop();
10407            })
10408        };
10409
10410        let began = std::time::Instant::now();
10411        tokio::time::timeout(
10412            Duration::from_secs(2),
10413            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10414        )
10415        .await
10416        .expect("a stop asked for while idle must wake the wait")
10417        .expect("the loop's own setup and teardown must not fail");
10418        asker.await.unwrap();
10419        assert!(
10420            began.elapsed() < opts.poll,
10421            "returned only after {:?}, so the stop waited on the sleep",
10422            began.elapsed()
10423        );
10424    }
10425
10426    #[tokio::test]
10427    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
10428        let dir = tempfile::tempdir().unwrap();
10429        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10430        let stop = Stop::new();
10431        stop.stop();
10432
10433        tokio::time::timeout(
10434            Duration::from_secs(2),
10435            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10436        )
10437        .await
10438        .expect("a stopped loop must return")
10439        .expect("the loop's own setup and teardown must not fail");
10440
10441        assert!(
10442            home.is_dir(),
10443            "the loop did publish a status file, so its removal is the teardown and not an absence"
10444        );
10445        assert!(
10446            !status_file.exists(),
10447            "a stopped loop clears its status file"
10448        );
10449        assert!(
10450            read_status(&home).is_none(),
10451            "a reader must see no daemon at all, not a heartbeat that merely stopped"
10452        );
10453    }
10454
10455    #[tokio::test]
10456    async fn housekeeping_worker_settles_questions_without_a_scheduler() {
10457        let dir = tempfile::tempdir().unwrap();
10458        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
10459
10460        let mut settled = RunState::new(
10461            dir.path().join("repo"),
10462            "main".to_owned(),
10463            "abc1234".to_owned(),
10464            "fixture".to_owned(),
10465            Config::default(),
10466        );
10467        settled.status = RunStatus::Ready;
10468        let run_dir = home.join("runs").join(&settled.id);
10469        std::fs::create_dir_all(&run_dir).unwrap();
10470        std::fs::write(
10471            run_dir.join("run.json"),
10472            serde_json::to_string_pretty(&settled).unwrap(),
10473        )
10474        .unwrap();
10475        let questions = Questions::at(home.join("questions"));
10476        let mut question = ask::Question::new(
10477            settled.id.clone(),
10478            "review".to_owned(),
10479            "reviewer-1".to_owned(),
10480            "Continue?".to_owned(),
10481            String::new(),
10482            Vec::new(),
10483        );
10484        questions.put(&mut question).unwrap();
10485
10486        run_service_worker(
10487            &home,
10488            serde_json::to_value(ServiceWorker {
10489                opts,
10490                queue: queue.root().to_path_buf(),
10491                worktrees_root: worktrees,
10492                operation: "housekeeping".to_owned(),
10493            })
10494            .unwrap(),
10495        )
10496        .await
10497        .unwrap();
10498
10499        assert_eq!(
10500            questions.get(&question.id).unwrap().status,
10501            ask::QuestionStatus::Abandoned,
10502            "the independent housekeeping worker settles ended-run questions"
10503        );
10504    }
10505
10506    #[test]
10507    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
10508        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10509
10510        assert!(
10511            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
10512            "never checked before: due at once"
10513        );
10514
10515        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
10516        assert!(
10517            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
10518            "well inside the interval: not due yet"
10519        );
10520
10521        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
10522        assert!(
10523            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
10524            "exactly at the edge: not yet due, same convention as `clean::due`"
10525        );
10526
10527        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
10528        assert!(
10529            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
10530            "past the interval: due again"
10531        );
10532    }
10533
10534    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
10535    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
10536    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
10537    /// and the congestion test below both need, and must not drift apart.
10538    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
10539        let config = dir.join("magi.toml");
10540        // A literal (single-quoted) TOML string, not a basic one: the cache
10541        // path is a Windows path full of backslashes, and a basic string
10542        // would have TOML try to interpret `\U` (from `\Users\...`) as a
10543        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
10544        // `{{ vars.cache }}` rendering documents.
10545        std::fs::write(
10546            &config,
10547            format!(
10548                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
10549                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
10550                cache_dir.display()
10551            ),
10552        )
10553        .unwrap();
10554        Opts {
10555            config: Some(config),
10556            repo: dir.join("repo"),
10557            ..Opts::default()
10558        }
10559    }
10560
10561    #[tokio::test]
10562    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
10563        let dir = tempfile::tempdir().unwrap();
10564        let home = dir.path().join("home");
10565        let cache_dir = dir.path().join("cache");
10566        std::fs::create_dir_all(&cache_dir).unwrap();
10567        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
10568        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
10569
10570        // Nobody has asked this daemon to stop, which is the ordinary case;
10571        // the skip that a stop buys is asserted by its own test below.
10572        let running = Stop::new();
10573        let mut last_checked = None;
10574        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10575        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
10576            .await;
10577        assert_eq!(
10578            crate::disk::dir_size(&cache_dir),
10579            0,
10580            "over the cap on the first check ever: pruned at once, no idle queue required"
10581        );
10582        assert_eq!(last_checked, Some(t0));
10583
10584        // A fresh oversized file lands, but the next check is not due yet.
10585        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
10586        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
10587        maybe_prune_cache_between_runs(
10588            &opts.repo,
10589            &opts,
10590            &home,
10591            &running,
10592            &mut last_checked,
10593            too_soon,
10594        )
10595        .await;
10596        assert_eq!(
10597            crate::disk::dir_size(&cache_dir),
10598            10,
10599            "too soon since the last check: left alone rather than rescanned every call"
10600        );
10601        assert_eq!(
10602            last_checked,
10603            Some(t0),
10604            "an idle check does not reset the clock"
10605        );
10606
10607        // Once the interval elapses, the same oversized cache is caught again.
10608        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
10609        maybe_prune_cache_between_runs(
10610            &opts.repo,
10611            &opts,
10612            &home,
10613            &running,
10614            &mut last_checked,
10615            due_again,
10616        )
10617        .await;
10618        assert_eq!(
10619            crate::disk::dir_size(&cache_dir),
10620            0,
10621            "due again: pruned back under the cap"
10622        );
10623    }
10624
10625    /// A stop must not queue behind housekeeping. The prune below is a
10626    /// synchronous walk of the whole cache with no await point in it, so a
10627    /// loop that entered it could not get back to its own `stopped()` test
10628    /// until the walk finished - and because no run is in flight at this
10629    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
10630    /// the stop had already landed. The idle branch has always made this same
10631    /// check before reaching `janitor`; the between-runs path makes it too.
10632    #[tokio::test]
10633    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
10634        let dir = tempfile::tempdir().unwrap();
10635        let home = dir.path().join("home");
10636        let cache_dir = dir.path().join("cache");
10637        std::fs::create_dir_all(&cache_dir).unwrap();
10638        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
10639        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
10640
10641        let stop = Stop::new();
10642        stop.stop();
10643        assert!(
10644            !stop.finishing(),
10645            "no run is in flight at a between-runs boundary, so nothing else \
10646             would tell the operator this stop had not taken effect yet"
10647        );
10648
10649        let mut last_checked = None;
10650        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10651        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
10652            .await;
10653        assert_eq!(
10654            crate::disk::dir_size(&cache_dir),
10655            10,
10656            "over its cap, and due for the first check ever, but a stop outranks \
10657             it: the cap is a standing policy the next start measures again"
10658        );
10659        assert_eq!(
10660            last_checked, None,
10661            "a check that never happened must not claim the interval"
10662        );
10663    }
10664
10665    /// A backlog must not starve cache pruning. The finite cache worker runs
10666    /// independently of queue drain and must not consume any task attempts.
10667    #[tokio::test]
10668    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
10669        let dir = tempfile::tempdir().unwrap();
10670        let cache_dir = dir.path().join("cache");
10671        std::fs::create_dir_all(&cache_dir).unwrap();
10672        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
10673
10674        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
10675        opts.poll = Duration::from_millis(20);
10676        opts.max_attempts = 1_000;
10677
10678        let queue = Queue::at(dir.path().join("queue"));
10679        for i in 0..128 {
10680            let mut task = Task::new(
10681                format!("queued work {i}"),
10682                format!("queued work {i}"),
10683                opts.repo.clone(),
10684                Source::Human,
10685            );
10686            queue.put(&mut task).unwrap();
10687        }
10688
10689        let home = dir.path().join("home");
10690        let worktrees = dir.path().join("wt");
10691        run_service_worker(
10692            &home,
10693            serde_json::to_value(ServiceWorker {
10694                opts,
10695                queue: queue.root().to_path_buf(),
10696                worktrees_root: worktrees,
10697                operation: "cache".to_owned(),
10698            })
10699            .unwrap(),
10700        )
10701        .await
10702        .unwrap();
10703        let after = queue.list();
10704        assert_eq!(after.len(), 128);
10705        assert!(
10706            after
10707                .iter()
10708                .all(|task| task.status.runnable() && task.attempts == 0)
10709        );
10710
10711        assert_eq!(
10712            crate::disk::dir_size(&cache_dir),
10713            0,
10714            "an oversized cache must not be left to grow unboundedly just because the \
10715             queue kept the loop busy the whole time"
10716        );
10717    }
10718
10719    #[test]
10720    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
10721        let dir = tempfile::tempdir().unwrap();
10722        let queue = Queue::at(dir.path().join("queue"));
10723        let questions = Questions::at(dir.path().join("questions"));
10724        let mut task = task();
10725        queue.put(&mut task).unwrap();
10726
10727        let mut task_question = ask::Question::new(
10728            task.id.clone(),
10729            crate::conduct::NODE.to_owned(),
10730            "conduct".to_owned(),
10731            "Which backend?".to_owned(),
10732            String::new(),
10733            Vec::new(),
10734        );
10735        questions.put(&mut task_question).unwrap();
10736        task.block(vec![task_question.id.clone()], None);
10737        queue.put(&mut task).unwrap();
10738
10739        let mut run_question = ask::Question::new(
10740            "20260101-000000-run1".to_owned(),
10741            "review".to_owned(),
10742            "reviewer-1".to_owned(),
10743            "Run question".to_owned(),
10744            String::new(),
10745            Vec::new(),
10746        );
10747        questions.put(&mut run_question).unwrap();
10748
10749        // A question from another node whose `run` happens to equal this
10750        // task's id — the same field, filled in for an unrelated reason. Only
10751        // `crate::conduct::NODE` questions use `run` as a task id; this one
10752        // must never be touched by this reconciliation, even after release.
10753        let mut coincidental = ask::Question::new(
10754            task.id.clone(),
10755            "review".to_owned(),
10756            "reviewer-1".to_owned(),
10757            "Unrelated review question".to_owned(),
10758            String::new(),
10759            Vec::new(),
10760        );
10761        questions.put(&mut coincidental).unwrap();
10762
10763        reconcile_task_questions(&queue, &questions);
10764        assert!(questions.get(&task_question.id).unwrap().status.open());
10765        assert!(questions.get(&run_question.id).unwrap().status.open());
10766        assert!(questions.get(&coincidental.id).unwrap().status.open());
10767
10768        task.release();
10769        queue.put(&mut task).unwrap();
10770        reconcile_task_questions(&queue, &questions);
10771        assert_eq!(
10772            questions.get(&task_question.id).unwrap().status,
10773            ask::QuestionStatus::Abandoned
10774        );
10775        assert!(
10776            questions.get(&run_question.id).unwrap().status.open(),
10777            "run questions remain the run janitor's responsibility"
10778        );
10779        assert!(
10780            questions.get(&coincidental.id).unwrap().status.open(),
10781            "a non-conductor question must not be abandoned just because its \
10782             run id coincides with a task id"
10783        );
10784    }
10785
10786    #[test]
10787    fn a_freshly_started_running_task_is_never_stalled() {
10788        let dir = tempfile::tempdir().unwrap();
10789        let mut t = task();
10790        t.start("run-1".to_owned());
10791        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
10792        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
10793        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
10794    }
10795
10796    #[test]
10797    fn a_long_running_task_with_no_live_daemon_is_stalled() {
10798        let dir = tempfile::tempdir().unwrap();
10799        let mut t = task();
10800        t.start("run-1".to_owned());
10801        t.updated_at = Timestamp::now()
10802            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
10803        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
10804        assert_eq!(
10805            stalled_tasks(
10806                &Queue::at(dir.path().join("q")),
10807                dir.path(),
10808                Timestamp::now()
10809            )
10810            .len(),
10811            0,
10812            "the task was never written to this queue"
10813        );
10814    }
10815
10816    #[test]
10817    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
10818        let dir = tempfile::tempdir().unwrap();
10819        let mut t = task();
10820        t.id = "20260903-080340-0167".to_owned();
10821        t.start("20260903-080619-01c2".to_owned());
10822        t.updated_at = Timestamp::now()
10823            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
10824
10825        let mut status = Status::new();
10826        status.current = vec![Current {
10827            worker: None,
10828            task: t.id.clone(),
10829            run: "20260903-080619-01c2".to_owned(),
10830        }];
10831        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10832
10833        assert!(
10834            !is_stalled(&t, dir.path(), Timestamp::now()),
10835            "a live daemon's own heartbeat rules out stalled, however long the task has run"
10836        );
10837    }
10838
10839    /// Rewrite a task's `updated_at` on disk directly, bypassing
10840    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
10841    /// a fixture look like it has genuinely been `running` for a while.
10842    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
10843        let path = queue.path_of(id);
10844        let body = std::fs::read_to_string(&path).unwrap();
10845        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
10846        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
10847        v["updated_at"] = serde_json::Value::String(old.to_string());
10848        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
10849    }
10850
10851    #[test]
10852    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
10853        // The realistic `poll()` ordering, not `is_stalled` in isolation:
10854        // `reclaim_orphaned_running` runs first, on every poll, and settles
10855        // any `running` task whose claim it can actually take. For most
10856        // crashes that is immediate - a dead pid is proof enough for
10857        // `sweep_stale_claims` to drop the lock the same tick, and the very
10858        // next claim attempt succeeds. But a lock whose pid cannot be parsed
10859        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
10860        // `sweep_stale_claims`'s own doc), so the lock - and the claim
10861        // failure behind it - can legitimately outlive many polls. This is
10862        // exactly the gap `stalled_tasks` exists to surface well before that
10863        // six-hour sweep would: reclaim leaves the task `running`, and it
10864        // must still reach the conductor as stalled.
10865        let dir = tempfile::tempdir().unwrap();
10866        let queue = Queue::at(dir.path().join("queue"));
10867        let home = dir.path().join("home");
10868
10869        let mut t = task();
10870        t.id = "20260101-000001-lock".to_owned();
10871        t.start("run-1".to_owned());
10872        queue.put(&mut t).unwrap();
10873        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
10874        std::fs::write(
10875            dir.path().join("queue").join(format!("{}.lock", t.id)),
10876            "not a pid",
10877        )
10878        .unwrap();
10879
10880        let now = Timestamp::now();
10881        assert!(
10882            reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
10883            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
10884             and reclaim must leave the task alone"
10885        );
10886        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
10887
10888        let stalled = stalled_tasks(&queue, &home, now);
10889        assert_eq!(
10890            stalled.len(),
10891            1,
10892            "reclaim's inability to claim it yet must not hide it from the conductor"
10893        );
10894        assert_eq!(stalled[0].id, t.id);
10895    }
10896
10897    #[test]
10898    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
10899        let dir = tempfile::tempdir().unwrap();
10900        crate::run::set_home(dir.path().join("run-home"));
10901        let queue = Queue::at(dir.path().join("queue"));
10902        let home = dir.path().join("home");
10903        let questions = Questions::at(dir.path().join("questions"));
10904
10905        let mut t = task();
10906        t.id = "20260101-000003-dead".to_owned();
10907        t.start("missing-run".to_owned());
10908        queue.put(&mut t).unwrap();
10909        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
10910
10911        // This is the real poll ordering: retain the deterministic stalled
10912        // input before a claim proves the owner is gone and reclaims it.
10913        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
10914        assert_eq!(
10915            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
10916            [&t.id]
10917        );
10918        assert_eq!(
10919            reclaim_orphaned_running(&queue, 2, &Default::default()),
10920            [t.id.clone()]
10921        );
10922        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10923
10924        // Reclaim drops its guard before conductor decisions are applied, so
10925        // the decision for the captured stalled input has a real write path.
10926        crate::conduct::apply(
10927            &queue,
10928            &questions,
10929            &crate::conduct::Verdict {
10930                decisions: vec![crate::conduct::Decision {
10931                    id: t.id.clone(),
10932                    recovery: Some(crate::conduct::Recovery::Requeue),
10933                    ..crate::conduct::Decision::default()
10934                }],
10935            },
10936        )
10937        .unwrap();
10938        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
10939    }
10940
10941    #[test]
10942    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
10943        let dir = tempfile::tempdir().unwrap();
10944        let queue = Queue::at(dir.path().join("queue"));
10945        let home = dir.path().join("home");
10946
10947        let mut fresh = task();
10948        fresh.id = "20260101-000001-aaaa".to_owned();
10949        fresh.start("run-1".to_owned());
10950        queue.put(&mut fresh).unwrap();
10951
10952        let mut old = task();
10953        old.id = "20260101-000002-bbbb".to_owned();
10954        old.start("run-2".to_owned());
10955        queue.put(&mut old).unwrap();
10956        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
10957
10958        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
10959        assert_eq!(stalled.len(), 1);
10960        assert_eq!(stalled[0].id, old.id);
10961    }
10962
10963    #[test]
10964    fn queued_and_finished_task_views_partition_by_status() {
10965        let dir = tempfile::tempdir().unwrap();
10966        let queue = Queue::at(dir.path().join("queue"));
10967
10968        let mut queued = task();
10969        queued.id = "20260101-000001-aaaa".to_owned();
10970        queue.put(&mut queued).unwrap();
10971
10972        let mut failed = task();
10973        failed.id = "20260101-000002-bbbb".to_owned();
10974        failed.start("run-1".to_owned());
10975        failed.fail("gate red", 5);
10976        queue.put(&mut failed).unwrap();
10977
10978        let mut held = task();
10979        held.id = "20260101-000003-cccc".to_owned();
10980        held.hold_machine(None);
10981        queue.put(&mut held).unwrap();
10982
10983        let mut running = task();
10984        running.id = "20260101-000004-dddd".to_owned();
10985        running.start("run-2".to_owned());
10986        queue.put(&mut running).unwrap();
10987
10988        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
10989        assert_eq!(queued_ids, [queued.id.clone()]);
10990
10991        let mut finished_ids: Vec<String> =
10992            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
10993        finished_ids.sort_unstable();
10994        let mut want = vec![failed.id.clone(), held.id.clone()];
10995        want.sort_unstable();
10996        assert_eq!(finished_ids, want);
10997    }
10998
10999    #[test]
11000    fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
11001        for short in [false, true] {
11002            let dir = tempfile::tempdir().unwrap();
11003            let queue = Queue::at(dir.path().join("queue"));
11004            let questions = ask::Questions::at(dir.path().join("questions"));
11005            let mut running = task();
11006            running.id = "20261013-192213-feb2".into();
11007            running.start("existing-run".into());
11008            queue.put(&mut running).unwrap();
11009            let mut middle = task();
11010            middle.id = "20261013-193611-ca5b".into();
11011            middle.block(
11012                vec![if short {
11013                    "feb2".into()
11014                } else {
11015                    running.id.clone()
11016                }],
11017                None,
11018            );
11019            queue.put(&mut middle).unwrap();
11020            let mut waiting = task();
11021            waiting.id = "20261013-202849-ee37".into();
11022            waiting.block(
11023                vec![if short {
11024                    "ca5b".into()
11025                } else {
11026                    middle.id.clone()
11027                }],
11028                Some("wait for implementation".into()),
11029            );
11030            queue.put(&mut waiting).unwrap();
11031            assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
11032            let inv = crate::blockers::Inventory::load(&queue, &questions);
11033            assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
11034            assert!(inv.stuck().is_empty());
11035            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11036            assert!(report.quarantined.is_empty());
11037            assert!(report.asked.is_empty());
11038            resolve_blockers(&queue, &questions);
11039            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11040            assert!(questions.list().is_empty());
11041            // Finishing the transitive prerequisite alone does not satisfy
11042            // the task's direct dependency.
11043            running.succeed();
11044            queue.put(&mut running).unwrap();
11045            resolve_blockers(&queue, &questions);
11046            assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
11047            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11048            middle = queue.get(&middle.id).unwrap();
11049            middle.succeed();
11050            queue.put(&mut middle).unwrap();
11051            resolve_blockers(&queue, &questions);
11052            let after = queue.get(&waiting.id).unwrap();
11053            assert_eq!(after.status, TaskStatus::Queued);
11054            assert!(after.blocked_by.is_empty());
11055            assert_eq!(after.instruction, waiting.instruction);
11056        }
11057    }
11058
11059    #[test]
11060    fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
11061        for future_schema in [false, true] {
11062            let name = "20261013-193611-ca5b";
11063            let mut future = task();
11064            future.id = name.into();
11065            future.schema = crate::queue::SCHEMA + 1;
11066            let contents = if future_schema {
11067                serde_json::to_string(&future).unwrap()
11068            } else {
11069                "corrupt".into()
11070            };
11071            let dir = tempfile::tempdir().unwrap();
11072            let queue = Queue::at(dir.path().join("queue"));
11073            let questions = ask::Questions::at(dir.path().join("questions"));
11074            let mut waiting = task();
11075            waiting.id = "20261013-202849-ee37".into();
11076            waiting.block(vec!["ca5b".into()], None);
11077            queue.put(&mut waiting).unwrap();
11078            std::fs::write(queue.path_of(name), contents).unwrap();
11079            assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
11080            assert!(
11081                crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
11082            );
11083            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11084            assert!(report.asked.is_empty());
11085            resolve_blockers(&queue, &questions);
11086            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11087            assert!(questions.list().is_empty());
11088        }
11089        let dir = tempfile::tempdir().unwrap();
11090        let queue = Queue::at(dir.path().join("queue"));
11091        let questions = ask::Questions::at(dir.path().join("questions"));
11092        let mut waiting = task();
11093        waiting.id = "20261013-202849-ee37".into();
11094        waiting.block(vec!["ca5b".into()], None);
11095        queue.put(&mut waiting).unwrap();
11096        let mut done = task();
11097        done.id = "20261013-193611-ca5b".into();
11098        done.succeed();
11099        queue.put(&mut done).unwrap();
11100        // An unreadable second match must not disappear from uniqueness
11101        // checks just because Queue::list skips it.
11102        std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
11103        assert!(queue.get("ca5b").is_err());
11104        assert_eq!(
11105            crate::queue::dependency(&queue, &questions, "ca5b"),
11106            crate::queue::Dependency::Ambiguous
11107        );
11108        resolve_blockers(&queue, &questions);
11109        let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11110        assert!(report.asked.is_empty());
11111        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11112        assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
11113    }
11114
11115    #[test]
11116    fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
11117        for held in [false, true] {
11118            for question in [false, true] {
11119                for reference in ["ca5b", "20261013-193611-ca5b"] {
11120                    let dir = tempfile::tempdir().unwrap();
11121                    let queue = Queue::at(dir.path().join("queue"));
11122                    let questions = ask::Questions::at(dir.path().join("questions"));
11123                    let mut prerequisite = task();
11124                    prerequisite.id = "20261013-193611-ca5b".into();
11125                    prerequisite.start("existing-run".into());
11126                    queue.put(&mut prerequisite).unwrap();
11127                    let mut waiting = task();
11128                    waiting.id = "20261013-202849-ee37".into();
11129                    if held {
11130                        waiting.hold_machine(Some("waiting for separate consent".into()));
11131                    }
11132                    queue.put(&mut waiting).unwrap();
11133                    let reason = "Deleting saved data requires separate owner consent";
11134                    crate::conduct::apply(
11135                        &queue,
11136                        &questions,
11137                        &crate::conduct::Verdict {
11138                            decisions: vec![crate::conduct::Decision {
11139                                id: waiting.id.clone(),
11140                                blocked_by: vec![reference.into()],
11141                                question: question.then(|| "May the saved data be deleted?".into()),
11142                                recovery: (!question).then_some(crate::conduct::Recovery::Hold),
11143                                reason: Some(reason.into()),
11144                                ..crate::conduct::Decision::default()
11145                            }],
11146                        },
11147                    )
11148                    .unwrap();
11149                    let before = queue.get(&waiting.id).unwrap();
11150                    if question {
11151                        assert_eq!(before.status, TaskStatus::Blocked);
11152                        let q = questions.get(&before.blocked_by[0]).unwrap();
11153                        assert_eq!(q.summary, "May the saved data be deleted?");
11154                        assert!(q.status.open());
11155                    } else {
11156                        assert_eq!(before.status, TaskStatus::Held);
11157                        let recorded_reason = before.hold_reason.as_deref().unwrap();
11158                        assert!(recorded_reason.starts_with(reason));
11159                        if held {
11160                            assert!(recorded_reason.contains("waiting for separate consent"));
11161                        }
11162                    }
11163                    prerequisite.succeed();
11164                    queue.put(&mut prerequisite).unwrap();
11165                    resolve_blockers(&queue, &questions);
11166                    let after = queue.get(&waiting.id).unwrap();
11167                    assert_eq!(after.status, before.status);
11168                    assert_eq!(after.blocked_by, before.blocked_by);
11169                    assert_eq!(after.hold_reason, before.hold_reason);
11170                    assert_eq!(after.instruction, waiting.instruction);
11171                    if question {
11172                        assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
11173                    }
11174                    assert!(
11175                        queue.next_runnable().is_none(),
11176                        "dependency completion is not consent"
11177                    );
11178                }
11179            }
11180        }
11181    }
11182
11183    #[test]
11184    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
11185        let dir = tempfile::tempdir().unwrap();
11186        let queue = Queue::at(dir.path().join("queue"));
11187        let questions = ask::Questions::at(dir.path().join("questions"));
11188
11189        let mut dep = task();
11190        dep.id = "20260101-000001-dep0".to_owned();
11191        dep.succeed();
11192        queue.put(&mut dep).unwrap();
11193
11194        let mut still_going = task();
11195        still_going.id = "20260101-000002-dep1".to_owned();
11196        queue.put(&mut still_going).unwrap();
11197
11198        let mut blocked = task();
11199        blocked.id = "20260101-000003-main".to_owned();
11200        blocked.block(
11201            vec![dep.id.clone(), still_going.id.clone()],
11202            Some("waits on both".to_owned()),
11203        );
11204        queue.put(&mut blocked).unwrap();
11205
11206        resolve_blockers(&queue, &questions);
11207
11208        let after = queue.get(&blocked.id).unwrap();
11209        assert_eq!(
11210            after.status,
11211            TaskStatus::Blocked,
11212            "one dependency is still outstanding"
11213        );
11214        assert_eq!(after.blocked_by, [still_going.id.clone()]);
11215    }
11216
11217    #[test]
11218    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
11219        let dir = tempfile::tempdir().unwrap();
11220        let queue = Queue::at(dir.path().join("queue"));
11221        let questions = ask::Questions::at(dir.path().join("questions"));
11222
11223        let mut q = crate::ask::Question::new(
11224            "20260101-000001-main".to_owned(),
11225            crate::conduct::NODE.to_owned(),
11226            "conduct".to_owned(),
11227            "Which backend?".to_owned(),
11228            String::new(),
11229            Vec::new(),
11230        );
11231        questions.put(&mut q).unwrap();
11232        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
11233            .unwrap();
11234        questions.put(&mut q).unwrap();
11235
11236        let mut blocked = task();
11237        blocked.id = "20260101-000001-main".to_owned();
11238        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
11239        queue.put(&mut blocked).unwrap();
11240
11241        resolve_blockers(&queue, &questions);
11242
11243        let after = queue.get(&blocked.id).unwrap();
11244        assert_eq!(
11245            after.status,
11246            TaskStatus::Queued,
11247            "the only blocker resolved"
11248        );
11249        assert_eq!(after.answers.len(), 1);
11250        assert_eq!(after.answers[0].question, "Which backend?");
11251        assert_eq!(after.answers[0].answer, "SQLite");
11252
11253        // And the run this task starts next is told about it.
11254        let instruction = instruction_for(&after);
11255        assert!(instruction.contains("Which backend?"));
11256        assert!(instruction.contains("SQLite"));
11257    }
11258
11259    #[test]
11260    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
11261        let dir = tempfile::tempdir().unwrap();
11262        let queue = Queue::at(dir.path().join("queue"));
11263        let questions = ask::Questions::at(dir.path().join("questions"));
11264
11265        let mut q = crate::ask::Question::new(
11266            "20260101-000001-main".to_owned(),
11267            crate::conduct::NODE.to_owned(),
11268            "conduct".to_owned(),
11269            "Is the setup done?".to_owned(),
11270            String::new(),
11271            Vec::new(),
11272        );
11273        q.abandon("no answer within 60s of asking");
11274        questions.put(&mut q).unwrap();
11275
11276        let mut blocked = task();
11277        blocked.id = "20260101-000001-main".to_owned();
11278        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
11279        queue.put(&mut blocked).unwrap();
11280
11281        resolve_blockers(&queue, &questions);
11282
11283        let after = queue.get(&blocked.id).unwrap();
11284        assert_eq!(
11285            after.status,
11286            TaskStatus::Held,
11287            "never left blocked on nothing"
11288        );
11289        assert!(!after.operator_held(), "a machine hold, for triage");
11290        assert!(
11291            after
11292                .hold_reason
11293                .as_deref()
11294                .unwrap_or_default()
11295                .contains("went unanswered")
11296        );
11297    }
11298
11299    #[test]
11300    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
11301        // Reproduces the reported bug (task 3958): a task held out of
11302        // attempts, blocked on a `crate::conduct` follow-up question, must
11303        // come back `held` once that question is answered - never `queued`,
11304        // whatever the answer said - or it silently re-enters the
11305        // competition queue with its attempts already exhausted.
11306        let dir = tempfile::tempdir().unwrap();
11307        let queue = Queue::at(dir.path().join("queue"));
11308        let questions = ask::Questions::at(dir.path().join("questions"));
11309
11310        let mut q = crate::ask::Question::new(
11311            "20260101-000001-main".to_owned(),
11312            crate::conduct::NODE.to_owned(),
11313            "conduct".to_owned(),
11314            "How should this be handled?".to_owned(),
11315            String::new(),
11316            Vec::new(),
11317        );
11318        questions.put(&mut q).unwrap();
11319        q.answer(crate::ask::Answer::Text(
11320            "leave it held, a human will look at it later".to_owned(),
11321        ))
11322        .unwrap();
11323        questions.put(&mut q).unwrap();
11324
11325        let mut held = task();
11326        held.id = "20260101-000001-main".to_owned();
11327        held.hold_machine(Some("out of attempts".to_owned()));
11328        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
11329        queue.put(&mut held).unwrap();
11330
11331        resolve_blockers(&queue, &questions);
11332
11333        let after = queue.get(&held.id).unwrap();
11334        assert_eq!(after.status, TaskStatus::Held);
11335        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
11336        assert_eq!(
11337            after.answers[0].answer,
11338            "leave it held, a human will look at it later"
11339        );
11340    }
11341
11342    #[test]
11343    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
11344        let dir = tempfile::tempdir().unwrap();
11345        let queue = Queue::at(dir.path().join("queue"));
11346        let questions = ask::Questions::at(dir.path().join("questions"));
11347        let mut dep = task();
11348        dep.id = "20260101-000001-gone".to_owned();
11349        queue.put(&mut dep).unwrap();
11350        let mut blocked = task();
11351        blocked.id = "20260101-000003-main".to_owned();
11352        blocked.block(vec![dep.id.clone()], None);
11353        queue.put(&mut blocked).unwrap();
11354
11355        // Claimed, so `remove` cannot rewrite it and the resolver must.
11356        let claim = queue.claim(&blocked.id).unwrap();
11357        queue.remove(&dep.id, false, &questions).unwrap();
11358        drop(claim);
11359        resolve_blockers(&queue, &questions);
11360
11361        let after = queue.get(&blocked.id).unwrap();
11362        assert_eq!(after.status, TaskStatus::Queued);
11363        assert!(after.blocked_by.is_empty());
11364    }
11365
11366    #[test]
11367    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
11368        // Reproduces the reported bug: a task blocked on a task id that was
11369        // removed (`magi task rm`, or deleted by hand) can never see that id
11370        // reach `Done`, so the ordinary per-id loop has nothing to notice and
11371        // would otherwise leave the task `blocked` forever with no way for an
11372        // operator to find out why.
11373        let dir = tempfile::tempdir().unwrap();
11374        let queue = Queue::at(dir.path().join("queue"));
11375        let questions = ask::Questions::at(dir.path().join("questions"));
11376
11377        let mut still_going = task();
11378        still_going.id = "20260101-000002-dep1".to_owned();
11379        queue.put(&mut still_going).unwrap();
11380
11381        let mut blocked = task();
11382        blocked.id = "20260101-000003-main".to_owned();
11383        blocked.block(
11384            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
11385            Some("waits on both".to_owned()),
11386        );
11387        queue.put(&mut blocked).unwrap();
11388
11389        resolve_blockers(&queue, &questions);
11390
11391        let after = queue.get(&blocked.id).unwrap();
11392        assert_eq!(
11393            after.status,
11394            TaskStatus::Held,
11395            "a missing dependency must not leave the task blocked forever"
11396        );
11397        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
11398        assert!(after.blocked_by.is_empty());
11399        let reason = after.hold_reason.as_deref().unwrap_or_default();
11400        assert!(
11401            reason.contains("20260101-000001-gone"),
11402            "the missing id must be named so an operator can tell what happened: {reason}"
11403        );
11404        assert!(
11405            reason.contains(&still_going.id),
11406            "the still-valid dependency must not silently vanish from the record: {reason}"
11407        );
11408    }
11409
11410    #[test]
11411    fn instruction_for_is_unchanged_without_any_answers() {
11412        let t = task();
11413        assert_eq!(instruction_for(&t), t.instruction);
11414    }
11415
11416    #[test]
11417    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
11418        let dir = tempfile::tempdir().unwrap();
11419        let q = Queue::at(dir.path().join("queue"));
11420        let src = dir.path().join("shot.png");
11421        std::fs::write(&src, "x").unwrap();
11422        let mut t = task();
11423        q.attach(&mut t, &[src]).unwrap();
11424        let paths = task_attachments(&q, &t).unwrap();
11425        assert_eq!(paths.len(), 1);
11426        assert!(paths[0].is_absolute() && paths[0].is_file());
11427        std::fs::remove_file(&paths[0]).unwrap();
11428        let err = task_attachments(&q, &t).unwrap_err().to_string();
11429        assert!(err.contains("shot.png"), "{err}");
11430    }
11431
11432    #[tokio::test]
11433    async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
11434        let dir = tempfile::tempdir().unwrap();
11435        let queue_path = dir.path().join("queue");
11436        let queue = Queue::at(queue_path.clone());
11437        let mut t = task();
11438        t.source = Source::Agent {
11439            run: "originating-chat".into(),
11440            node: crate::queue::CHAT_NODE.into(),
11441        };
11442        let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
11443            stage: "config-fetch",
11444            target: "origin/main".into(),
11445        });
11446        record_config_failure(&mut t, &fetch);
11447        t.hold_machine(Some(format!("{fetch:#}")));
11448        let fetch_key = t.chat_notice_due().unwrap();
11449        t.chat_notices.push(fetch_key.clone());
11450        queue.put(&mut t).unwrap();
11451
11452        let queue = Queue::at(queue_path);
11453        let mut t = queue.get(&t.id).unwrap();
11454        let a = dir.path().join("a.toml");
11455        let b = dir.path().join("b.toml");
11456        for (path, text, new_cause) in [
11457            (&a, "[graph", true),
11458            (&a, "[verify", false),
11459            (&a, "[graph]\nimplementers = 'invalid-type'", true),
11460            (&b, "[graph]\nimplementers = 'invalid-type'", true),
11461        ] {
11462            t.release_operator("test", None);
11463            std::fs::write(path, text).unwrap();
11464            let error = Config::discover_fetched(dir.path(), Some(path))
11465                .await
11466                .unwrap_err();
11467            record_config_failure(&mut t, &error);
11468            t.hold_machine(Some(format!("{error:#}")));
11469            let due = t.chat_notice_due();
11470            assert_eq!(due.is_some(), new_cause, "{error:#}");
11471            if let Some(key) = due {
11472                assert_ne!(key, fetch_key);
11473                t.chat_notices.push(key);
11474            }
11475        }
11476        t.succeed();
11477        assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
11478    }
11479
11480    #[test]
11481    fn different_missing_attachments_have_distinct_persisted_notice_causes() {
11482        let dir = tempfile::tempdir().unwrap();
11483        let queue_path = dir.path().join("queue");
11484        let queue = Queue::at(queue_path.clone());
11485        let mut t = task();
11486        t.source = crate::queue::Source::Agent {
11487            run: "originating-chat".into(),
11488            node: crate::queue::CHAT_NODE.into(),
11489        };
11490        let a = dir.path().join("a.png");
11491        let b = dir.path().join("b.png");
11492        std::fs::write(&a, "a").unwrap();
11493        std::fs::write(&b, "b").unwrap();
11494        queue.attach(&mut t, &[a, b]).unwrap();
11495        let paths = task_attachments(&queue, &t).unwrap();
11496        for path in &paths {
11497            std::fs::remove_file(path).unwrap();
11498        }
11499        let missing = task_attachments(&queue, &t).unwrap_err();
11500        t.attempts += 1;
11501        let reason = missing.to_string();
11502        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
11503        let first = t.chat_notice_due().expect("first attachment notice");
11504        t.chat_notices.push(first.clone());
11505        queue.put(&mut t).unwrap();
11506
11507        let queue = Queue::at(queue_path.clone());
11508        let mut t = queue.get(&t.id).unwrap();
11509        assert!(t.chat_notice_due().is_none(), "restart does not replay");
11510        t.release_operator("test", None);
11511        t.attempts += 1;
11512        let missing = task_attachments(&queue, &t).unwrap_err();
11513        t.fail_startup_target(
11514            "startup-attachments",
11515            missing.name,
11516            "same missing attachment with regenerated wording",
11517            1,
11518        );
11519        assert!(t.chat_notice_due().is_none(), "same object stays quiet");
11520
11521        std::fs::write(&paths[0], "restored").unwrap();
11522        t.release_operator("test", None);
11523        t.attempts += 1;
11524        let missing = task_attachments(&queue, &t).unwrap_err();
11525        let reason = missing.to_string();
11526        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
11527        let second = t
11528            .chat_notice_due()
11529            .expect("different attachment must notify");
11530        assert_ne!(first, second);
11531        assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
11532    }
11533
11534    #[test]
11535    fn resumed_instruction_is_unchanged_without_any_answers() {
11536        let t = task();
11537        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
11538    }
11539
11540    #[test]
11541    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
11542        let mut t = task();
11543        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11544        // The run's own instruction on disk predates the answer: it is the
11545        // plain original text `Runner::start` saved before the operator was
11546        // ever asked anything.
11547        let old = t.instruction.clone();
11548
11549        let refreshed = resumed_instruction(&old, &t);
11550        assert!(refreshed.starts_with(&old), "the original text is kept");
11551        assert!(refreshed.contains("Which backend?"));
11552        assert!(refreshed.contains("SQLite"));
11553    }
11554
11555    #[test]
11556    fn resumed_instruction_keeps_an_original_answers_heading() {
11557        let mut t = task();
11558        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
11559        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11560
11561        let refreshed = resumed_instruction(&t.instruction, &t);
11562
11563        assert!(
11564            refreshed.starts_with(&t.instruction),
11565            "an answers heading in the original instruction is not the appended block"
11566        );
11567        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
11568        assert!(refreshed.contains("Which backend?"));
11569        assert!(refreshed.contains("SQLite"));
11570
11571        let repeated = resumed_instruction(&refreshed, &t);
11572        assert_eq!(
11573            repeated, refreshed,
11574            "only the final appended block is refreshed"
11575        );
11576    }
11577
11578    #[test]
11579    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
11580        let mut t = task();
11581        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11582
11583        // A first resume appends the block; a second resume of the same run,
11584        // with no new answer in between, must reproduce exactly the same
11585        // text rather than appending the block a second time.
11586        let once = resumed_instruction(&t.instruction, &t);
11587        let twice = resumed_instruction(&once, &t);
11588        assert_eq!(once, twice);
11589        assert_eq!(once.matches("Which backend?").count(), 1);
11590
11591        // A later answer replaces the block wholesale rather than growing it.
11592        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
11593        let refreshed = resumed_instruction(&once, &t);
11594        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
11595        assert!(refreshed.contains("Which backend?"));
11596        assert!(refreshed.contains("Which cache?"));
11597    }
11598
11599    #[test]
11600    fn prepare_instruction_covers_all_three_starters() {
11601        let mut t = task();
11602        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11603
11604        // Start: a fresh run gets the task text plus every answer so far —
11605        // exactly `instruction_for`.
11606        assert_eq!(
11607            prepare_instruction(&Starter::Start, None, &t),
11608            Some(instruction_for(&t))
11609        );
11610
11611        // Resume: the run's prior instruction is refreshed with the answer,
11612        // not discarded and not left stale.
11613        let old = t.instruction.clone();
11614        assert_eq!(
11615            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
11616            Some(resumed_instruction(&old, &t))
11617        );
11618
11619        // Review: a review-only pass builds its own instruction from the
11620        // branch's history in `crate::graph`, with no task statement at all -
11621        // this boundary must leave it alone.
11622        assert_eq!(
11623            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
11624            None
11625        );
11626    }
11627
11628    #[test]
11629    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
11630        assert_eq!(
11631            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
11632            Starter::Review("magi/eba2/A".to_owned())
11633        );
11634    }
11635
11636    #[test]
11637    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
11638        assert_eq!(
11639            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
11640            Starter::Start,
11641            "a vanished review branch must not fall back to resuming the old run either"
11642        );
11643    }
11644
11645    #[test]
11646    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
11647        let mut t = task();
11648        t.start("old-run".to_owned());
11649        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
11650        t.release();
11651        let branch = t.review_branch.take();
11652        assert_eq!(
11653            choose_starter(branch.as_deref(), true, Some("old-run")),
11654            Starter::Review("magi/eba2/A".to_owned()),
11655            "a review wins over resuming the old run"
11656        );
11657    }
11658
11659    #[test]
11660    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
11661        assert_eq!(
11662            choose_starter(None, false, Some("some-run")),
11663            Starter::Resume("some-run".to_owned())
11664        );
11665        assert_eq!(choose_starter(None, false, None), Starter::Start);
11666    }
11667
11668    #[test]
11669    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
11670        let mut released = task();
11671        released.start("stalled-run".to_owned());
11672        released.requeue();
11673        let unfinished = (!released.fresh_start)
11674            .then(|| Some("stalled-run".to_owned()))
11675            .flatten();
11676        assert_eq!(
11677            choose_starter(None, false, unfinished.as_deref()),
11678            Starter::Start,
11679            "release keeps run history but must not resume it"
11680        );
11681        assert_eq!(released.runs, ["stalled-run"]);
11682    }
11683
11684    fn stopped_public_run(status: RunStatus) -> RunState {
11685        let mut state = run_state(status);
11686        state.driver_exited = true;
11687        state.config.graph.land = true;
11688        state.config.graph.review_rounds = 1;
11689        state.reviews = vec![review_round(1)];
11690        state.merge = Some(crate::run::MergeOutcome {
11691            mode: MergeMode::Pr,
11692            ok: false,
11693            detail: "landing stopped".into(),
11694            empty: false,
11695        });
11696        state.pr = Some(crate::run::PrRecord {
11697            url: "https://example.test/pull/1".into(),
11698            number: 1,
11699            state: "open".into(),
11700            checks: "red".into(),
11701            round: 1,
11702            rounds: 1,
11703            red_at_merge: Vec::new(),
11704        });
11705        state
11706    }
11707
11708    #[test]
11709    fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
11710        for status in [RunStatus::Blocked, RunStatus::Gating] {
11711            let home = tempfile::tempdir().unwrap();
11712            let mut state = stopped_public_run(status);
11713            state.save_under(home.path()).unwrap();
11714            assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
11715            assert!(!exhausted_review_budget(&state));
11716            let mut task = held_task_with(&state.id);
11717            task.release();
11718            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
11719            assert_eq!(
11720                choose_starter(None, false, unfinished.as_deref()),
11721                Starter::Resume(state.id.clone())
11722            );
11723            let question = action_question(&state.id, resume_action(&state.id));
11724            assert_eq!(
11725                decide_action(&task, &question, &PHRASES_EN, |_| Ok(state.clone())),
11726                ActionDecision::Resume(state.id.clone())
11727            );
11728            // The control-plane command uses this same preflight before pinning.
11729            assert_eq!(
11730                crate::resume::validate(home.path(), &state.id).unwrap().id,
11731                state.id
11732            );
11733            let queue = Queue::at(home.path().join("queue"));
11734            let mut controlled = Task::new(
11735                "resume land".into(),
11736                state.instruction.clone(),
11737                state.repo.clone(),
11738                Source::Agent {
11739                    run: "talk".into(),
11740                    node: crate::queue::CHAT_NODE.into(),
11741                },
11742            );
11743            controlled.runs.push(state.id.clone());
11744            controlled.hold_machine(Some("land stopped".into()));
11745            queue.put(&mut controlled).unwrap();
11746            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
11747            assert_eq!(resumed.status, TaskStatus::Queued);
11748            assert_eq!(
11749                resumed.resume_override.unwrap().pinned_run,
11750                Some(state.id.clone())
11751            );
11752            assert_eq!(resumed.attempts, 0);
11753        }
11754    }
11755
11756    #[test]
11757    fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
11758        for review_rounds in [0, 1] {
11759            let home = tempfile::tempdir().unwrap();
11760            let mut state = run_state(RunStatus::Blocked);
11761            state.config.graph.review_rounds = review_rounds;
11762            if review_rounds > 0 {
11763                let mut review = review_round(1);
11764                review.clean = true;
11765                state.reviews = vec![review];
11766            }
11767            state.gate_ran = true;
11768            state.gate = vec![crate::run::CommandOutcome {
11769                command: "verify".into(),
11770                code: Some(1),
11771                output_tail: "gate failed after repair budget exhausted".into(),
11772                duration_ms: 0,
11773                resource_blocked: false,
11774            }];
11775            state.save_under(home.path()).unwrap();
11776            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
11777            assert!(exhausted_review_budget(&state));
11778            let mut task = held_task_with(&state.id);
11779            task.release();
11780            assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
11781            let question = action_question(&state.id, resume_action(&state.id));
11782            assert_ne!(
11783                decide_action(&task, &question, &PHRASES_EN, |_| Ok(state.clone())),
11784                ActionDecision::Resume(state.id.clone())
11785            );
11786            let error = crate::resume::validate(home.path(), &state.id)
11787                .unwrap_err()
11788                .to_string();
11789            assert!(!error.contains("review budget exhausted"), "{error}");
11790            assert!(
11791                error.contains(if review_rounds == 0 {
11792                    "review is disabled"
11793                } else {
11794                    "gate already ran"
11795                }),
11796                "{error}"
11797            );
11798
11799            // An unexecuted gate still has work to do with or without reviews.
11800            state.gate_ran = false;
11801            state.gate.clear();
11802            assert!(!exhausted_review_budget(&state));
11803            assert_eq!(
11804                unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
11805                Some(state.id)
11806            );
11807        }
11808    }
11809
11810    #[test]
11811    fn resource_blocked_verification_resumes_the_same_run() {
11812        for (kind, stage) in [
11813            ("cache", "clean"),
11814            ("coordination", "clean"),
11815            ("cache", "review-e2e"),
11816            ("coordination", "no-reviews"),
11817            ("coordination", "handoff"),
11818        ] {
11819            let home = tempfile::tempdir().unwrap();
11820            let mut state = run_state(RunStatus::Blocked);
11821            state.config.graph.review_rounds = 1;
11822            let mut review = review_round(1);
11823            review.clean = true;
11824            state.reviews = vec![review];
11825            if stage == "review-e2e" {
11826                let review = &mut state.reviews[0];
11827                review.clean = false;
11828                review.blocking = 1;
11829                review.e2e = vec![crate::run::CommandOutcome {
11830                    command: "verify".into(),
11831                    code: None,
11832                    output_tail: "resource wait expired".into(),
11833                    duration_ms: 0,
11834                    resource_blocked: true,
11835                }];
11836            } else if stage == "no-reviews" {
11837                state.config.graph.review_rounds = 0;
11838                state.reviews.clear();
11839            } else if stage == "handoff" {
11840                // A completed final verification can hand off to the gate
11841                // even when the review still carries contested findings.
11842                let review = &mut state.reviews[0];
11843                review.clean = false;
11844                review.blocking = 1;
11845                review.e2e = vec![crate::run::CommandOutcome {
11846                    command: "verify".into(),
11847                    code: Some(0),
11848                    output_tail: String::new(),
11849                    duration_ms: 0,
11850                    resource_blocked: false,
11851                }];
11852            }
11853            state.gate_ran = false;
11854            state.resource_block = Some(crate::run::ResourceBlock {
11855                cause: crate::run::ResourceBlockCause::Other,
11856                node: if stage == "review-e2e" {
11857                    "review"
11858                } else {
11859                    "gate"
11860                }
11861                .into(),
11862                kind: kind.into(),
11863                detail: "resource wait expired".into(),
11864                at: jiff::Timestamp::now(),
11865            });
11866            state.save_under(home.path()).unwrap();
11867            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
11868            assert!(!exhausted_review_budget(&state));
11869            let mut task = held_task_with(&state.id);
11870            task.release();
11871            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
11872            assert_eq!(
11873                choose_starter(None, false, unfinished.as_deref()),
11874                Starter::Resume(state.id.clone())
11875            );
11876            let question = action_question(&state.id, resume_action(&state.id));
11877            assert_eq!(
11878                decide_action(&task, &question, &PHRASES_EN, |_| Ok(state.clone())),
11879                ActionDecision::Resume(state.id.clone())
11880            );
11881            assert_eq!(
11882                crate::resume::validate(home.path(), &state.id).unwrap().id,
11883                state.id
11884            );
11885            let queue = Queue::at(home.path().join("queue"));
11886            let mut controlled = Task::new(
11887                "resume verification".into(),
11888                state.instruction.clone(),
11889                state.repo.clone(),
11890                Source::Agent {
11891                    run: "talk".into(),
11892                    node: crate::queue::CHAT_NODE.into(),
11893                },
11894            );
11895            controlled.runs.push(state.id.clone());
11896            controlled.hold_machine(Some("verification resource unavailable".into()));
11897            queue.put(&mut controlled).unwrap();
11898            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
11899            assert_eq!(resumed.status, TaskStatus::Queued);
11900            assert_eq!(
11901                resumed.resume_override.unwrap().pinned_run,
11902                Some(state.id.clone())
11903            );
11904            assert_eq!(resumed.attempts, 0);
11905
11906            // A genuinely unresolved final review still exhausts the budget.
11907            state.config.graph.review_rounds = 1;
11908            let mut unresolved = review_round(1);
11909            unresolved.blocking = 1;
11910            state.reviews = vec![unresolved];
11911            state.resource_block = None;
11912            state.save_under(home.path()).unwrap();
11913            assert!(exhausted_review_budget(&state));
11914            assert!(crate::resume::validate(home.path(), &state.id).is_err());
11915        }
11916    }
11917
11918    #[tokio::test]
11919    async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
11920        if !crate::standalone_test(
11921            "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
11922        ) {
11923            return;
11924        }
11925        let home = tempfile::tempdir().unwrap();
11926        let mut owner = stopped_public_run(RunStatus::Blocked);
11927        owner.save_under(home.path()).unwrap();
11928        let history = vec![owner.id.clone()];
11929        let repo = owner.repo.clone();
11930        let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
11931        let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
11932        let initial =
11933            std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
11934        assert!(
11935            initial.is_pending(),
11936            "a busy record must not hold or resume the task"
11937        );
11938        owner.retired_to = Some("20260101-000001-bbbb".into());
11939        owner.save_under(home.path()).unwrap();
11940        drop(lock);
11941        let result = tokio::time::timeout(Duration::from_secs(10), lookup)
11942            .await
11943            .expect("ownership lock released")
11944            .expect("read settled owner");
11945        assert!(
11946            result.is_none(),
11947            "the retired owner must not be resumed from a stale read"
11948        );
11949    }
11950
11951    #[tokio::test]
11952    async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
11953        if !crate::standalone_test(
11954            "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
11955        ) {
11956            return;
11957        }
11958        let home = tempfile::tempdir().unwrap();
11959        let mut owner = stopped_public_run(RunStatus::Blocked);
11960        let repo = tempfile::tempdir().unwrap();
11961        crate::git::git(repo.path(), &["init"]).await.unwrap();
11962        owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
11963        owner.id = "20260101-000000-aaaa".into();
11964        owner.save_under(home.path()).unwrap();
11965        let mut successor = run_state(RunStatus::Blocked);
11966        successor.id = "20260101-000001-bbbb".into();
11967        successor.save_under(home.path()).unwrap();
11968        let runs = vec![owner.id.clone(), successor.id.clone()];
11969        assert_eq!(
11970            public_resume_owner(home.path(), &runs, &owner.repo)
11971                .await
11972                .unwrap()
11973                .unwrap()
11974                .id,
11975            owner.id
11976        );
11977        let subdir = owner.repo.join("nested");
11978        std::fs::create_dir(&subdir).unwrap();
11979        assert_eq!(
11980            public_resume_owner(home.path(), &runs, &subdir)
11981                .await
11982                .unwrap()
11983                .unwrap()
11984                .id,
11985            owner.id
11986        );
11987        #[cfg(unix)]
11988        {
11989            let alias = home.path().join("repo-alias");
11990            std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
11991            assert_eq!(
11992                public_resume_owner(home.path(), &runs, &alias.join("nested"))
11993                    .await
11994                    .unwrap()
11995                    .unwrap()
11996                    .id,
11997                owner.id
11998            );
11999        }
12000        let different = tempfile::tempdir().unwrap();
12001        crate::git::git(different.path(), &["init"]).await.unwrap();
12002        assert!(
12003            public_resume_owner(home.path(), &runs, different.path())
12004                .await
12005                .is_err()
12006        );
12007        std::fs::remove_file(
12008            home.path()
12009                .join("runs")
12010                .join(&successor.id)
12011                .join("run.json"),
12012        )
12013        .unwrap();
12014        assert!(
12015            public_resume_owner(home.path(), &runs, &owner.repo)
12016                .await
12017                .is_err()
12018        );
12019    }
12020
12021    #[test]
12022    fn an_ordinary_release_keeps_a_resumable_run_available() {
12023        let mut released = task();
12024        released.start("stalled-run".to_owned());
12025        released.release();
12026        let unfinished = (!released.fresh_start)
12027            .then(|| Some("stalled-run".to_owned()))
12028            .flatten();
12029        assert_eq!(
12030            choose_starter(None, false, unfinished.as_deref()),
12031            Starter::Resume("stalled-run".to_owned()),
12032            "manual release must preserve the normal resume path"
12033        );
12034    }
12035
12036    #[test]
12037    fn resume_refusals_explain_admission_without_changing_task_or_run() {
12038        crate::run::pin_test_home();
12039        use crate::handover::{ResumeRefusal, resume_refusal_under};
12040        let home = tempfile::tempdir().unwrap();
12041        let mut exhausted = run_state(RunStatus::Blocked);
12042        exhausted.driver_exited = true;
12043        exhausted.config.graph.review_rounds = 3;
12044        exhausted.reviews = (1..=3).map(review_round).collect();
12045        for refusal in [
12046            ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
12047            ResumeRefusal::Status(RunStatus::Ready),
12048            ResumeRefusal::Released("20261022-000000-aaaa".into()),
12049            ResumeRefusal::Retired("retirement-successor".into()),
12050            ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
12051        ] {
12052            let mut state = exhausted.clone();
12053            let expected = match refusal {
12054                ResumeRefusal::Status(_) => {
12055                    state.status = RunStatus::Ready;
12056                    "status `ready`"
12057                }
12058                ResumeRefusal::Released(ref target) => {
12059                    state.released_to = Some(target.clone());
12060                    "execution was released"
12061                }
12062                ResumeRefusal::Retired(ref target) => {
12063                    state.retired_to = Some(target.clone());
12064                    "execution was retired"
12065                }
12066                ResumeRefusal::OwnershipTransferred(ref target) => {
12067                    state.pr_taken_over_by = Some(target.clone());
12068                    "PR ownership was transferred"
12069                }
12070                _ => "review budget exhausted (3/3 rounds used)",
12071            };
12072            assert_eq!(
12073                resume_refusal_under(&state, Some(home.path())),
12074                Some(refusal.clone())
12075            );
12076            assert_eq!(
12077                refusal.successor(),
12078                state
12079                    .released_to
12080                    .as_deref()
12081                    .or(state.retired_to.as_deref())
12082                    .or(state.pr_taken_over_by.as_deref())
12083            );
12084            state.save_under(home.path()).unwrap();
12085            let queue = Queue::at(home.path().join("queue"));
12086            let mut task = Task::new(
12087                "retained implementation".into(),
12088                state.instruction.clone(),
12089                state.repo.clone(),
12090                Source::Agent {
12091                    run: "talk".into(),
12092                    node: crate::queue::CHAT_NODE.into(),
12093                },
12094            );
12095            task.runs.push(state.id.clone());
12096            task.hold_machine(Some("stopped".into()));
12097            queue.put(&mut task).unwrap();
12098            let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
12099            let before_run = serde_json::to_value(&state).unwrap();
12100            let error = crate::chat_control::resume(&queue, home.path(), &state.id)
12101                .unwrap_err()
12102                .to_string();
12103            assert!(error.contains(expected), "{error}");
12104            assert!(!error.contains("only a stalled or blocked"), "{error}");
12105            if matches!(refusal, ResumeRefusal::Status(_)) {
12106                assert!(
12107                    error.contains("is final; there is nothing left to resume"),
12108                    "{error}"
12109                );
12110            }
12111            if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
12112                assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
12113                assert!(error.contains("review-only successor with a new review budget"));
12114                assert!(error.contains("does not resume this run"));
12115            }
12116            for target in [
12117                &state.released_to,
12118                &state.retired_to,
12119                &state.pr_taken_over_by,
12120            ]
12121            .into_iter()
12122            .flatten()
12123            {
12124                let short = if state.retired_to.as_ref() == Some(target) {
12125                    target.as_str()
12126                } else {
12127                    crate::run::short_of(target)
12128                };
12129                assert!(
12130                    error.contains(&format!("run {short}; inspect `magi show {short}`")),
12131                    "{error}"
12132                );
12133                if short != target {
12134                    assert!(!error.contains(target), "full successor id leaked: {error}");
12135                }
12136            }
12137            assert_eq!(
12138                serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
12139                before_task
12140            );
12141            assert_eq!(
12142                serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
12143                    .unwrap(),
12144                before_run
12145            );
12146            let question = action_question(&state.id, resume_action(&state.id));
12147            for phrases in [&PHRASES_EN, &PHRASES_JA] {
12148                let ActionDecision::Refuse(detail) =
12149                    decide_action(&task, &question, phrases, |_| Ok(state.clone()))
12150                else {
12151                    panic!("refusal expected");
12152                };
12153                assert!(detail.contains(expected), "{detail}");
12154            }
12155        }
12156        // Preserve predicate ordering, while keeping every recorded destination visible.
12157        exhausted.status = RunStatus::Ready;
12158        exhausted.released_to = Some("released".into());
12159        exhausted.retired_to = Some("retired".into());
12160        exhausted.pr_taken_over_by = Some("owner".into());
12161        let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
12162        assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
12163        let detail = reason.diagnostic(&exhausted);
12164        for target in ["released", "retired", "owner"] {
12165            assert!(detail.contains(&format!("magi show {target}")));
12166        }
12167    }
12168
12169    #[test]
12170    fn resume_checkpoint_admission_uses_the_supplied_question_store() {
12171        let home = tempfile::tempdir().unwrap();
12172        let mut state = run_state(RunStatus::Blocked);
12173        state.driver_exited = true;
12174        state.config.graph.review_rounds = 1;
12175        state.reviews = vec![review_round(1)];
12176        assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
12177        for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
12178            let mut saved = state.clone();
12179            match checkpoint {
12180                "publication" => saved.pr_publication_pending = true,
12181                "approval" => {
12182                    saved.land_approval = Some(crate::run::LandApproval {
12183                        question: "approval".into(),
12184                        head: "head".into(),
12185                    })
12186                }
12187                "armed" => saved.land_armed_head = Some("head".into()),
12188                "landing" => saved.status = RunStatus::Landing,
12189                _ => {
12190                    let mut question = ask::Question::new(
12191                        saved.id.clone(),
12192                        "review".into(),
12193                        "review-1".into(),
12194                        "continue?".into(),
12195                        String::new(),
12196                        vec!["continue".into()],
12197                    );
12198                    ask::Questions::at(home.path().join("questions"))
12199                        .put(&mut question)
12200                        .unwrap();
12201                }
12202            }
12203            saved.save_under(home.path()).unwrap();
12204            assert!(
12205                crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
12206                "{checkpoint}"
12207            );
12208            assert!(
12209                crate::resume::validate(home.path(), &saved.id).is_ok(),
12210                "{checkpoint}"
12211            );
12212        }
12213    }
12214
12215    #[test]
12216    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
12217        let mut state = run_state(RunStatus::Blocked);
12218        state.config.graph.review_rounds = 3;
12219        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
12220        assert!(exhausted_review_budget(&state));
12221
12222        // One round still unused: resuming can still ask a reviewer something.
12223        state.reviews.pop();
12224        assert!(!exhausted_review_budget(&state));
12225
12226        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
12227        // count: only a `Blocked` run re-enters the review loop on resume.
12228        let mut stalled = run_state(RunStatus::Stalled);
12229        stalled.config.graph.review_rounds = 1;
12230        stalled.reviews = vec![review_round(1)];
12231        assert!(!exhausted_review_budget(&stalled));
12232    }
12233
12234    fn review_round(round: usize) -> crate::run::ReviewRound {
12235        crate::run::ReviewRound {
12236            round,
12237            head: "deadbeef".to_owned(),
12238            verified_head: None,
12239            verified_at: None,
12240            reviews: Vec::new(),
12241            e2e: Vec::new(),
12242            verify_retried: false,
12243            e2e_deferred: false,
12244            e2e_defer_reason: None,
12245            fix: None,
12246            blocking: 0,
12247            answered: 1,
12248            expected: 1,
12249            clean: false,
12250            progressed: true,
12251            vote_split: false,
12252            reconsideration: Vec::new(),
12253            verdict: None,
12254        }
12255    }
12256
12257    #[test]
12258    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
12259        let mut run = RunState::new(
12260            PathBuf::from("/repo"),
12261            "main".to_owned(),
12262            "abc1234def".to_owned(),
12263            "add retries".to_owned(),
12264            Config::default(),
12265        );
12266        run.status = RunStatus::Judging;
12267        run.parked = true;
12268        let mut task = Task::new(
12269            "add retries".to_owned(),
12270            "add retries".to_owned(),
12271            PathBuf::from("/repo"),
12272            crate::queue::Source::Human,
12273        );
12274        task.status = TaskStatus::Failed;
12275        task.runs = vec![run.id.clone()];
12276        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
12277        assert!(with(&task, &run), "parked after judging is the case");
12278        let mut parked_task = task.clone();
12279        parked_task.status = TaskStatus::Parked;
12280        assert!(with(&parked_task, &run), "the Parked status is the case");
12281
12282        let mut not_parked = run.clone();
12283        not_parked.parked = false;
12284        not_parked.status = RunStatus::Stalled;
12285        assert!(!with(&task, &not_parked), "a stall is the conductor's");
12286
12287        let mut fresh = task.clone();
12288        fresh.fresh_start = true;
12289        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
12290
12291        let mut review = task.clone();
12292        review.review_branch = Some("magi/x/A".to_owned());
12293        assert!(!with(&review, &run), "review is ranked before resume");
12294
12295        let mut held = task.clone();
12296        held.status = TaskStatus::Held;
12297        assert!(!with(&held, &run), "a hold stays visible to the conductor");
12298
12299        let mut released = run.clone();
12300        released.released_to = Some("20260901-000000-new1".to_owned());
12301        assert!(!with(&task, &released), "nothing left to resume into");
12302
12303        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
12304            "unreadable"
12305        )));
12306    }
12307
12308    #[test]
12309    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
12310        let mut released = RunState::new(
12311            PathBuf::from("/repo"),
12312            "main".to_owned(),
12313            "abc1234def".to_owned(),
12314            "add retries".to_owned(),
12315            Config::default(),
12316        );
12317        released.status = RunStatus::Blocked;
12318        assert_eq!(
12319            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
12320            Some(released.id.clone())
12321        );
12322        released.released_to = Some("20260901-000000-new1".to_owned());
12323        assert_eq!(
12324            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
12325            None,
12326            "there is nothing left to resume it into"
12327        );
12328    }
12329
12330    #[test]
12331    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
12332        // Mirrors the failure this exists to close: a task's last run ended
12333        // `Blocked` with the review budget spent, `crate::conduct` chose
12334        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
12335        // evidence), and without this check `attempt` would go on treating
12336        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
12337        // review loop iterates zero times over an already-spent budget, so
12338        // the resumed run settles right back to `Blocked` having asked nobody
12339        // anything, and `Requeue`'s promised fresh competition never happens.
12340        let mut exhausted = RunState::new(
12341            PathBuf::from("/repo"),
12342            "main".to_owned(),
12343            "abc1234def".to_owned(),
12344            "add retries".to_owned(),
12345            Config::default(),
12346        );
12347        exhausted.status = RunStatus::Blocked;
12348        exhausted.config.graph.review_rounds = 1;
12349        exhausted.reviews = vec![review_round(1)];
12350
12351        assert_eq!(
12352            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
12353            None,
12354            "an exhausted `Blocked` run must not be offered as resumable"
12355        );
12356
12357        // A `Blocked` run with rounds still unused is genuinely worth
12358        // resuming, and must still be found.
12359        let mut has_budget_left = RunState::new(
12360            PathBuf::from("/repo"),
12361            "main".to_owned(),
12362            "abc1234def".to_owned(),
12363            "add retries".to_owned(),
12364            Config::default(),
12365        );
12366        has_budget_left.status = RunStatus::Blocked;
12367        has_budget_left.config.graph.review_rounds = 3;
12368        has_budget_left.reviews = vec![review_round(1)];
12369
12370        assert_eq!(
12371            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
12372                Ok(has_budget_left.clone())
12373            }),
12374            Some(has_budget_left.id.clone())
12375        );
12376    }
12377
12378    #[test]
12379    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
12380        let mut run = RunState::new(
12381            PathBuf::from("/repo"),
12382            "main".to_owned(),
12383            "abc1234def".to_owned(),
12384            "add retries".to_owned(),
12385            Config::default(),
12386        );
12387        run.status = RunStatus::Blocked;
12388        run.config.graph.review_rounds = 1;
12389        run.reviews = vec![review_round(1)];
12390        run.pr_publication_pending = true;
12391        assert_eq!(
12392            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
12393            Some(run.id.clone()),
12394            "a spent review budget must not turn a failed publication into a re-competition"
12395        );
12396    }
12397
12398    #[test]
12399    fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
12400        let mut task = Task::new(
12401            "recover work".into(),
12402            "recover work".into(),
12403            PathBuf::from("/repo"),
12404            crate::queue::Source::Human,
12405        );
12406        let mut history = std::collections::BTreeMap::new();
12407        for index in 0..8 {
12408            let mut run = run_state(RunStatus::Blocked);
12409            run.id = format!("20260101-000000-{index:04}");
12410            run.base_commit = format!("upstream-{index}");
12411            // Seven empty newer attempts must not erase the old recovery owner.
12412            if index > 0 {
12413                run.candidates.clear();
12414            }
12415            task.runs.extend([run.id.clone(), run.id.clone()]);
12416            history.insert(run.id.clone(), run);
12417            task.requeue();
12418        }
12419        let check = |task: &Task, starter: &Starter, limit| {
12420            retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
12421        };
12422        assert!(
12423            check(&task, &Starter::Start, 8)
12424                .unwrap()
12425                .contains("8 unretired")
12426        );
12427        assert!(check(&task, &Starter::Start, 9).is_none());
12428        assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
12429        task.release_operator("owner", None);
12430        assert_eq!(task.attempts, 0);
12431        let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
12432        assert!(check(&restored, &Starter::Start, 8).is_some());
12433        assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
12434        assert!(check(&restored, &Starter::Start, 0).is_none());
12435    }
12436
12437    #[test]
12438    fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
12439        let mut task = Task::new(
12440            "recover work".into(),
12441            "recover work".into(),
12442            PathBuf::from("/repo"),
12443            crate::queue::Source::Human,
12444        );
12445        let mut run = run_state(RunStatus::Superseded);
12446        run.candidates.clear();
12447        task.runs.push(run.id.clone());
12448        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
12449        run.retired_to = Some("authority".into());
12450        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
12451        run.retired_to = None;
12452        run.released_to = Some("authority".into());
12453        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
12454        assert!(
12455            retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
12456                .unwrap()
12457                .contains("Cannot verify")
12458        );
12459        // Resuming an existing owner needs no new inventory or worktree budget.
12460        assert!(
12461            retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
12462                panic!("resume must not load historical attempts")
12463            })
12464            .is_none()
12465        );
12466    }
12467
12468    #[test]
12469    fn retired_resume_requires_a_valid_same_repository_authority() {
12470        let mut source = run_state(RunStatus::Blocked);
12471        let mut empty = run_state(RunStatus::Blocked);
12472        empty.retired_to = Some(source.id.clone());
12473        let runs = vec![source.id.clone(), empty.id.clone()];
12474        let resolve = |source: &RunState, empty: &RunState| {
12475            unfinished_run_with(&runs, "fixture", |id| {
12476                if id == source.id {
12477                    Ok(source.clone())
12478                } else if id == empty.id {
12479                    Ok(empty.clone())
12480                } else {
12481                    bail!("unreadable authority")
12482                }
12483            })
12484        };
12485        assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
12486        assert_eq!(
12487            choose_starter(None, false, resolve(&source, &empty).as_deref()),
12488            Starter::Resume(source.id.clone())
12489        );
12490        source.retired_to = Some(empty.id.clone());
12491        assert!(
12492            resolve(&source, &empty).is_none(),
12493            "cycles do not revive obsolete runs"
12494        );
12495        source.retired_to = None;
12496        source.repo = PathBuf::from("/another-repository");
12497        assert!(resolve(&source, &empty).is_none());
12498        source.repo = empty.repo.clone();
12499        source.released_to = Some("later".into());
12500        assert!(resolve(&source, &empty).is_none());
12501        empty.retired_to = Some("unlisted-run".into());
12502        assert!(resolve(&source, &empty).is_none());
12503    }
12504
12505    #[test]
12506    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
12507        // A task whose history holds an *older* run that still looks
12508        // resumable (say, a competition `Runner::review` was started
12509        // alongside after that older run went `Stalled`) and a *newest* run
12510        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
12511        // on this task must mean a fresh competition — falling back to the
12512        // stale, superseded `Stalled` run instead would resurrect history
12513        // nothing asked to revisit and silently defeat the requeue.
12514        let mut older_stalled = RunState::new(
12515            PathBuf::from("/repo"),
12516            "main".to_owned(),
12517            "abc1234def".to_owned(),
12518            "add retries".to_owned(),
12519            Config::default(),
12520        );
12521        older_stalled.status = RunStatus::Stalled;
12522
12523        let mut newest_exhausted = RunState::new(
12524            PathBuf::from("/repo"),
12525            "main".to_owned(),
12526            "abc1234def".to_owned(),
12527            "add retries".to_owned(),
12528            Config::default(),
12529        );
12530        newest_exhausted.status = RunStatus::Blocked;
12531        newest_exhausted.config.graph.review_rounds = 1;
12532        newest_exhausted.reviews = vec![review_round(1)];
12533
12534        assert_eq!(
12535            unfinished_run_with(
12536                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
12537                "t",
12538                |_| Ok(newest_exhausted.clone())
12539            ),
12540            None,
12541            "the newest run is exhausted, so nothing here is worth resuming - \
12542             least of all the older, already-superseded run"
12543        );
12544    }
12545
12546    #[test]
12547    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
12548        assert_eq!(
12549            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
12550                Err(anyhow::anyhow!("fixture is absent"))
12551            }),
12552            None
12553        );
12554    }
12555
12556    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
12557        let mut q = ask::Question::new(
12558            run.to_owned(),
12559            "implement".to_owned(),
12560            "impl-A".to_owned(),
12561            "continue?".to_owned(),
12562            String::new(),
12563            vec!["resume で続行する".to_owned(), "other".to_owned()],
12564        );
12565        q.actions.insert("resume で続行する".to_owned(), action);
12566        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
12567            .unwrap();
12568        q
12569    }
12570
12571    fn held_task_with(run: &str) -> Task {
12572        let mut t = task();
12573        t.runs = vec![run.to_owned()];
12574        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
12575        t
12576    }
12577
12578    fn resume_action(run: &str) -> ask::ChoiceAction {
12579        ask::ChoiceAction::Resume { run: run.into() }
12580    }
12581
12582    #[test]
12583    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
12584        for parked in [false, true] {
12585            let mut t = task();
12586            t.start("A".into());
12587            t.start("B".into());
12588            assert_eq!(t.runs, vec!["A", "B"]);
12589            t.start("A".into());
12590            let mut resumed = run_state(RunStatus::Blocked);
12591            resumed.id = "A".into();
12592            resumed.parked = parked;
12593            resumed.driver_exited = true;
12594            t.hold_machine(Some("resumed run stopped".into()));
12595            let q = action_question("A", resume_action("A"));
12596            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
12597            assert_eq!(
12598                decide_action(&t, &q, &PHRASES_EN, |id| {
12599                    assert_eq!(id, "A");
12600                    Ok(resumed.clone())
12601                }),
12602                ActionDecision::Resume("A".into())
12603            );
12604            assert_eq!(
12605                action_standing(&t, &action_question("B", resume_action("B"))),
12606                ActionStanding::Stale
12607            );
12608            t.release_operator("cli", None);
12609            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
12610                assert_eq!(id, "A");
12611                Ok(resumed.clone())
12612            });
12613            assert_eq!(
12614                choose_starter(None, false, unfinished.as_deref()),
12615                Starter::Resume("A".into())
12616            );
12617            assert_eq!(t.runs, vec!["B", "A"]);
12618        }
12619    }
12620
12621    #[test]
12622    fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
12623        let mut state = crate::land::tests::repair_state(true, true);
12624        state.status = RunStatus::Landing;
12625        state.parked = true;
12626        state.driver_exited = true;
12627        let mut q = ask::Question::new(
12628            state.id.clone(),
12629            land::APPROVAL_NODE.into(),
12630            "land".into(),
12631            "Merge?".into(),
12632            String::new(),
12633            vec![land::APPROVE.into(), land::HOLD.into()],
12634        );
12635        q.id = state.id.clone();
12636        state.land_approval = Some(crate::run::LandApproval {
12637            question: q.id.clone(),
12638            head: "current-head".into(),
12639        });
12640        assert!(land::upgrade_repair_choice(&mut q, &state));
12641        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12642        let mut task = held_task_with(&state.id);
12643        task.status = TaskStatus::Parked;
12644        assert_eq!(
12645            decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
12646            ActionDecision::Resume(state.id.clone())
12647        );
12648        q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
12649        q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
12650        task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
12651        assert_eq!(
12652            decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
12653            ActionDecision::Resume(state.id.clone()),
12654            "a repair answer newer than the manual hold resumes the existing owner"
12655        );
12656        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
12657        for answered_at in [q.answered_at, None] {
12658            let mut older = q.clone();
12659            older.answered_at = answered_at;
12660            let refused = decide_action(&task, &older, &PHRASES_EN, |_| {
12661                panic!("a later manual hold must prevent dispatch")
12662            });
12663            let ActionDecision::Refuse(reason) = refused else {
12664                panic!("expected an actionable refusal, got {refused:?}");
12665            };
12666            assert!(reason.contains("later operator decision"));
12667            assert!(reason.contains(&format!("magi task release {}", task.id)));
12668        }
12669        task.operator_decided_at = None;
12670        let mut superseded = state.clone();
12671        superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
12672        assert_eq!(
12673            decide_action(&task, &q, &PHRASES_EN, |_| Ok(superseded)),
12674            ActionDecision::Stale
12675        );
12676        for case in 1..4 {
12677            let mut changed = state.clone();
12678            match case {
12679                1 => changed.status = RunStatus::Blocked,
12680                2 => changed.released_to = Some("new-owner".into()),
12681                _ => changed.land_approval.as_mut().unwrap().head.clear(),
12682            }
12683            assert!(matches!(
12684                decide_action(&task, &q, &PHRASES_EN, |_| Ok(changed)),
12685                ActionDecision::Refuse(_)
12686            ));
12687        }
12688        assert!(matches!(
12689            decide_action(&task, &q, &PHRASES_EN, |_| anyhow::bail!("missing owner")),
12690            ActionDecision::Refuse(_)
12691        ));
12692        task.runs.push("replacement".into());
12693        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
12694        assert_eq!(
12695            decide_action(&task, &q, &PHRASES_EN, |_| panic!(
12696                "old owner must not load"
12697            )),
12698            ActionDecision::Stale
12699        );
12700    }
12701
12702    #[test]
12703    fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
12704        let mut state = crate::land::tests::repair_state(true, true);
12705        state.status = RunStatus::Landing;
12706        state.parked = true;
12707        state.driver_exited = true;
12708        let mut q = ask::Question::new(
12709            state.id.clone(),
12710            land::APPROVAL_NODE.into(),
12711            "land".into(),
12712            "Merge?".into(),
12713            String::new(),
12714            vec![land::APPROVE.into(), land::HOLD.into()],
12715        );
12716        q.id = state.id.clone();
12717        state.land_approval = Some(crate::run::LandApproval {
12718            question: q.id.clone(),
12719            head: "current-head".into(),
12720        });
12721        state.save().unwrap();
12722        land::upgrade_repair_choice(&mut q, &state);
12723        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12724        Questions::open().put(&mut q).unwrap();
12725        let tmp = tempfile::tempdir().unwrap();
12726        let queue = Queue::at(tmp.path().join("queue"));
12727        let mut task = held_task_with(&state.id);
12728        task.status = TaskStatus::Parked;
12729        queue.put(&mut task).unwrap();
12730        let empty = Arc::new(tokio::sync::Semaphore::new(0));
12731        let free = Arc::new(tokio::sync::Semaphore::new(1));
12732        assert!(claim_dispatch(&queue, &task, false, &empty, &free).is_none());
12733        assert!(claim_dispatch(&queue, &task, true, &free, &free).is_none());
12734        let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
12735        assert!(claim.permit.is_some());
12736        assert!(claim_dispatch(&queue, &task, false, &free, &free).is_none());
12737        drop(claim);
12738        Questions::open()
12739            .update(&q.id, |q| {
12740                q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
12741                Ok(())
12742            })
12743            .unwrap();
12744        let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
12745        assert!(claim.permit.is_none());
12746        assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
12747    }
12748
12749    #[test]
12750    fn decide_action_resumes_only_the_latest_resumable_run() {
12751        let t = held_task_with("r1");
12752        let q = action_question("r1", resume_action("r1"));
12753        let load = |s: RunState| move |_: &str| Ok(s);
12754        assert_eq!(
12755            decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Blocked))),
12756            ActionDecision::Resume("r1".into())
12757        );
12758        // Not the latest run of the task.
12759        let q_other = action_question("r1", resume_action("r0"));
12760        assert!(matches!(
12761            decide_action(
12762                &t,
12763                &q_other,
12764                &PHRASES_EN,
12765                load(run_state(RunStatus::Blocked))
12766            ),
12767            ActionDecision::Refuse(_)
12768        ));
12769        // A finished run cannot make progress.
12770        assert!(matches!(
12771            decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Ready))),
12772            ActionDecision::Refuse(_)
12773        ));
12774        // A released one either.
12775        let mut released = run_state(RunStatus::Blocked);
12776        released.released_to = Some("elsewhere".into());
12777        assert!(matches!(
12778            decide_action(&t, &q, &PHRASES_EN, load(released)),
12779            ActionDecision::Refuse(_)
12780        ));
12781        // Unreadable state is a refusal, never a fresh competition.
12782        assert!(matches!(
12783            decide_action(&t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
12784            ActionDecision::Refuse(_)
12785        ));
12786    }
12787
12788    #[test]
12789    fn decide_action_ignores_a_question_about_an_earlier_run() {
12790        let mut t = held_task_with("r1");
12791        t.runs.push("r2".to_owned());
12792        let never = |_: &str| -> Result<RunState> { bail!("not read") };
12793        assert_eq!(
12794            decide_action(
12795                &t,
12796                &action_question("r1", ask::ChoiceAction::Done),
12797                &PHRASES_EN,
12798                never
12799            ),
12800            ActionDecision::Stale
12801        );
12802    }
12803
12804    #[test]
12805    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
12806        let mut t = held_task_with("r1");
12807        let never = |_: &str| -> Result<RunState> { bail!("not read") };
12808        assert_eq!(
12809            decide_action(
12810                &t,
12811                &action_question("r1", ask::ChoiceAction::Requeue),
12812                &PHRASES_EN,
12813                never
12814            ),
12815            ActionDecision::Requeue
12816        );
12817        let done_q = action_question("r1", ask::ChoiceAction::Done);
12818        assert_eq!(
12819            decide_action(&t, &done_q, &PHRASES_EN, never),
12820            ActionDecision::Done
12821        );
12822        t.mark_action_applied(&done_q.id);
12823        assert_eq!(
12824            decide_action(&t, &done_q, &PHRASES_EN, never),
12825            ActionDecision::Skip
12826        );
12827
12828        // A plain answer (no action for that label) does nothing.
12829        let mut plain = action_question("r1", ask::ChoiceAction::Done);
12830        plain.actions.clear();
12831        assert_eq!(
12832            decide_action(&held_task_with("r1"), &plain, &PHRASES_EN, never),
12833            ActionDecision::Skip
12834        );
12835        // A running task is left alone.
12836        let mut running = held_task_with("r1");
12837        running.status = TaskStatus::Running;
12838        assert_eq!(
12839            decide_action(
12840                &running,
12841                &action_question("r1", ask::ChoiceAction::Done),
12842                &PHRASES_EN,
12843                never
12844            ),
12845            ActionDecision::Skip
12846        );
12847    }
12848
12849    #[test]
12850    fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
12851        crate::run::pin_test_home();
12852        for legacy in [false, true] {
12853            let dir = tempfile::tempdir().unwrap();
12854            let queue = Queue::at(dir.path().join("queue"));
12855            let questions = Questions::at(dir.path().join("questions"));
12856            let run = "20260101-000000-hold";
12857            let mut task = held_task_with(run);
12858            task.status = TaskStatus::Parked;
12859            let mut q = ask::Question::new(
12860                run.into(),
12861                land::APPROVAL_NODE.into(),
12862                "land".into(),
12863                "Repair?".into(),
12864                String::new(),
12865                vec![land::REPAIR.into()],
12866            );
12867            q.actions.insert(land::REPAIR.into(), resume_action(run));
12868            q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12869            // Deterministically order the answer before the actual manual hold.
12870            q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
12871            q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
12872            questions.put(&mut q).unwrap();
12873            task.hold_manual(Some("Keep this PR paused".into()));
12874            if legacy {
12875                task.hold_source = None;
12876            }
12877            queue.put(&mut task).unwrap();
12878
12879            apply_task_choice_actions(&queue, &questions, dir.path());
12880            let after = queue.get(&task.id).unwrap();
12881            assert!(after.operator_held());
12882            assert_eq!(after.hold_source, task.hold_source);
12883            assert_eq!(after.operator_decided_at, task.operator_decided_at);
12884            assert_eq!(after.runs, task.runs);
12885            assert_eq!(after.instruction, task.instruction);
12886            assert!(after.resume_override.is_none());
12887            assert!(after.action_applied(&q.id));
12888            let reason = after.hold_reason.as_deref().unwrap();
12889            assert!(reason.starts_with("Keep this PR paused"));
12890            assert!(reason.contains("later operator decision"));
12891            assert!(reason.contains(&format!("magi task release {}", task.id)));
12892
12893            for recovery in [
12894                crate::conduct::Recovery::Review,
12895                crate::conduct::Recovery::Requeue,
12896            ] {
12897                crate::conduct::apply(
12898                    &queue,
12899                    &questions,
12900                    &crate::conduct::Verdict {
12901                        decisions: vec![crate::conduct::Decision {
12902                            id: task.id.clone(),
12903                            recovery: Some(recovery),
12904                            ..Default::default()
12905                        }],
12906                    },
12907                )
12908                .unwrap();
12909            }
12910            // Reconciliation is idempotent, and automatic recovery cannot
12911            // reopen this owner after it observes the rejected repair answer.
12912            apply_task_choice_actions(&queue, &questions, dir.path());
12913            let still_held = queue.get(&task.id).unwrap();
12914            assert!(still_held.operator_held());
12915            assert_eq!(still_held.hold_reason, after.hold_reason);
12916            assert_eq!(still_held.runs, task.runs);
12917            assert!(still_held.review_branch.is_none());
12918            assert!(!still_held.fresh_start);
12919            assert!(queue.next_runnable().is_none());
12920        }
12921    }
12922
12923    #[test]
12924    fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
12925        for held in [false, true] {
12926            for retry in [false, true] {
12927                let dir = tempfile::tempdir().unwrap();
12928                let queue = Queue::at(dir.path().join("queue"));
12929                let questions = Questions::at(dir.path().join("questions"));
12930                let home = dir.path().join("home");
12931                let mut t = task();
12932                if held {
12933                    t.hold_machine(Some("driver state unknown".into()));
12934                }
12935                queue.put(&mut t).unwrap();
12936                let verdict = serde_json::from_value(serde_json::json!({
12937                    "decisions": [{
12938                        "id": t.id,
12939                        "question": "Driver state unknown; retry the checks or hold?",
12940                        "choices": ["daemon: recheck and retry", "daemon: hold the task"],
12941                        "actions": {
12942                            "daemon: recheck and retry": {"do": "requeue"},
12943                            "daemon: hold the task": {"do": "hold"}
12944                        }
12945                    }]
12946                }))
12947                .unwrap();
12948                crate::conduct::apply(&queue, &questions, &verdict).unwrap();
12949                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
12950                let mut q = questions.list().pop().unwrap();
12951                let choice = if retry {
12952                    "daemon: recheck and retry"
12953                } else {
12954                    "daemon: hold the task"
12955                };
12956                assert_eq!(q.actions.len(), 2);
12957                q.answer(ask::Answer::Choice(choice.into())).unwrap();
12958                questions.put(&mut q).unwrap();
12959
12960                // A Web answer does not remove the deputy's fresh lease.
12961                questions.beat(&q.id, ask::WaiterKind::Deputy);
12962                for _ in 0..2 {
12963                    resolve_blockers(&queue, &questions);
12964                    apply_task_choice_actions(&queue, &questions, &home);
12965                    let waiting = queue.get(&t.id).unwrap();
12966                    assert_eq!(waiting.status, TaskStatus::Blocked);
12967                    assert_eq!(waiting.blocked_by, [q.id.clone()]);
12968                    assert!(waiting.answers.is_empty());
12969                    assert!(!waiting.action_applied(&q.id));
12970                    assert!(runnable(&queue).is_empty());
12971                    let free = Arc::new(tokio::sync::Semaphore::new(1));
12972                    assert!(claim_dispatch(&queue, &t, false, &free, &free).is_none());
12973                }
12974                std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
12975
12976                // Releasing the blocker and applying the operation share one save.
12977                resolve_blockers(&queue, &questions);
12978                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
12979                apply_task_choice_actions(&queue, &questions, &home);
12980                let after = queue.get(&t.id).unwrap();
12981                assert_eq!(
12982                    after.status,
12983                    if retry {
12984                        TaskStatus::Queued
12985                    } else {
12986                        TaskStatus::Held
12987                    }
12988                );
12989                assert!(after.action_applied(&q.id));
12990                assert_eq!(after.operator_held(), !retry);
12991                assert_eq!(after.answers.len(), 1);
12992
12993                // A later operator decision must not replay this answer.
12994                let mut changed = after;
12995                if retry {
12996                    changed.hold_manual(Some("later hold".into()));
12997                } else {
12998                    changed.release_operator("test", None);
12999                }
13000                let expected = changed.status;
13001                queue.put(&mut changed).unwrap();
13002                apply_task_choice_actions(&queue, &questions, &home);
13003                assert_eq!(queue.get(&t.id).unwrap().status, expected);
13004            }
13005        }
13006    }
13007
13008    #[test]
13009    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
13010        let dir = tempfile::tempdir().unwrap();
13011        let queue = Queue::at(dir.path().join("queue"));
13012        let questions = Questions::at(dir.path().join("questions"));
13013        let home = dir.path().join("home");
13014        let mut state = run_state(RunStatus::Blocked);
13015        state.id = "20260101-000000-act1".to_owned();
13016        state.save_under(&home).unwrap();
13017
13018        let mut t = held_task_with(&state.id);
13019        queue.put(&mut t).unwrap();
13020        let mut q = action_question(&state.id, resume_action(&state.id));
13021        questions.put(&mut q).unwrap();
13022
13023        apply_task_choice_actions(&queue, &questions, &home);
13024        let after = queue.get(&t.id).unwrap();
13025        assert_eq!(after.status, TaskStatus::Queued);
13026        assert!(!after.fresh_start);
13027        assert!(after.action_applied(&q.id));
13028        let pin = after.resume_override.clone().unwrap();
13029        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
13030        assert!(pin.forced);
13031
13032        // Held again later: the same answer does not release it a second time.
13033        let mut again = queue.get(&t.id).unwrap();
13034        again.hold_machine(Some("later".into()));
13035        queue.put(&mut again).unwrap();
13036        apply_task_choice_actions(&queue, &questions, &home);
13037        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13038    }
13039
13040    #[test]
13041    fn a_delivered_answer_is_still_acted_on_exactly_once() {
13042        let dir = tempfile::tempdir().unwrap();
13043        let queue = Queue::at(dir.path().join("queue"));
13044        let questions = Questions::at(dir.path().join("questions"));
13045        let home = dir.path().join("home");
13046        let mut state = run_state(RunStatus::Blocked);
13047        state.id = "20260101-000000-act2".to_owned();
13048        state.save_under(&home).unwrap();
13049
13050        let mut t = held_task_with(&state.id);
13051        queue.put(&mut t).unwrap();
13052        let mut q = action_question(&state.id, resume_action(&state.id));
13053        q.answer_delivered = true;
13054        questions.put(&mut q).unwrap();
13055
13056        // Delivered, and the agent then died: the task is still held, so the
13057        // chosen action applies.
13058        apply_task_choice_actions(&queue, &questions, &home);
13059        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
13060        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
13061
13062        // Held again: the same answer does nothing a second time.
13063        let mut again = queue.get(&t.id).unwrap();
13064        again.hold_machine(Some("later".into()));
13065        queue.put(&mut again).unwrap();
13066        apply_task_choice_actions(&queue, &questions, &home);
13067        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13068    }
13069
13070    #[test]
13071    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
13072        let dir = tempfile::tempdir().unwrap();
13073        let queue = Queue::at(dir.path().join("queue"));
13074        let questions = Questions::at(dir.path().join("questions"));
13075        let home = dir.path().join("home");
13076        let mut state = run_state(RunStatus::Blocked);
13077        state.id = "20260101-000000-act3".to_owned();
13078        state.save_under(&home).unwrap();
13079        let mut t = held_task_with(&state.id);
13080        queue.put(&mut t).unwrap();
13081        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
13082        questions.put(&mut q).unwrap();
13083
13084        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
13085        apply_task_choice_actions(&queue, &questions, &home);
13086        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13087
13088        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
13089        apply_task_choice_actions(&queue, &questions, &home);
13090        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
13091    }
13092
13093    #[test]
13094    fn action_standing_tells_the_reasons_apart() {
13095        let mut t = held_task_with("r1");
13096        let q = action_question("r1", ask::ChoiceAction::Requeue);
13097        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
13098        let mut plain = q.clone();
13099        plain.actions.clear();
13100        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
13101
13102        // Applied wins over everything, even a running task.
13103        t.mark_action_applied(&q.id);
13104        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
13105
13106        // A newer attempt running: the old question is Stale, not Busy.
13107        let mut t = held_task_with("r1");
13108        t.start("r2".to_owned());
13109        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
13110        // The same question about the latest run just waits.
13111        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
13112        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
13113        t.status = TaskStatus::Blocked;
13114        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
13115
13116        // A conductor question is keyed by the task, never stale.
13117        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
13118        c.node = crate::conduct::NODE.to_owned();
13119        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
13120        assert!(!ActionStanding::Busy.daemon_owns());
13121    }
13122
13123    #[test]
13124    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
13125        let dir = tempfile::tempdir().unwrap();
13126        let queue = Queue::at(dir.path().join("queue"));
13127        let questions = Questions::at(dir.path().join("questions"));
13128        let home = dir.path().join("home");
13129        let mut state = run_state(RunStatus::Blocked);
13130        state.id = "20260101-000000-act4".to_owned();
13131        state.save_under(&home).unwrap();
13132        let mut t = held_task_with(&state.id);
13133        t.status = TaskStatus::Running;
13134        queue.put(&mut t).unwrap();
13135        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
13136        q.cwd = Some(dir.path().display().to_string());
13137        questions.put(&mut q).unwrap();
13138
13139        // While the task runs the daemon will not act, so the waiter still
13140        // delivers the word to the dead asker's seat ...
13141        let running = queue.get(&t.id).unwrap();
13142        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
13143        assert!(matches!(
13144            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
13145            crate::waiter::Action::Deliver(_)
13146        ));
13147        // ... and the daemon waits while the task runs, then applies once.
13148        apply_task_choice_actions(&queue, &questions, &home);
13149        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
13150        let mut back = queue.get(&t.id).unwrap();
13151        back.hold_machine(Some("later".into()));
13152        queue.put(&mut back).unwrap();
13153        apply_task_choice_actions(&queue, &questions, &home);
13154        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
13155        let mut again = queue.get(&t.id).unwrap();
13156        again.hold_machine(Some("again".into()));
13157        queue.put(&mut again).unwrap();
13158        apply_task_choice_actions(&queue, &questions, &home);
13159        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13160    }
13161}